0

I have a column in a dataframe in R, where each row contains a string. However, many of these are replicated although they are all in order, so rows with the same string are grouped together. I would like to create a new column that adds a count to the string.

I am relatively new to R and have no idea where to start with this so any suggestions would be helpful. Thanks!

Example:


String

apple
apple
apple
orange
orange
banana
banana
banana
banana
banana

I would like the second column to look like:


String-n

apple-1
apple-2
apple-3
orange-1
orange-2
banana-1
banana-2
banana-3
banana-4
banana-5

sf1
  • 25
  • 1
  • 6

1 Answers1

1

Here is a simple dplyr solution:

library(dplyr)

df %>% 
  group_by(String) %>% 
  mutate(`String-n` = paste0(String, "-", row_number())) %>% 
  ungroup()
## A tibble: 10 x 2
#   String `String-n`
#   <fct>  <chr>     
# 1 apple  apple-1   
# 2 apple  apple-2   
# 3 apple  apple-3   
# 4 orange orange-1  
# 5 orange orange-2  
# 6 banana banana-1  
# 7 banana banana-2  
# 8 banana banana-3  
# 9 banana banana-4  
#10 banana banana-5  
dave-edison
  • 3,666
  • 7
  • 19