Reputation: 2583
I have a data.frame that looks like this:
names value1 Value2 S1_xxx-1 9.65 1.24 S1_xxx-1 1.15 3.64 S1_xxx-1 3.05 1.65 S2_xxx-1 7.12 6.109 S2_xxx-1 8.9 6.03 S2_xxx-1 4.23 2.10 ....... ...... ......
with S* from S1 to S16 and _xxx- are some letters. Is there a way to obtain the following output on the first column?
names value1 Value2 S1_xxx-1-0 9.65 1.24 S1_xxx-1-0 1.15 3.64 S1_xxx-1-0 3.05 1.65 S2_xxx-1-1 7.12 6.109 S2_xxx-1-1 8.9 6.03 S2_xxx-1-1 4.23 2.10 ....... ...... ......
i.e. when there is S1* I would like to add -0 as a suffix to all the rows having S1*. Equally, when there is S2* I would like to add -1 as a suffix to all the rows having S2* and so on until S16* that will have -15 as a suffix. Thank you in advance
Upvotes: 1
Views: 109
Reputation: 887153
We extract the digits with parse_number
, subtract 1, and paste
with the 'names'
df1$names <- with(df1, paste0(names, '-', readr::parse_number(names) -1))
df1$names
#[1] "S1_xxx-1-0" "S1_xxx-1-0" "S1_xxx-1-0" "S2_xxx-1-1" "S2_xxx-1-1" "S2_xxx-1-1"
Or similar option in tidyverse
library(dplyr)
library(stringr)
df1 %>%
mutate(names = str_c(names, readr::parse_number(names), sep = '-'))
df1 <- structure(list(names = c("S1_xxx-1", "S1_xxx-1", "S1_xxx-1",
"S2_xxx-1", "S2_xxx-1", "S2_xxx-1"), value1 = c(9.65, 1.15, 3.05,
7.12, 8.9, 4.23), Value2 = c(1.24, 3.64, 1.65, 6.109, 6.03, 2.1
)), class = "data.frame", row.names = c(NA, -6L))
Upvotes: 1