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

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

我正在尝试在 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 中有矢量化的方式来执行此操作吗?

r string gsub
4个回答
17
投票

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"        

5
投票

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)

0
投票

另一个具有函数式编程风格的基础 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"

0
投票

使用递归函数。像这样的东西:

gsub.rec <- function(a, b, c) {
  if(length(a) == 0) c else gsub.rec(a[-1], b[-1], gsub(a[1], b[1], c, fixed = TRUE))
}

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

gsub.rec(a, b, c)

#> [1] "i am going to the party" "he would go too"  
© www.soinside.com 2019 - 2024. All rights reserved.