用模式替换 R 中的字符串并替换两个向量 [英] Replace string in R with patterns and replacements both vectors
问题描述
假设我有两个这样的向量:
Let's say I have two vectors like so:
a <- c("this", "is", "test")
b <- c("that", "was", "boy")
我也有一个像这样的字符串变量:
I also have a string variable like so:
string <- "this is a story about a test"
我想替换字符串中的值,使其变为以下内容:
I want to replace values in string so that it becomes the following:
string <- "that was a story about a boy"
我可以使用 for 循环来做到这一点,但我希望将其矢量化.我该怎么做?
I could do this using a for loop but I want this to be vectorized. How should I do this?
推荐答案
如果您愿意使用非基础包,stringi
在这里非常有效:
If you're open to using a non-base package, stringi
will work really well here:
stringi::stri_replace_all_fixed(string, a, b, vectorize_all = FALSE)
#[1] "that was a story about a boy"
请注意,这也适用于长度 > 1 的输入字符串.
Note that this also works the same way for input strings of length > 1.
为了安全起见,您可以对此进行调整 - 类似于 RUser 的回答 - 在替换之前检查单词边界:
To be on the safe side, you can adapt this - similar to RUser's answer - to check for word boundaries before replacing:
stri_replace_all_regex(string, paste0("\\b", a, "\\b"), b, vectorize_all = FALSE)
例如,这将确保您不会意外地将 his
替换为 hwas
.
This would ensure that you don't accidentally replace his
with hwas
, for example.
这篇关于用模式替换 R 中的字符串并替换两个向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!