Search code examples
rregexstringr

How can I 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 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))

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