Replace a character string in a column · #11
This snippet needs the following
libraries:
tidyverse: stringr
tidyverse: dplyr
· How to load the right library →
To replace a character string in a column, use str_replace_all()
and mutate()
.
# With the pipe operator
df <- df %>%
mutate(col = str_replace_all(col, "string to replace", "replacement string"))
# Without the pipe operator
df <- mutate(df, col = str_replace_all(col, "string to replace", "replacement string"))
The code above will replace every single instance of string to replace
found in col
in the dataframe df
with replacement string
.
More specifically, str_replace_all()
replace string to replace
found in col
with replacement string
and mutate()
replace col
with the version where string to replace
has been replaced.
Documentation
Replace matched patterns in a string. — str_replace
Vectorised over string, pattern and replacement.

Create, modify, and delete columns — mutate
mutate() adds new variables and preserves existing ones;transmute() adds new variables and drops existing ones.New variables overwrite existing variables of the same name.Variables can be removed by setting their value to NULL.
