【问题标题】:Fill an empty data.table in R by columns按列填充 R 中的空 data.table
【发布时间】:2018-07-31 10:50:41
【问题描述】:

有没有办法在 R 中填充一个完全空的data.table?我必须填写data.table,列由循环中调用的函数给出。在启动函数之前,我不知道将创建多少列或它们的长度,但我知道所有列的长度都相同。

我的方法是创建一个空的 data.table 并在循环中填充它。但这不起作用,因为我无法将列附加到空 data.table 或因为我无法正确插入行。检查下面的玩具示例(为简单起见,我们避免使用for bucle)

 f <- someFunction() # just imagine that returns c(1,2,3)

 # this does not work. fails with error msg:  Cannot use := to add columns to a null data.table (no columns), currently
 dt <- data.table()
 dt[, c("b", "c") := list(f(), f())]

 # this actually work. But creates a 0 row data.table which cannot be filled latter
 dt <- data.table(a = numeric() )
 dt[, c("b", "c") := list(numeric(), numeric())]
 dt[, c("b", "c") := list(f(), f())] # no rows are added

 # this workaround works but is ugly as hell 
 dt <- data.table(a = rep(NA, length(f())) )
 dt[, c("b", "c") := list(f(), f())]
 dt[, a := NULL]

那么有什么优雅/有效的方法来解决这个问题

【问题讨论】:

  • 您是否考虑过先将数据存储在列表中,然后在最后转换为 data.table。
  • f &lt;- function() c(1,2,3); L &lt;- list(f(), f()); setDT(L); setnames(L, c("b", "c"))
  • @snoram 我已经考虑过了,但是data.table(list) 按行填充data.table 并且转置无法正常工作。 @jogo 解决方案似乎工作正常!
  • @DavidArenburg 请阅读整个问题。在示例中,为了简单起见,我使用 c("b", "c"),但实际上是在 for 循环中生成的。

标签: r data.table


【解决方案1】:

你可以这样使用:

library("data.table")   

f <- function(x) c(1,2,3)

dt <- as.data.table(lapply(11:13, f))
setnames(dt, c("a", "b", "c"))

lapply() 正在执行您在问题中提到的循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    • 2019-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-03
    相关资源
    最近更新 更多