[英]Fill an empty data.table in R by columns
有沒有辦法在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]
那么是否有任何優雅/有效的方法來解決這個問題
您可以使用如下形式:
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()
正在執行您在問題中提到的循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.