【问题标题】:Create numbered sequence for occurrences of a given nesting variable为给定嵌套变量的出现创建编号序列
【发布时间】:2014-08-01 03:35:10
【问题描述】:

我希望向数据集添加一个变量,该变量对出现的某个分组变量的实例进行排序。例如:

ids <- c(rep(1,4),rep(2,6),rep(3,2))

我想要另一个变量来计算每个 id 出现的实例。像这样创建一个向量:

1,2,3,4,1,2,3,4,5,6,1,2

它们结合起来看起来像这样:

    ids count
1    1      1
2    1      2
3    1      3
4    1      4
5    2      1
6    2      2
7    2      3
8    2      4
9    2      5
10   2      6
11   3      1
12   3      2

有什么想法吗?非常感谢!

【问题讨论】:

    标签: r sequence sequences


    【解决方案1】:

    我建议aveseq_along

    ids <- c(rep(1,4),rep(2,6),rep(3,2))
    count <- ave(ids,ids, FUN=seq_along)
    cbind(ids, count)
    
    #       ids count
    #  [1,]   1     1
    #  [2,]   1     2
    #  [3,]   1     3
    #  [4,]   1     4
    #  [5,]   2     1
    #  [6,]   2     2
    #  [7,]   2     3
    #  [8,]   2     4
    #  [9,]   2     5
    # [10,]   2     6
    # [11,]   3     1
    # [12,]   3     2
    

    【讨论】:

      【解决方案2】:

      或者如果它被订购了

      cbind(ids, count=sequence(unname(table(ids))))
      #       ids count
      #  [1,]   1     1
      #  [2,]   1     2
      #  [3,]   1     3
      #  [4,]   1     4
      #  [5,]   2     1
      #  [6,]   2     2
      #  [7,]   2     3
      #  [8,]   2     4
      #  [9,]   2     5
      # [10,]   2     6
      # [11,]   3     1
      # [12,]   3     2
      

      或者

        cbind(ids,within.list(rle(ids), lengths <- sequence(lengths))$lengths)
      

      或者

       library(data.table)
       dt <- as.data.table(ids)
       dt[,count:=seq_len(.N), by=ids]
      

      或者

      library(dplyr)
      dat <- data.frame(ids)
      dat %>% 
      group_by(ids) %>%
      mutate(count=row_number())
      

      【讨论】:

        猜你喜欢
        • 2021-05-19
        • 2022-01-12
        • 2019-01-29
        • 2019-04-09
        • 1970-01-01
        • 2014-01-06
        • 1970-01-01
        • 2022-10-21
        • 1970-01-01
        相关资源
        最近更新 更多