A safe, multiple, simultaneous string substitution function
You have a string you want to make substitutions on. You want to make many different substitutions at the same time and you want them done in a safe way. For example, you want to shift each word in “hey, how are you?” to the left by replacing “hey” with “how”, “how” with "are, etc. Existing functions either do not support vectorization (e.g. gsub
), don’t support simultaneous substition (e.g. stringr::str_replace_all
) or do the replacements in an unsafe manner (e.g. qdap::mgsub
). This is a lightweight, pure R function with no dependencies to avoid package bloat when being used.
install.packages('mgsub')
#Install the latest version from GitHub
#devtools::install_github("bmewing/mgsub")
Simply pass in a vector of strings to be modified, a vector of patterns to match and a vector of replacements. Then watch as they are safely, simultaneously replaced!
The pattern to match is supplied first and the replacement vector follows.
Recycling is to make it easy to provide a single replacement (or a pattern of replacements) for multiple matches.
Matches and replacements can still be supplied as regex exressions. Additional arguments can be passed to the sub
/gsub
/gregexpr
family of internal functions.