简体   繁体   中英

Fill an empty data.table in R by columns

Is there any way to fill a completely empty data.table in R? I have to fill a data.table and columns are given by a function called in a loop. I don't know how many columns will be created or what length they will be before launching the function but I do know that all will be the same length.

My aproach is to create an empty data.table and fill it within the loop. But this does not work either because I cannot append columns to empty data.table or beacuse I cannot insert rows properly. Check the toy example below (for the sake of simplicity let's avoid the 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]

So Is there any elegant/efficient way of approaching this

You can use something like this:

library("data.table")   

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

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

The lapply() is doing the loop you mentioned in your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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