4

I've been playing with R's gsub2 function R: replace characters using gsub, how to create a function? to create a ciphertext:

from<-c('s','l','k','u','m','i','x','j','o','p','n','q','b','v','w','z','f','y','t','g','h','a','e','d','c','r')
  to<-c('z','e','b','r','a','s','c','d','f','g','h','i','j','k','l','m','n','o','p','q','t','u','v','w','x','y')

For example:

original text: the who's 1973

ciphertext: ptv ltn'm 1973

Problem is, that gsub2 replaces some letters twice, (o->f->n and s->z->n), which messes up my ciphertext and makes it almost impossible to decode. Could anyone point out the mistake I'm making? Thanks!

Community
  • 1
  • 1

2 Answers2

7

One way is to use a named vector as the encoding cipher. An easy way to create such a named vector is to use setNames:

cipher <- setNames(to, from)
cipher
  s   l   k   u   m   i   x   j   o   p   n   q   b   v   w   z   f   y   t   g   h   a   e   d   c   r 
"z" "e" "b" "r" "a" "s" "c" "d" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "t" "u" "v" "w" "x" "y" 

For the encoding function, you can use strsplit and paste:

encode <- function(x){
  splitx <- strsplit(x, "")[[1]]
  xx <- cipher[splitx]
  xx[is.na(xx)] <- splitx[is.na(xx)]
  paste(xx, collapse="")
}

encode("the who's 1973")
[1] "ptv ltf'z 1973"
Andrie
  • 176,377
  • 47
  • 447
  • 496
6

You can also use chartr as mentionned in a (popular : 12 ups) answer to the question you quoted:

cipher <- function(x) 
    chartr( "slkumixjopnqbvwzfytghaedcr", "zebrascdfghijklmnopqtuvwxy", x )
Romain Francois
  • 17,432
  • 3
  • 51
  • 77