Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

r - Add a suffix based on a pattern in rows

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

question from:https://stackoverflow.com/questions/65891329/add-a-suffix-based-on-a-pattern-in-rows

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 = '-'))

data

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...