transform(df, Initials = ave(as.character(Initials), Initials,
FUN = function(x) if (length(x) > 1) paste0(x, " (", seq(x), ")") else x))
# Initials Data
# 1 AA 1
# 2 AB (1) 2
# 3 AB (2) 3
R - Make unique strings in a data frame
Question
I'd like to make a column of (possibly) non-unique strings into a column of unique strings.
For instance, consider:
df <- data.frame(
'Initials' = c("AA","AB","AB")
, 'Data' = c(1,2,3)
)
df
Initials Data
1 AA 1
2 AB 2
3 AB 3
I would like to obtain this:
Initials Data
1 AA 1
2 AB (1) 2
3 AB (2) 3
Thanks!
Note: I know I could use the rownames to uniquely identify the row, but I'd like to retain the string stored in the Initials column, with a number appended.
Solution
OTHER TIPS
w <- ave(df$Data, df$Initials, FUN = seq_along )
> df$Initials <- paste(df$Initials, "(", w, ")", sep = "")
# > df
# Initials Data
# 1 AA(1) 1
# 2 AB(1) 2
# 3 AB(2) 3
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow