Whenever I need to do text replacement, it’s rare that I only have to replace one pattern. I often find myself stringing together multiple str_replace_all() calls, one after another. The example code below feels very repetitive. Is there a way to do this with only one call to str_replace_all()?
library(dplyr)
library(stringr)
text <- r'(mother, father, grandmother, and grandfather)'
# is there a better way to do this?
text %>%
str_replace_all(
pattern = r'(\bmother\b)',
replacement = 'mom'
) %>%
str_replace_all(
pattern = r'(\bfather\b)',
replacement = 'dad'
) %>%
str_replace_all(
pattern = 'grandmother',
replacement = 'grandma'
) %>%
str_replace_all(
pattern = 'grandfather',
replacement = 'grandpa'
) %>%
str_replace_all(
pattern = r'(\band\b)',
replacement = '&'
)
#> [1] "mom, dad, grandma, & grandpa"
Created on 2023-12-12 with reprex v2.0.2
I’m imagining something with a lookup table.
df_lookup <-
tribble(
~pattern, ~replacement,
r'(\bmother\b)', 'mom',
r'(\bfather\b)', 'dad',
'grandmother', 'grandma',
'grandfather', 'grandpa',
r'(\band\b)', '&'
)
>Solution :
You can perform multiple str_replace as follows:
str_replace_all(text,
c(
r'(\bmother\b)' = "mom",
r'(\bfather\b)' = "dad",
'grandmother' = "grandma",
'grandfather' = "grandpa",
r'(\band\b)' = "&")
)