我有类似的数据:
number_of_runs <- 4
r1 <- c(1,2,3)
r2 <- c(4,5,6)
r3 <- c(7,8,9)
r4 <- c(10,11,12)我通常有不同的运行次数(在一个名为r1的向量中保存为第一次运行的三个数字,第二次运行的名为r2等)。我想将这些向量组合到一个data.table中,但是由于运行的次数不同,我需要通过编程来实现这一点。
如下所示,对于一定数量的运行,输出dt完全符合我的需要:
dt <- data.table(r1,r2,r3,r4) 我需要一些类似于下面的内容,但这实际上是可行的:
dt <- data.table(c(paste0("r", 1:number_of_runs)))因此,如果有3次运行,它将输出类似于data.table的data.table(r1,r2,r3),如果有4次运行,它将输出像data.table(r1,r2,r3,r4)这样的data.table等等。
我在一台Windows7机器上使用data.table版本1.10.4。我很感激你在这方面的想法。
发布于 2017-02-15 17:29:07
正如@MrFlick所指出的,如果将r*矢量存储在更好的格式中,就会简单得多。例如,可以将它们直接放入data.table中。或者,如果它们在一个名为rList的列表中,那么您的回答就是使用as.data.table(rList)。所以你真的需要重新评估你是如何创建这些变量的。请与我们分享这段代码!
但是,为了完整起见,有一种方法可以做到您所要求的:从变量的字符向量开始,并将变量与当前环境中的名称组合到一个data.table中。
library(data.table)
# say we must start with these vectors flaoting around the global environment
r1 <- c(1,2,3)
r2 <- c(4,5,6)
r3 <- c(7,8,9)
r4 <- c(10,11,12)
number_of_runs <- 4
# collect their names in a character vector as you have done:
rNames <- paste0("r", 1:number_of_runs)
# collapse them into one string
rNamesCollapsed <- paste(rNames, collapse = ", ")
# form the command we need to switch to create the data.table, still as a character vector:
commandString <- paste0("data.table(", rNamesCollapsed , ")")
# parse the character vector command into an R expression:
commandExpr <- parse(text = commandString)
# evaluate the expression to get the data.table:
dt <- eval(commandExpr )我不推荐您这样做,我只想包括这个示例,以帮助您理解表达式和字符向量之间的差异,从而理解为什么您的方法不起作用。
显然,所有的代码都可以被缩短,但是我想要分析一下正在发生的事情。正如@Roland建议的那样,一种更短、更好的方法是使用mget,它直接搜索具有给定名称的变量,并在适当命名的列表中返回这些变量。
# collect their names in a character vector as you have done:
rNames <- paste0("r", 1:number_of_runs)
# search the environment for objects with those names, and put them into a list:
rList <- mget(rNames)
# convert the list to a data.table:
dt <- as.data.table(rList)https://stackoverflow.com/questions/42255834
复制相似问题