Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to subtract a number from string elements in R?

I have a long string, the part is

x <- "Text1 q10_1 text2 q17 text3 q22_5 ..."

How to subtract 1 from each number after "q" letter to obtain

y <- "Text1 q9_1 text2 q16 text3 q21_5 ..."

I can extract all my numbers from x:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

numbers <- stringr::str_extract_all(x, "(?<=q)\\d+")
numbers <- as.integer(numbers[[1]]) - 1

But how to update x with this new numbers?

The next is not working

stringr::str_replace_all(x, "(?<=q)\\d+", as.character(numbers))

>Solution :

I learned today that stringr::str_replace_all will take a function:

stringr::str_replace_all(
  x, 
  "(?<=q)\\d+", 
  \(x) as.character(as.integer(x) - 1)
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading