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
网友评论