【问题标题】:R: Is there an efficient way to perform groupBy on one column and sum another column?R:有没有一种有效的方法来对一列执行 groupBy 并对另一列求和?
【发布时间】:2014-04-01 03:37:03
【问题描述】:

我正在尝试使用 R 处理两列。

我希望能够按第 1 列分组,但合计值为 2。

col1 col2
A    3
B    2
A    5
B    1
B    4

示例结果应该是:

A    8
B    7

我已经查看了“aggregate”、“summaryBy”和“by”两者,但我缺少一些东西,因为我没有得到想要的输出。

任何帮助将不胜感激......

【问题讨论】:

    标签: r aggregate plyr


    【解决方案1】:

    考虑到您的数据被称为dat,然后使用aggregate,它对我有用

    > aggregate(.~col1, FUN="sum", data=dat )
      col1 col2
    1    A    8
    2    B    7
    

    更多示例see this post

    【讨论】:

      【解决方案2】:

      data.table是你的朋友!

      更多信息http://datatable.r-forge.r-project.org/

      library(data.table)
      dt <- data.table(your_dataframe,key="col1")
      dt[,list(col2=sum(col2)),by="col1" ]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-11-06
        • 1970-01-01
        • 2011-07-28
        • 2022-01-25
        • 1970-01-01
        • 1970-01-01
        • 2021-05-16
        相关资源
        最近更新 更多