gpt4 book ai didi

r - 为重复的行分配唯一的值

转载 作者:行者123 更新时间:2023-12-04 13:57:20 25 4
gpt4 key购买 nike

我想通过R中的ID为每个重复的行分配值

df <- data.frame(ID=c(1,1,1,2,2,2,2,2,3,3,4),
Code = c("A","A","A","B","B","C","C","D","A","A","C"))
> df
ID Code
1 1 A
2 1 A
3 1 A
4 2 B
5 2 B
6 2 C
7 2 C
8 2 D
9 3 A
10 3 A
11 4 C

我想要这样的输出,检查ID是否重复,然后分配第二个重复的_1,依此类推...
   ID Code Code_n
1 1 A A
2 1 A A_1
3 1 A A_2
4 2 B B
5 2 B B_1
6 2 C C
7 2 C C_1
8 2 D D
9 3 A A
10 3 A A_1
11 4 C C

最佳答案

您可以按以下方式从基数R使用make.unique

with(df, ave(as.character(Code), ID, FUN = make.unique))
#[1] "A" "A.1" "A.2" "B" "B.1" "C" "C.1" "D" "A" "A.1" "C"

关于r - 为重复的行分配唯一的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42237443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com