匹配并替换文本向量中的多个字符串,而无需在R中循环 [英] Match and replace multiple strings in a vector of text without looping in R
问题描述
我正在尝试在R中应用gsub,以将字符串a中的匹配项替换为字符串b中的相应匹配项.例如:
I am trying to apply gsub in R to replace a match in string a with the corresponding match in string b. For example:
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的长度为90,而c的长度> 200,000,因此执行循环以遍历a和b的过程将非常缓慢. R中是否存在矢量化方式来执行此操作?
This approach does not work because gsub only accepts a string of length 1 for a and b. Executing a loop to cycle through a and b will be very slow since the real a and b have a length of 90 and c has a length > 200,000. Is there a vectorized way in R to perform this operation?
推荐答案
1)gsubfn包中的gsubfn gsubfn
类似于gsub
,只是替换字符串可以是字符串,列表,功能或原型对象.如果它是一个列表,它将用名称等于匹配字符串的列表部分替换每个匹配的字符串.
1) gsubfn gsubfn
in the gsubfn package is like gsub
except the replacement string can be a character string, list, function or proto object. If its a list it will replace each matched string with the component of the list whose name equals the matched string.
library(gsubfn)
gsubfn("\\S+", setNames(as.list(b), a), c)
给予:
[1] "i am going to the party" "he would go too"
2)gsub 对于没有软件包的解决方案,请尝试以下循环:
2) gsub For a solution with no packages try this loop:
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"
这篇关于匹配并替换文本向量中的多个字符串,而无需在R中循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!