简体   繁体   English

通过动态选择名称来组合多个数据框

[英]Combine multiple dataframes by selecting names dynamically

I received a script that generates a bunch of objects. 我收到了一个生成一堆对象的脚本。 I want to combine multiple dataframes using bind_rows. 我想使用bind_rows合并多个数据框。 I am able to choose the correct objects using grep but I am not able to pass those object names as argument to bind_rows. 我可以使用grep选择正确的对象,但无法将这些对象名称作为参数传递给bind_rows。

For example, I want to select the objects that start with df and pass those to bind_rows. 例如,我要选择以df开头的对象并将其传递给bind_rows。 In the example below I expect to have a dataframe named data which have the dataframe mtcars 3 times. 在下面的示例中,我希望有一个名为data的数据mtcars ,该数据mtcars次数为3次。

df1 <- mtcars
df2 <- mtcars
df3 <- mtcars
notdf4 <- mtcars
dfx <- ls()[grep("^df", ls())]
data <- bind_rows(eval(parse(text = dfx)))

The suggestion to use mget makes sense, although it returns a list so you would need to use do.call to execute an `rbind operation. 使用mget的建议很有意义,尽管它返回一个列表,所以您将需要使用do.call来执行`rbind操作。

str( do.call( rbind, mget(ls( patt="^df.") ) )  )
'data.frame':   96 obs. of  11 variables:
 $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
 $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
 $ disp: num  160 160 108 258 360 ...
 $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
 $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 $ qsec: num  16.5 17 18.6 19.4 17 ...
 $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
 $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
 $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
 $ carb: num  4 4 1 1 2 1 4 2 2 4 ...

I think using mget and do.call (rather than will have a lower chance of offending people like me who might be called R purists. I chose to use the "pattern" argument to ls as cleaner than first getting all the workspace names and then selecting from them with grep. 我认为使用mgetdo.call (而不是冒犯像我这样的人的机会较小,这些人可能被称为R纯粹主义者。我选择使用ls作为更清洁的“模式”参数,而不是首先获取所有工作区名称,然后再使用用grep从中选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM