Replace the string in R with the pattern and replace the two vectors

Suppose I have two such vectors:

a <- c("this","is","test")
b <- c("that","was","boy")@H_301_12@ 
 

我也有一个像这样的字符串变量:

string <- "this is a story about a test"@H_301_12@ 
 

我想替换字符串中的值,以便它成为以下:

string <- "that was a story about a boy"@H_301_12@ 
 

我可以使用for循环来做这个,但我希望这是矢量化的.我该怎么做?

Solution

If you prefer to use non basic packages, stringi works well here:

stringi::stri_replace_all_fixed(string,a,b,vectorize_all = FALSE)
#[1] "that was a story about a boy"@H_301_12@ 
 

注意,对于长度> 1的输入字符串,这也是相同的方式. 1.

为了安全起见,您可以对此进行调整 – 类似于RUser的答案 – 在更换之前检查字边界:

stri_replace_all_regex(string,paste0("\\b","\\b"),vectorize_all = FALSE)@H_301_12@ 
 

例如,这将确保您不会意外地将其替换为hwas.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>