匹配并替换文本向量中的多个字符串,而无需在 R 中循环

Match and replace multiple strings in a vector of text without looping in R

我正在尝试在 R 中应用 gsub 以将字符串 a 中的匹配项替换为字符串 b 中的相应匹配项。例如:

a <- c("don't", "i'm", "he'd")
b <- c("do not", "i am", "he would")
c <- c("i'm going to the party", "he'd go too")
newc <- gsub(a, b, c)

期望的结果是

newc = c("i am going to the party", "he would go too")

这种方法行不通,因为gsub 只接受a 和b 长度为1 的字符串。执行循环以循环遍历 a 和 b 将非常慢,因为真实的 a 和 b 的长度为 90,而 c 的长度 > 200,000。 R 中是否有向量化的方式来执行此操作?

1) gsubfn 包中的 gsubfn gsubfn 类似于 gsub 除了替换字符串可以是字符串、列表、函数或原型对象.如果它是一个列表,它将用名称等于匹配字符串的列表组件替换每个匹配的字符串。

library(gsubfn)
gsubfn("\S+", setNames(as.list(b), a), c)

给予:

[1] "i am going to the party" "he would go too"    

2) gsub 对于没有包的解决方案尝试这个循环:

cc <- c
for(i in seq_along(a)) cc <- gsub(a[i], b[i], cc, fixed = TRUE)

给予:

> cc
[1] "i am going to the party" "he would go too"        

stringr::str_replace_all()是一个选项:

library(stringr)
names(b) <- a
str_replace_all(c, b)
[1] "i am going to the party" "he would go too"  

这是相同的代码,但带有不同的标签,希望能让它更清晰一些:

to_replace <- a
replace_with <- b
target_text <- c

names(replace_with) <- to_replace
str_replace_all(target_text, replace_with)

另一个具有函数式编程风格的基础 R 解决方案。

#' Replace Multiple Strings in a Vector
#'
#' @param x vector with strings to replace
#' @param y vector with strings to use instead
#' @param vec initial character vector
#' @param ... arguments passed to `gsub`
replace_strngs <- function(x, y, vec, ...) {
  # iterate over strings
  vapply(X = vec, 
         FUN.VALUE = character(1),
         USE.NAMES = FALSE, 
         FUN = function(x_string) {
           # iterate over replacements
           Reduce(
             f = function(s, x) {
               gsub(pattern = x[1],
                    replacement = x[2],
                    x = s,
                    ...) 
             },
             x = Map(f = base::c, x, y),
             init = x_string)
         })
}

a <- c("don't", "i'm", "he'd")
b <- c("do not", "i am", "he would")
c <- c("i'm going to the party", "he'd go too")

replace_strngs(a, b, c, fixed = TRUE)
#> [1] "i am going to the party" "he would go too"