我正在尝试在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 =&#34;我要参加派对&#34;,&#34;他也会去#34;) 这种方法不起作用,因为gsub只接受a和b的长度为1的字符串。执行循环以循环通过a和b将非常慢,因为实数a和b具有90的长度并且c具有> 1的长度。 200000。 R中是否有矢量化方式来执行此操作?
答案 0 :(得分:12)
1)gsubfn gsubfn
与gsub
类似,但替换字符串可以是字符串,列表,函数或proto对象。如果它是一个列表,它将用名称等于匹配字符串的列表组件替换每个匹配的字符串。
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"
答案 1 :(得分:0)
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)
答案 2 :(得分: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"