Append incremental number to specific string in a column

Viewed 66

Im sure this this something basic but I just cannot find a solution that fits. I have a large df which looks like:

Sample  cat
data1   124
data2   125
data3   126
Test1   Nice
Test2   Fluffy
Sample  Dog
data1   123
data2   124
data3   125
Test1   Good
Test2   Soft

I want to add incremental numbers to Samplevalues in the first column so I would get the following output:

Sample_1    cat
data1   124
data2   125
data3   126
Test1   Nice
Test2   Fluffy
Sample_2    Dog
data1   123
data2   124
data3   125
Test1   Good
Test2   Soft

Ive tried various gsub, grep, paste, paste0 combinations and no joy.

Example

structure(list(V1 = c("Sample", "data1", "data2", "data3", "Test1", "Test2", "Sample", "data1", "data2", "data3", "Test1", "Test2"), V2 = structure(c(5L, 2L, 3L, 4L, 9L, 7L, 6L, 1L, 2L, 3L, 8L, 10L), .Label = c("123", "124", "125", "126", "cat", "Dog", "Fluffy", "Good", "Nice", "Soft"), class = "factor")), row.names = c(NA, -12L), class = "data.frame")
2 Answers

You can use cumsum to get the number of Samples and paste them, i.e.

d1$V1[d1$V1 == 'Sample'] <- paste0(d1$V1[d1$V1 == 'Sample'], '_', unique(cumsum(d1$V1 == 'Sample')))

Something like this should work...

df2 <- df %>% 
  filter(str_detect(V1, "Sample")) %>% 
  mutate(V1 = ifelse(str_detect(V1, "Sample"), paste0("Sample_", row_number()), V1))

df <- df[-which(df$V1 == "Sample"),]


rbind(df2, df)

-Brennan

Related