R 如何通过组合编程命名的向量来创建data.table?
我有类似的数据:R 如何通过组合编程命名的向量来创建data.table?,r,data.table,R,Data.table,我有类似的数据: number_of_runs <- 4 r1 <- c(1,2,3) r2 <- c(4,5,6) r3 <- c(7,8,9) r4 <- c(10,11,12) 我需要类似于以下内容的东西,但实际上是可行的: dt <- data.table(c(paste0("r", 1:number_of_runs))) dt正如@MrFlick所指出的,如果r*向量以更好的格式存储,则会简单得多。例如,它们可以直接放入data.table中。或
number_of_runs <- 4
r1 <- c(1,2,3)
r2 <- c(4,5,6)
r3 <- c(7,8,9)
r4 <- c(10,11,12)
我需要类似于以下内容的东西,但实际上是可行的:
dt <- data.table(c(paste0("r", 1:number_of_runs)))
dt正如@MrFlick所指出的,如果r*
向量以更好的格式存储,则会简单得多。例如,它们可以直接放入data.table中。或者,如果它们在一个名为sayrList
的列表中,那么您的答案就是使用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 )
4个r*
向量来自哪里?用相关信息构建不同的变量并不是最好的方法。这些可能应该在一个列表中,使事情更容易处理。但是您遇到的问题是,无法用字符值(即paste0()
返回的值)替换符号(没有引号的东西)。那么,您首先是如何创建它们的呢?您是否运行了一些函数4次?我认为像r绑定行这样的东西在这里更有意义。我的意思是每次运行都应该是结果中的一行。从MrFlick的r
list开始:rbindlist(lappy(r,函数(x)as.data.table(as.list(x)))
。你现在把每一次跑步都放在自己的专栏里,这在R中是适得其反的…@Frank非常感谢。我现在明白了。对解析文本进行向下表决。如果您有这样的向量,请使用mget将它们收集到一个列表中,然后从列表中继续。我看不出他们要求解析文本的位置,您当然不应该建议。他们尝试在这行中执行:dt如果您认为任何引用parse
和eval
都应该删除,请随意删除该解决方案以改进我的答案。@mb7744非常感谢您在这方面所做的工作。因为最终需要以广泛的格式输出此信息,所以您关于mget
的建议非常有效。下面是我最终使用的,它完全按照要求执行:dt
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 )
# 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)