美文网首页
dplyr-分组添加组序号(group.id)

dplyr-分组添加组序号(group.id)

作者: 倪桦 | 来源:发表于2022-12-18 18:11 被阅读0次

    1.Test data

    data <- data.frame( names = rep(c("aaa","bbb","ccc"),c(3,8,5)), elements = stringi::stri_rand_strings(16,3, pattern = "[A-Za-z0-9]"))
    -------------------------
    > data
       names elements
    1    aaa      9Zp
    2    aaa      VLa
    3    aaa      aIY
    4    bbb      2Jw
    5    bbb      Vxs
    6    bbb      S6Q
    7    bbb      PHV
    8    ccc      Ezz
    9    ccc      8ct
    10   ccc      dxG
    11   ccc      Jk2
    12   ccc      68E
    

    2.Assign Group ID

    data %>%  group_by(names) %>% mutate(groupID =cur_group_id()) 
    -------------------------
    # A tibble: 12 x 3
    # Groups:   names [3]
       names elements groupID
       <chr> <chr>      <int>
     1 aaa   9Zp            1
     2 aaa   VLa            1
     3 aaa   aIY            1
     4 bbb   2Jw            2
     5 bbb   Vxs            2
     6 bbb   S6Q            2
     7 bbb   PHV            2
     8 ccc   Ezz            3
     9 ccc   8ct            3
    10 ccc   dxG            3
    11 ccc   Jk2            3
    12 ccc   68E            3
    

    3.Assign Seq_ID within group

    data %>% group_by(names) %>% mutate(id = seq(n()))
    -------------------------
    # A tibble: 12 x 3
    # Groups:   names [3]
       names elements    id
       <chr> <chr>    <int>
     1 aaa   9Zp          1
     2 aaa   VLa          2
     3 aaa   aIY          3
     4 bbb   2Jw          1
     5 bbb   Vxs          2
     6 bbb   S6Q          3
     7 bbb   PHV          4
     8 ccc   Ezz          1
     9 ccc   8ct          2
    10 ccc   dxG          3
    11 ccc   Jk2          4
    12 ccc   68E          5
    

    相关文章

      网友评论

          本文标题:dplyr-分组添加组序号(group.id)

          本文链接:https://www.haomeiwen.com/subject/hbexartx.html