本文介绍了使用gsub替换字符,如何创建函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试替换data.frame中的字符.我对此有解决方案

I'm trying to replace characters in a data.frame. I have a solution for this

> df <- data.frame(var1 = c("aabbcdefg", "aabbcdefg"))
> df
       var1
1 aabbcdefg
2 aabbcdefg
> df$var1 <- gsub("a", "h", df$var1)
> df$var1 <- gsub("b", "i", df$var1)
> df$var1 <- gsub("c", "j", df$var1)
> df$var1 <- gsub("d", "k", df$var1)
> df$var1 <- gsub("e", "l", df$var1)
> df$var1 <- gsub("f", "m", df$var1)
> df
       var1
1 hhiijklmg
2 hhiijklmg
> 

但是我想避免使用多个gsub调用,立即生成一个函数来执行此操作会更好呢?

but I would like to avoid using several gsub calls, it would be much nicer to produce a function to do this at once?

有什么想法可以继续吗?

Any ideas ho to proceed?

推荐答案

您可以创建fromto向量:

from <- c('a','b','c','d','e','f')
to <- c('h','i','j','k','l','m')

,然后将gsub函数矢量化:

gsub2 <- function(pattern, replacement, x, ...) {
for(i in 1:length(pattern))
x <- gsub(pattern[i], replacement[i], x, ...)
x
}

哪个给:

> df <- data.frame(var1 = c("aabbcdefg", "aabbcdefg"))
> df$var1 <- gsub2(from, to, df$var1)
> df
       var1
1 hhiijklmg
2 hhiijklmg

这篇关于使用gsub替换字符,如何创建函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 21:20