Dennis
Dennis

Reputation: 45

Rename string if two columns are identical

I have a table with several columns. I want to number a string in a column in case this is identical. --> want to go to wide format later this is why I cannot have identical strings.

Example:

Name    drink   number
stefan  beer    3
stefan beer 4
stefan wine 4
michael soda 2

should be

Name    drink   number
stefan  beer_1  3
stefan beer_2   4
stefan wine 4
michael soda 2

Right now I only remove the columns but would be great just to add a number to the second column.

df[!duplicated(df[c(1,2)]),]

Thank you so much for your help. i guess this can be done with replace as well as with dplyr package and mutate but not sure how the code has to look like.

Thanks. Dennis

Upvotes: 1

Views: 54

Answers (1)

akrun
akrun

Reputation: 887223

One option is make.unique

library(dplyr)
df %>%
  group_by(Name) %>%
   mutate(drink = make.unique(drink, sep = "_"))

Upvotes: 5

Related Questions