我有一根长绳子,零件是
x <- "Text1 q10_1 text2 q17 text3 q22_5 ..."
如何将“q”字母后面的每个数字减1得到
y <- "Text1 q9_1 text2 q16 text3 q21_5 ..."
我可以从 x 中提取我的所有数字:
numbers <- stringr::str_extract_all(x, "(?<=q)\\d+")
numbers <- as.integer(numbers[[1]]) - 1
但是如何用这个新数字更新 x 呢?
下一个不起作用
stringr::str_replace_all(x, "(?<=q)\\d+", as.character(numbers))
我今天了解到
stringr::str_replace_all
将采用一个函数:
stringr::str_replace_all(
x,
"(?<=q)\\d+",
\(x) as.character(as.integer(x) - 1)
)
我们可以使用
gregexpr
和 regmatches
为此:
x <- "Text1 q10_1 text2 q17 text3 q22_5 ..."
gre <- gregexpr("(?<=q)[0-9]+", x, perl = TRUE)
regmatches(x, gre)
# [[1]]
# [1] "10" "17" "22"
regmatches(x, gre) <- lapply(regmatches(x, gre), function(z) as.integer(z) - 1L)
x
# [1] "Text1 q9_1 text2 q16 text3 q21_5 ..."
这是使用
gsubfn
包中的 gsubfn
函数的替代方法:
gsubfn
匹配“q”后跟一位或多位数字。~ paste0("q", as.numeric(x) - 1)
,该函数将捕获的数字转换为数值并减去 1,然后将其连接回来。#install.packages("gsubfn")
library(gsubfn)
gsubfn("q(\\d+)", ~ paste0("q", as.numeric(x) - 1), x)
"Text1 q9_1 text2 q16 text3 q21_5 ..."