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!
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With