Similar to an earlier question, I would like to add multiple columns to a data.table with just one function call. However, my function doesn't just return one number, as in mean(), but rather an entire vector, as in scale() or cat(). Does anybody know how to do that?
The following works without problems:
library(data.table)
x <- data.table(a=1:3,b=1:6)
f <- function(b) {
d = mean(b) * 2
list("hi", "hello",d)
}
x[,c("col1","col2","col3"):=f(b), by=a][]
But when I replace the mean in my function by e.g. scale(), I get an Error and a friendly advice but I don't know what to make of it:
x <- data.table(a=1:3,b=1:6)
f <- function(b) {
d = scale(b) * 2
list("hi", "hello",d)
}
x[,c("col1","col2","col3"):=f(b), by=a][]
Error in
`[.data.table`(x, , `:=`(c("col1", "col2", "col3"), f(b)), by = a)
:All items in j=list(...) should be atomic vectors or lists. If you are trying something like j=list(.SD,newcol=mean(colA)) then use := by group instead (much quicker), or cbind or merge afterwards.