Assign unique ID to distinct values within Group with dplyr

前端 未结 2 1305
刺人心
刺人心 2021-01-20 13:22

Problem: I need to make a unique ID field for data that has two levels of grouping. In the example code here, it is Emp and Color. The ID needs to

2条回答
  •  情歌与酒
    2021-01-20 13:46

    We can try

    dat %>% 
       group_by(Emp) %>%
       mutate(temp = match(Color, unique(Color)),
              temp2 = duplicated(Color)+1,
              ID = sprintf("%s.%02d.%03d", Emp, temp, temp2))%>%
       select(-temp, -temp2)  
    #    Emp  Color       ID
    #         
    #1     A    Red A.01.001
    #2     A  Green A.02.001
    #3     A  Green A.02.002
    #4     B Orange B.01.001
    #5     B Yellow B.02.001
    #6     C  Brown C.01.001
    

提交回复
热议问题