表()在R中分组

table() by group in R

示例数据:

a <- sample(1:4, 100, replace = T)
b <- sample(0:1, 100, replace = T)

d <- data.frame(a, b)

我想为 a 的所有级别自动实现此输出:

table(d$b[d$a==1])
table(d$b[d$a==2])
table(d$b[d$a==3])
table(d$b[d$a==4])

我可以做一个 for 循环,但这不符合 R 的精神。

for (i in unique(d$a)) {
print(table(d$b[d$a==i]))
}

相反,我想使用 R 中的众多列表函数之一。 我尝试使用 plyr 包中的 ddply

ddply(d, ~a, function(x) table(b))

但这与 table(d$b) 重复四次相同。

如何使用列表函数将 table() 函数应用于 a 中的每个组,最好是 ddply

您可以将 table 与多个参数一起使用:

table(d$a,d$b)

     0  1
  1 15 10
  2  6 16
  3 13 10
  4 20 10

或者,如果您只有要在 data.frame 中制表的数据,它会在您传入 data.frame 时为您处理:

table(d)
   b
a    0  1
  1 15 10
  2  6 16
  3 13 10
  4 20 10