使用 sub 增加字符串中的数字

Incrementing a number in a string using sub

某处有一个带有(单个)数字的字符串。我想把数字加一。简单吧?我没有再考虑就写了以下内容:

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

...并获得了 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

为什么不起作用?我知道这样做的其他方法,所以我不需要 "solution"。我想明白为什么这个方法失败了。

它不起作用,因为 sub 的参数在传递给正则表达式引擎(由 .Internal 调用)之前被评估。

特别是,as.numeric("\1") 的计算结果为 NA ... 之后你就完蛋了。

要点是反向引用仅在匹配操作期间进行评估,在此之前您不能将其传递给任何函数。

当您编写 as.numeric("\1") 时,as.numeric 函数接受一个 </code> 字符串(一个反斜杠和一个 <code>1 字符)。因此,结果是预期的,NA.

发生这种情况是因为 R 中没有内置的反向引用插值。

您可以使用 gsubfn 软件包:

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

换个角度想可能更容易。如果您使用:

,您会收到相同的错误
print(as.numeric("\1")+1)

请记住,字符串被传递给函数,在那里它们由正则表达式引擎解释。字符串 \1 永远不会转换为 5,因为此计算是在函数内完成的。

请注意 \1 不是数字。 NA在其他语言中似乎类似于null:

NA... is a product of operation when you try to access something that is not there

来自 mpiktas 的回答 here