在一个r函数中使用多个gsubs

时间:2016-02-10 14:58:03

标签: r

所以请记住,我现在开始使用R两天了,对于我们的第一个任务,我们必须创建一个函数,而我正计划只进行基本的加密。

这是我到目前为止所做的:

g <- c("Hello, this is a test, do you understand?")

convert <- function(a) {
    gsub("H","$",a)
    gsub("e","f",a)
    gsub("l","*",a)
    gsub("o","7",a)
}

convert(g)

看问题是这个输出:

"Hell7, this is a test, d7 y7u undertstand?"

如何让多个gsub生效?

2 个答案:

答案 0 :(得分:7)

如果它是逐字符类型替换,我会使用chartr

g <- c("Hello, this is a test, do you understand?")
chartr("Helo", "$f*7", g)
# [1] "$f**7, this is a tfst, d7 y7u undfrstand?"

答案 1 :(得分:2)

我们可以使用mgsub

中的qdap
library(qdap)
mgsub(c('H', 'e', 'l', 'o'), c('$', 'f', '*', '7'), g)
#[1] "$f**7, this is a tfst, d7 y7u undfrstand?"

或来自gsubfn

gsubfn
library(gsubfn)
gsubfn('.', list(H='$', e='f', l='*', o='7'), g)
#[1] "$f**7, this is a tfst, d7 y7u undfrstand?"