I know this question description may be a bit vague, forgive my broken English.
I want to add multiple columns in data.table, the common practice is:
DT[,c('col1.m','col2.m'):=map(.SD,mean),.SDcols = c('col1','col2')],
but this doesn't solve my problem because I have multiple values in each column in my dt, the example is as follows.
x <- list(c(1,2),c(3,4),c(5,6)) y <- list(c(20,10),c(40,30),c(60,50)) dt <- data.table(x,y)
dt[,c('x.m','y.m'):=map(.SD,mean),.SDcols = c('x','y')]
I use the code as above and get all the results as NA
1: In mean.default(.x[[i]], ...) :
argument is not numeric or logical: returning NA
I guess here I might need nested map functions, the first map is used to calculate the mean value (or some other function) for each element in the list, the second map applies the above process to the other columns in the .SDcols.
I've tried to implement the above process using the 'unnest' function as well as 'by' in data.table, but I'm wondering if there is a more direct way to do it.
The final desired result
- List item