histelheim
histelheim

Reputation: 5088

Writing a generic function for "find and replace" in R

I need to write a generic function for "find and replace in R". How can I write a function that takes the following inputs

and rewrites the CSV file/data frame so that all the found strings are replaced with the replacement string?

Upvotes: 0

Views: 3625

Answers (2)

hadley
hadley

Reputation: 103928

Here's a quick function to do the job:

library(stringr)

replace_all <- function(df, pattern, replacement) {
  char <- vapply(df, function(x) is.factor(x) || is.character(x), logical(1))
  df[char] <- lapply(df[char], str_replace_all, pattern, replacement)  
  df
}

replace_all(iris, "setosa", "barbosa")

Basically, it identifies all the variables in the data frame that are characters or factors, and then applies str_replace_all to each column. Pattern should be a regular expression, but if you want to match a fixed string, you can do (e.g.)

replace_all(iris, fixed("setosa"), "barbosa")

Upvotes: 8

Justin
Justin

Reputation: 43265

The solution below will work for "exact" matches:

dat <- data.frame(a=letters[1:10], y=letters[10:1]) 
apply(dat, 2, function(v, foo, bar) {v[v==foo]=bar;return(v)}, foo='a', bar='baz')

However, this won't replace strings that contain a 1. It will also have many edge cases that won't work the way you might expect.

As I mentioned in my comment, the command line tool sed is ideally suited for this kind of operation.

Upvotes: 1

Related Questions