Writing a generic function for “find and replace” in R

放肆的年华 提交于 2020-01-01 07:37:09

问题


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?


回答1:


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")



回答2:


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.



来源:https://stackoverflow.com/questions/12829309/writing-a-generic-function-for-find-and-replace-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!