1

So keep in mind I started using R for two days now, and for our first assignment we have to create a function, and I'm planning on just doing basic encryption kind of thing.

This is what I have so far:

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)

See the problem is this outputs:

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

How would I get the multiple gsubs to work?

A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
Dobly
  • 61
  • 1
  • 5

2 Answers2

7

I would use chartr for this if it's a character-by-character type replacement:

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?"
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
2

We could use mgsub from qdap

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

Or gsubfn from gsubfn package

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