【问题标题】:Count number of times a value increases in a column计算列中值增加的次数
【发布时间】:2014-11-14 00:05:38
【问题描述】:

我在 R 中有一个如下所示的数据框:

person  purch_date   num_purchased
Alex    2011-01-01   6
Alex    2011-06-05   5
Alex    2012-03-04   6
Beth    2011-02-04   7
Beth    2012-05-21   8
Beth    2013-11-11   10
Candy   2007-08-09   3
Candy   2009-10-01   2
Candy   2013-12-02   2

我首先按“person”排序,然后按“purch_date”排序。

我正在尝试计算每个人的“购买数量”列中增加了多少。我知道用于计算列的唯一值数量或值更改次数的代码,但这不是我想要的,因为我只想知道值从一个日期到下一个日期增加了多少次。理想情况下,输出如下所示:

person  num_increases
Alex    1
Beth    2
Candy   0

【问题讨论】:

    标签: r count


    【解决方案1】:

    这是一个 data.table 方法,它只会给你结果 增加 > 0,即那些 = 0 将不会被制成表格。虽然 FYR

    library(data.table)
    setDT(df)  ## set your data frame as data table
    df[, diff(num_purchased), by=person][V1>0, .N, by=person]
    #    person N
    # 1:   Alex 1
    # 2:   Beth 2
    

    编辑。

    合并@Arun 的评论。更紧凑并获得“0”计数。

    df[, sum(diff(num_purchased) > 0), by=person]
    #    person V1
    # 1:   Alex  1
    # 2:   Beth  2
    # 3:  Candy  0
    

    【讨论】:

      【解决方案2】:

      您可以使用 aggregate 在 1-liner 中获取所需格式的数据:

      aggregate(num_purchased~person, data=dat, function(x) sum(diff(x) > 0))
      #   person num_purchased
      # 1   Alex             1
      # 2   Beth             2
      # 3  Candy             0
      

      如果您更喜欢输出的命名向量,我会建议 tapply,如 Richard Scriven 的回答中所述。

      【讨论】:

        【解决方案3】:

        如果你想要一个向量,你可以使用tapplydf 是您的原始数据。

        foo <- function(x) sum(diff(x) > 0)
        
        with(df, tapply(num_purchased, person, foo))
        # Alex  Beth Candy 
        #    1     2     0 
        

        或使用dplyr 并仍在使用foo

        library(dplyr)
        group_by(df, person) %>% summarize(increases = foo(num_purchased))
        #   person increases
        # 1   Alex         1
        # 2   Beth         2
        # 3  Candy         0
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-10-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-27
          相关资源
          最近更新 更多