str_replace_all 在 for 循环中

str_replace_all in for loop

我想用某些替换词替换某些词。 我做了一个 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\")"

问题正确地变成了问题但是 examples 应该变成 example

使用purrr:

library(purrr)
text <- data.frame(
  tekstid = c(1,2),
  example = c("here are some examples", "and questions i ask")
)

wordmatch <- c("examples" = "example",
               "questions" = "question")

text$example <- data.frame(example = matrix(unlist(map(text[,2],
                                                       str_replace_all,
                                                       wordmatch)),
                                            ncol = 1))

输出:

  tekstid               example
1       1 here are some example
2       2    and question i ask