Create numbered sequence for occurrences of a given nesting variable

前端 未结 2 963
清酒与你
清酒与你 2021-01-24 16:43

I\'m hoping to add to a data set a variable that sequences the instances a certain grouping variable appears. For example:

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


        
相关标签:
2条回答
  • 2021-01-24 16:55

    I suggest ave with seq_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
    
    0 讨论(0)
  • 2021-01-24 16:58

    Or if it is ordered

    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
    

    Or

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

    Or

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

    Or

    library(dplyr)
    dat <- data.frame(ids)
    dat %>% 
    group_by(ids) %>%
    mutate(count=row_number())
    
    0 讨论(0)
提交回复
热议问题