r - data.table 中按组划分的频率表 (R)

标签 r data.table

我想获取每个组的因子/类别变量值的频率。

以下方法不起作用:

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/

相关文章:

r - 在 r 中的非等值连接期间,从 data.table 中按组提取条件数据的有效方法

r - 与 data.table 连接的排列

r - 在 R 中创建空间集群 LISA map

r - 让 Emacs 忽略 Sweave 文档中\Sexpr{} 命令的内容,以防止错误的基于 $ 的语法突出显示

r - 从由 "-"分隔的字符串中提取数字及其符号

r - R 中的温度曲线

r - 根据另一个 data.table 的行提取 data.table 的行

r - 为什么排序比 R 中的排序函数慢?

r - data.table 更新对非等价自联接的奇怪行为

r - 轻松检查目标是否记录在其他变量中?