我想获取每个组的因子/类别变量值的频率。
以下方法不起作用:
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]
错误信息是:
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.
有没有简单的方法来完成这个任务?谢谢。
最佳答案
我们可以使用dcast
并绕过OP代码的第二行和第三行。
dcast(dt, grp~fac, length)
# grp l1 l2
#1: A 1 0
#2: B 1 1
关于r - data.table 中按组划分的频率表 (R),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38941380/