2017-02-14 38 views
5

我想通過ID中的R爲重複的行

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 

回答

9

您可以使用make.unique從基礎R如下,

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" 
+4

'AVE(as.character(DF $代碼),DF $ ID,FUN =函數(X)make.unique(X 09月= 「_」))'如果下劃線是超級重要。 – thelatemail

1

或者用dplyr

library(dplyr) 
df %>% 
    group_by(ID) %>% 
    mutate(Code_n = make.unique(as.character(Code)))