Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace letters with ciphertext ones

Tags:

r

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!

like image 947
user1843519 Avatar asked Dec 11 '22 20:12

user1843519


1 Answers

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"
like image 181
Andrie Avatar answered Jan 03 '23 11:01

Andrie