Replace multiple strings in one gsub() or chartr() statement in R?

You can use gsubfn

library(gsubfn)
gsubfn(".", list("'" = "", " " = "_"), x)
# [1] "ab_c"

Similarly, we can also use mgsub which allows multiple replacement with multiple pattern to search

mgsub::mgsub(x, c("'", " "), c("", "_"))
#[1] "ab_c"

Leave a Comment