【问题标题】:auto cumulative calculation in a column R列 R 中的自动累积计算
【发布时间】:2014-07-22 06:56:30
【问题描述】:

我有如下数据集

 >df
  id time  cycle
  1   0    1
  1   5    NA
  2   0    1
  2   10   NA
  2   20   NA
  3   0    0
  3   2    NA
  3   5    NA
  3   8    NA
  3   15   NA
  4   0    1
  ......

我想让所有NA 自动累积到下一个 ID,如下所示:

 >df.new
  id time  cycle
  1   0    1
  1   5    2
  2   0    1
  2   10   2
  2   20   3
  3   0    1
  3   2    2
  3   5    3
  3   8    4
  3   15   5
  4   0    1
  ......

应该有一种简单的方法可以在 R 中对其进行编码。请分享您的想法。谢谢!

【问题讨论】:

    标签: r count autofill


    【解决方案1】:
    df$cycle <- with(df, ave(cycle, id, FUN=seq_along))
    df$cycle
     #[1] 1 2 1 2 3 1 2 3 4 5 1
    

    或者

    sequence(tabulate(df$id)) #if IDs are in order
    # [1] 1 2 1 2 3 1 2 3 4 5 1
    

    【讨论】:

      【解决方案2】:

      dplyr

      require(dplyr)
      df %>% group_by(id) %>% mutate(cycle = seq_along(id))
      
        id time cycle
      1   1    0     1
      2   1    5     2
      3   2    0     1
      4   2   10     2
      5   2   20     3
      6   3    0     1
      7   3    2     2
      8   3    5     3
      9   3    8     4
      10  3   15     5
      11  4    0     1
      

      【讨论】:

        【解决方案3】:

        data.table

        library(data.table)
        setDT(df)[, cycle := seq_len(.N), by = id]
        
        #     id time cycle
        #  1:  1    0     1
        #  2:  1    5     2
        #  3:  2    0     1
        #  4:  2   10     2
        #  5:  2   20     3
        #  6:  3    0     1
        #  7:  3    2     2
        #  8:  3    5     3
        #  9:  3    8     4
        # 10:  3   15     5
        # 11:  4    0     1
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-12-17
          • 2018-03-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-07-18
          相关资源
          最近更新 更多