0

I would like to replace certain words with certain replacements. I made a for loop but only the last replacement takes place.

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)

The output is: "c(\"here are some examples\", \"and question i ask\")"

questions correctly turned into question but examples should have turned into example

Nina van Bruggen
  • 393
  • 2
  • 13
  • 1
    You're overwriting `text_output` with each iteration of the loop. That's why it appears only the last replacement is made. – Limey Jul 21 '21 at 14:17

1 Answers1

1

Using 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))

Output:

  tekstid               example
1       1 here are some example
2       2    and question i ask
MonJeanJean
  • 2,876
  • 1
  • 4
  • 20
  • Thanks, it worked! For the people that don't know how to convert a dataframe to a named vector, I found the answer here: https://stackoverflow.com/questions/19265172/converting-two-columns-of-a-data-frame-to-a-named-vector – Nina van Bruggen Jul 21 '21 at 14:38