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

时光总嘲笑我的痴心妄想 提交于 2019-12-03 21:51:39

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

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.

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