如何从 R 中的字符串元素中减去数字?

问题描述 投票:0回答:3

我有一根长绳子,零件是

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))
r regex stringr
3个回答
18
投票

我今天了解到

stringr::str_replace_all
将采用一个函数:

stringr::str_replace_all(
  x, 
  "(?<=q)\\d+", 
  \(x) as.character(as.integer(x) - 1)
)

13
投票

我们可以使用

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 ..."

5
投票

这是使用

gsubfn
包中的
gsubfn
函数的替代方法:

  1. gsubfn
    匹配“q”后跟一位或多位数字。
  2. 数字作为一组被捕获。
  3. 每个捕获的组都会传递给内联函数
    ~ 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 ..."
© www.soinside.com 2019 - 2024. All rights reserved.