【发布时间】:2022-01-17 11:52:43
【问题描述】:
我想根据另一个数据框中的原始单词和替换单词替换向量中的单词。举个例子:
要更改的字符串向量:
my_words <- c("example r", "example River", "example R", "anthoer river",
"now a creek", "and another Ck", "example river tributary")
要替换的词的数据框和对应的替换词:
my_replace <- data.frame(
original = c("r", "River", "R", "river", "Ck", "creek", "Creek"),
replacement = c("R", "R", "R", 'R', "C", "C", "C"))
我想用向量my_words 中my_replace$replacement 中的相应值替换my_replace$original 中出现的任何单词。我尝试使用stringr::str_replace_all(),但它替换了字母/单词的所有实例,而不是整个单词(例如“another”变成了“anotherR”),这是不可取的。
我想做的伪代码:
str_replace_all(my_words, my_replace$original, my_replace$replacement)
期望的输出:
"example R", "example R", "example R", "another R", "now a C", "and another C", "example R tributary"
我确实找到了使用for 循环的解决方案,但鉴于我的数据集很大,for 循环选项太慢了。非常感谢任何建议。
【问题讨论】: