【问题标题】:Add column with order counts添加包含订单计数的列
【发布时间】:2015-09-09 03:24:00
【问题描述】:

如何在我的数据框中添加一列来说明另一列中某个值出现的顺序计数?这就是我想要的结果:

   Fruit orderCount
1 Orange          1
2 Banana          1
3 Orange          2
4  Apple          1
5 Orange          3
6 Banana          2

对于 Fruit 列中值的第一次观察,我希望对应的 orderCount 为 1,第二次观察为 2,依此类推。

感谢您的帮助。

【问题讨论】:

    标签: r


    【解决方案1】:

    你可以试试我的“splitstackshape”包中的getanID

    library(splitstackshape)
    getanID(mydf, "Fruit")
    #     Fruit .id
    # 1: Orange   1
    # 2: Banana   1
    # 3: Orange   2
    # 4:  Apple   1
    # 5: Orange   3
    # 6: Banana   2
    

    在基础 R 中,您可以使用 aveseq_along 作为聚合函数。

    【讨论】:

    • 是的,太棒了。谢谢。
    【解决方案2】:

    你可以使用dplyr:

    library(dplyr)
    dat %>% group_by(Fruit) %>%
            mutate(id = row_number())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-19
      • 2019-04-02
      • 2016-05-28
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 2022-07-11
      • 2021-09-04
      相关资源
      最近更新 更多