我正在尝试在 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中是否有矢量化方式来执行此操作?
最佳答案
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 - 匹配和替换文本向量中的多个字符串,而不在 R 中循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29403080/