Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I subtract a number from string elements in R?

Tags:

regex

r

stringr

I have a long string. The part is

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

How can I subtract 1 from each number after "q" letter to obtain the following?

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

I can extract all my numbers from x:

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

But how can I update x with these new numbers?

The following is not working

stringr::str_replace_all(x, "(?<=q)\\d+", as.character(numbers))
like image 460
drastega Avatar asked Dec 20 '25 03:12

drastega


1 Answers

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)
)
like image 61
Will Oldham Avatar answered Dec 22 '25 20:12

Will Oldham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!