乱世@小熊 2009-11-02 09:01 采纳率: 25%
浏览 274
已采纳

如何求变数之和?

Let's say I have two columns of data. The first contains categories such as "First", "Second", "Third", etc. The second has numbers which represent the number of times I saw "First".

For example:

Category     Frequency
First        10
First        15
First        5
Second       2
Third        14
Third        20
Second       3

I want to sort the data by Category and sum the Frequencies:

Category     Frequency
First        30
Second       5
Third        34

How would I do this in R?

转载于:https://stackoverflow.com/questions/1660124/how-to-sum-a-variable-by-group

  • 写回答

10条回答 默认 最新

  • 衫裤跑路 2009-11-02 12:52
    关注

    Using aggregate:

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

    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) ...
    

    (embedding @thelatemail comment), aggregate has a formula interface too

    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)
    

    or 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))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(9条)

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 如何将下列的“无限压缩存储器”设计出来
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口