编写用于“查找并替换”的通用函数。在R中 [英] Writing a generic function for "find and replace" in R
本文介绍了编写用于“查找并替换”的通用函数。在R中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要为在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
- CSV文件(或数据框)
- 要查找的字符串,例如 name@email.com
- 将找到的字符串替换为例如 medium的字符串
并重写CSV文件/数据框,以便将所有找到的字符串替换为替换字符串?
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:
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")
基本上,它标识数据帧中所有字符或因素,然后将 str_replace_all
应用于每个列。模式应该是一个正则表达式,但是如果要匹配固定的字符串,则可以执行(例如)
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")
这篇关于编写用于“查找并替换”的通用函数。在R中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文