2

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.

Funkwecker
  • 766
  • 13
  • 22

1 Answers1

4

We can use dcast and bypass the second and third line of OP's code.

dcast(dt, grp~fac, length)
#   grp l1 l2
#1:   A  1  0
#2:   B  1  1
akrun
  • 874,273
  • 37
  • 540
  • 662