How to create a consecutive group number

后端 未结 8 1089
深忆病人
深忆病人 2020-11-21 16:13

I have a data frame (all_data) in which I have a list of sites (1... to n) and their scores e.g.

  site  score
     1    10
     1    11  
              


        
8条回答
  •  时光说笑
    2020-11-21 16:56

    In the new dplyr 1.0.0 we can use cur_group_id() which gives a unique numeric identifier to a group.

    library(dplyr)
    df %>% group_by(site) %>% mutate(number = cur_group_id())
    
    #  site score number
    #     
    #1     1    10      1
    #2     1    11      1
    #3     1    12      1
    #4     4    10      2
    #5     4    11      2
    #6     4    11      2
    #7     8     9      3
    #8     8     8      3
    #9     8     7      3
    

    data

    df <- structure(list(site = c(1L, 1L, 1L, 4L, 4L, 4L, 8L, 8L, 8L), 
    score = c(10L, 11L, 12L, 10L, 11L, 11L, 9L, 8L, 7L)), 
    class = "data.frame", row.names = c(NA, -9L))
    

提交回复
热议问题