如何在 R 中按因素级别对变量求和?


我们可以通过使用聚合函数或采用 tapply 来实现此目的

实例

> x <- data.frame(Category=factor(c("Graduation", "Graduation", "Post-Graduation",
"Graduation","PhD", "Post-Graduation", "PhD")),
Frequency=c(12,19,15,20,25,13,14))
> x
Category Frequency
1 Graduation 12
2 Graduation 19
3 Post-Graduation 15
4 Graduation 20
5 PhD 25
6 Post-Graduation 13
7 PhD 14

使用聚合

> aggregate(x$Frequency, by=list(Group=x$Category), FUN=sum)
    Group x
1 Graduation 51
2 PhD 39
3 Post-Graduation 28
Using tapply
> tapply(x$Frequency, x$Category, FUN=sum)
Graduation PhD Post-Graduation
51         39      28

更新日期:2020 年 7 月 6 日

2 千+浏览量

开创 职业生涯

完成课程可获得认证

开始学习
广告