I want to compute the mean of several columns for each group, but the columns should be given as a vector of names:
library(data.table)
DT <- data.table(k=c(1,1,2,2,2),v=1:5,w=11:15,key="k")
DT[,list(N=.N,v=mean(v),w=mean(w)),by="k"]
k N v w
1: 1 2 1.5 11.5
2: 2 3 4.0 14.0
However, I don't want to specify v
and w
explicitly when computing means.
I have another variable
mycols <- c("v","w")
which should be used instead of explicit column names.
I tried various versions of
DT[,list(.N,colMeans(.SD[mycols])),by="k"]
and got
Error in `[.data.table`(.SD, mycols) :
I wonder if there is a way to do it...