【发布时间】:2021-07-21 14:06:21
【问题描述】:
我想用某些替换词替换某些词。 我做了一个 for 循环,但只进行了最后一次替换。
library(dplyr)
library(stringr)
text <- data.frame(
tekstid = c(1,2),
example = c("here are some examples", "and questions i ask")
)
wordmatch <- data.frame(
word = c("examples", "questions"),
replacement = c("example", "question"))
for(i in 1:nrow(wordmatch)) {
text_output <- text %>%
str_replace_all(example, fixed(wordmatch$word[i]), wordmatch$replacement[i])
return(text_output)
}
print(text_output)
输出为:"c(\"here are some examples\", \"and question i ask\")"
questions 正确地变成了 question 但是 examples 应该变成 example
【问题讨论】:
-
循环的每次迭代都会覆盖
text_output。这就是为什么它似乎只进行了最后一次替换。
标签: r for-loop str-replace stringr