I need to write a generic function for “find and replace in R”. How can I write a function that takes the following inputs
- A CSV file (or data frame)
- A string to find, for example “name@email.com”
- A string the replace the found string with, for example “medium”
and rewrites the CSV file/data frame so that all the found strings are replaced with the replacement string?
Here’s a quick function to do the job:
Basically, it identifies all the variables in the data frame that are characters or factors, and then applies
str_replace_allto each column. Pattern should be a regular expression, but if you want to match a fixed string, you can do (e.g.)