Victor Kostyuk Victor Kostyuk - 2 months ago 4x
R Question

Incrementing a number in a string using sub

There's a string with a (single) number somewhere in it. I want to increment the number by one. Simple, right? I wrote the following without giving it a second thought:

sub("([[:digit:]]+)", as.character(as.numeric("\\1")+1), string)

... and got an NA.

> sub("([[:digit:]]+)", as.character(as.numeric("\\1")+1), "x is 5")
[1] NA
Warning message:
In sub("([[:digit:]]+)", as.character(as.numeric("\\1") + 1), "x is 5") :
NAs introduced by coercion

Why doesn't it work? I know other ways of doing this, so I don't need a "solution". I want to understand why this method fails.


The point is that the backreference is only evaluated during a match operation, and you cannot pass it to any function before that.

When you write as.numeric("\\1") the as.numeric function accepts a \1 string (a backslash and a 1 char). Thus, the result is expected, NA.

This happens because there is no built-in backreference interpolation in R.

You may use a gsubfn package:

> library(gsubfn)
> s <- "x is 5"
> gsubfn("\\d+", function(x) as.numeric(x) + 1, s)
[1] "x is 6"