2017-10-06 23 views
0

对于我来说,我无法弄清楚如何通过我的列表lapply来grep列名。如何使用lapply与grep删除列表中的列

下面是一个数据帧作品代码:

tl1 <- trend1[,grep("Date|AIR|LSL",colnames(trend1))] 

但我有trend1通过trend12。我如何将它变成一个列表并将这个grep应用于列表的每个元素以获得tl1到t12的数据帧?

或者,我会愿意使用for循环。

+0

假设你已经将trend1设置为12,那么'lapply(list_of_dfs,function(df)df [,grep(“Date | AIR | LSL”,colnames(df))])'应该这样做。 – Abdou

回答

0

假设你已经有trend1通过trend12数据帧中的[R的环境中,你可以把他们都在一个列表,然后使用lapply删除列,你并不需要:

# mget gets the dataframes whose names are returned by ls 
list_of_dfs <- mget(ls(pattern="trend\\d{1,2}")) 

# loop through the dataframes and make the changes 
new_dfs <- lapply(list_of_dfs, function(df) df[,grep("Date|AIR|LSL",colnames(df))]) 

我希望这有助于。