Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace/modify duplicates in a dataframe

Based on the data and code below how can I replace duplicates by adding a, b, c and so on for each duplicate value except the first one?

Please note that in the actual data provided to me, there are thousands of entries, so there could be any number of duplicates thus, it would be hard for me to manually find each and every duplicate value in the data. So, I don’t know if it might be a problem in not identifying the duplicates first before replacing them. Maybe there is a way to identify them first, which as of now I don’t know.

Code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# Sample data
df = structure(list(id = c(1, 1, 1, 1, 2, 2, 2, 2, 35555, 35555, 35555
), year = c(2022, 2022, 2022, 2022, 2022, 2022, 2022, 2022, 2022, 
2022, 2022)), class = "data.frame", row.names = c(NA, -11L))

# Desired output
df = structure(list(id = c(1, "1a", "1b", "1c", 2, "2a", "2b", "2c", 35555, "35555a", "35555b"
), year = c(2022, 2022, 2022, 2022, 2022, 2022, 2022, 2022, 2022, 
2022, 2022)), class = "data.frame", row.names = c(NA, -11L))

# Replace/modify duplicates

>Solution :

If the suffix doesn’t matter, make.unique does this automatically

library(dplyr)
df %>% 
   mutate(id = make.unique(as.character(id)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading