gsubfn在R中,如何有条件地只替换一组字符串中的第二组数字



我很难找到只替换字符串中第二组整数的语法

我有这个

initpop <- c("a-00-04","a-00-00","a-00-00", "dead", "a-00-00")
initpop
[1] "a-00-04" "a-00-00" "a-00-00" "dead"    "a-00-00"

对于这个数组中的每个字符串,如果值<4,并且如果值==4则重置为0。我试图分块来做,但很难用最简单的正则表达式来指定第二组数字,而不是同时指定

gsubfn("[[:digital:]]+",函数(x(为.number(x(+1,initpop[1]([1] "a-1-1">

我想取回的是

[1] "a-00-00" "a-00-01" "a-00-01" "dead" "a-00-01"

我意识到这很简单,我无法理解。任何建议。Thx。J

您可以使用

gsubfn(
"^\D*\d+\D*\K(\d+)",
~ ifelse(as.numeric(x) < 4, sprintf("%02d",as.numeric(x)+1), "00"),
initpop,
perl=TRUE
)

输出:

[1] "a-00-00" "a-00-01" "a-00-01" "dead"    "a-00-01"

正则表达式-^D*d+D*K(d+)使用PCRE引擎进行解析(由于perl=TRUE(,并与匹配

  • ^-字符串的开头
  • D*-0+非数字字符
  • d+-1+位(第一组数字(
  • D*-0+非数字
  • K-匹配重置运算符丢弃迄今为止匹配的文本
  • (d+)-第1组:一位或多位(第二组(

~ ifelse(as.numeric(x) < 4, sprintf("%02d",as.numeric(x)+1), "00")部分是替换:如果x小于4,则返回增量值,并填充初始0,否则返回00。这是可以调整的。

最新更新