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

人盡茶涼 提交于 2019-12-18 01:16:26

问题


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)

such that newc = "i am going to the party", "he would go too") 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:


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)

giving:

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

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)

giving:

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



回答2:


stringr::str_replace_all() is an option:

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

Here is the same code but with different labels to hopefully make it a little clearer:

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

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


来源:https://stackoverflow.com/questions/29403080/match-and-replace-multiple-strings-in-a-vector-of-text-without-looping-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!