用模式替换 R 中的字符串并替换两个向量

标签 r string vector

假设我有两个这样的向量:

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

我也有一个像这样的字符串变量:
string <- "this is a story about a test"

我想替换字符串中的值,使其变为以下内容:
string <- "that was a story about a boy"

我可以使用 for 循环来做到这一点,但我希望将其矢量化。我该怎么做?

最佳答案

如果您愿意使用非基础包,stringi在这里工作得很好:

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

请注意,这也适用于长度 > 1 的输入字符串。

为了安全起见,您可以对此进行调整 - 类似于 RUser 的回答 - 在替换之前检查单词边界:
stri_replace_all_regex(string, paste0("\\b", a, "\\b"), b, vectorize_all = FALSE)

这将确保您不会意外更换 hishwas , 例如。

关于用模式替换 R 中的字符串并替换两个向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45301218/

相关文章:

Haskell 中带列表的字符串替换运算符

c++ - 使用 C API 时,使用字符数组还是使用字符串并根据需要进行转换?

c++ - 无法用 C++ 打开 file.txt

r - 保存时空的R环境变成大文件

在 R shiny 中双击将 plotoutput 替换为 leafletoutput

java - 正则表达式捕获 Java 中的所有单词和 "i' m you’re 等

MATLAB 矢量化 : filling struct fields from vector elements

vector - 如何将 illustrator 中的各个图层导出为 png?

r - 更新包并防止它恢复到原始状态

r - 在R中使用mfrow:如何为每个子图赋予不同的y标签和x轴一个标签