Assign a unique value to duplicate rows

I want to assign a value for each duplicated row by ID in 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 

I want this output to look like this: check the duplicate by id, then assign the second duplicate _1 and so on ...

  ID Code Code_n 1 1 AA 2 1 A A_1 3 1 A A_2 4 2 BB 5 2 B B_1 6 2 CC 7 2 C C_1 8 2 DD 9 3 AA 10 3 A A_1 11 4 CC 
+5
source share
2 answers

You can use make.unique from the R base as follows:

 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" 
+9
source

Or using dplyr

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

Source: https://habr.com/ru/post/1264212/


All Articles