简体   繁体   English

如何使用字符变量来引用 R 中的 data.frame?

[英]How to use a character variable to refer to a data.frame in R?

I have a dynamic number of data.frames depending on input - n_tables.我有一个动态数量的 data.frames,具体取决于输入 - n_tables。

n_tables = 5 ## This may vary between 3 to 12
for(i in 1:n_tables){
    assign(paste0("r", i),data.frame(X = c("a","b","c"),Y = runif(3,0,10)))
}

Now, I need to put all these data.frames in a list and subset them.现在,我需要将所有这些 data.frames 放在一个列表中并对它们进行子集化。 I have tried the below code but not working -我试过下面的代码但没有工作 -

t <- paste0("r",1:n_tables)
p <-lapply(t,function(x){(x[x$X == "a",])})

Thank you in advance.先感谢您。

You can use get() to fetch the object, ie,您可以使用get()来获取对象,即,

p <-lapply(t,function(x){x <- get(x);x[x$X == "a",]})

such that以至于

> p
[[1]]
  X        Y
1 a 5.550481

[[2]]
  X        Y
1 a 5.365116

[[3]]
  X        Y
1 a 5.783017

[[4]]
  X        Y
1 a 2.782952

[[5]]
  X        Y
1 a 2.123357

We get the objects into a list with mget , loop over the list with map and filter the rows from the column 'X'我们使用mget将对象放入一个list ,使用map遍历list并从“X”列中filter

library(purrr)
library(dplyr)
map(mget(t), ~ .x %>% 
                   filter(X == "a"))

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

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