且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何按组对变量求和

更新时间:2022-12-14 15:19:07

使用聚合

aggregate(x$Frequency, by=list(Category=x$Category), FUN=sum)
  Category  x
1    First 30
2   Second  5
3    Third 34






在上面的示例中,多次暗淡可以在列表中指定。可以通过 cbind 合并同一数据类型的多个聚合指标:


In the example above, multiple dimensions can be specified in the list. Multiple aggregated metrics of the same data type can be incorporated via cbind:

aggregate(cbind(x$Frequency, x$Metric2, x$Metric3) ...






(嵌入@thelatemail评论),汇总也具有公式界面

aggregate(Frequency ~ Category, x, sum)

或如果要聚合多个列,则可以使用表示法(也适用于一列)

Or if you want to aggregate multiple columns, you could use the . notation (works for one column too)

aggregate(. ~ Category, x, sum)






tapply

tapply(x$Frequency, x$Category, FUN=sum)
 First Second  Third 
    30      5     34 






使用此数据:


Using this data:

x <- data.frame(Category=factor(c("First", "First", "First", "Second",
                                      "Third", "Third", "Second")), 
                    Frequency=c(10,15,5,2,14,20,3))