Search code examples
rreplacestringr

Replace multiple patterns with different replacements in R


I'm probably blind in one eye, but I can't find a "smarter" solution to my problem. I want to replace the emojis with their description which are stored in a separate dataframe. Is there a more convenient way to replace them?

My reproducible example:

library("tidyverse")

emojis <- tibble(
  "descr" = c("grinning","rofl","smile"),
  "emoji" = c("😀","🤣","😄")
)

data <- tibble(
  content = c("Hi 😄", "😄🤣", "lol")
)

for (i in 1:nrow(emojis)) {
  pattern <- emojis[i,"emoji"] %>% pull()
  replacement <- emojis[i,"descr"] %>% pull()
  data <- data %>%
    mutate(content = str_replace_all(content,pattern,replacement))
}


Solution

  • If we use str_replace_all's ability to take named replacements, we can do this in one step:

    stringr::str_replace_all(data$content, setNames(emojis$descr, emojis$emoji))
    # [1] "Hi smile"  "smilerofl" "lol"