I want to get for each group the frequencies of the values of a factor/categorial variable.
The following does not work:
library(data.table)
dt<-data.table(fac=c("l1","l1","l2"),grp=c("A","B","B"))
dt[,fac:=as.factor(fac)]
dt[,list( table(fac) ),by=grp]
The error message is:
Error in `[.data.table`(dt, , list(table(fac)), by = grp) :
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.
Is there an easy way to accomblish this task? Thanks.