Replace letters with encrypted texts

I played with the R function gsub2 R: replace characters with gsub, how to create a function? to create 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 instance:

source text: who 1973

ciphertext: ptv ltn'm 1973

The problem is that gsub2 twice replaces a few letters (o-> f-> n and s-> z-> n), which will ruin my encrypted text and make it almost impossible to decode. Can anyone point out the error I'm making? Thanks!
+4
source share
2 answers

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

 cipher <- setNames(to, from) cipher slkumixjopnqbvwzfytgh aedcr "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 1973") [1] "ptv ltf'z 1973" 
+7
source

You can also use chartr as indicated in the answer (popular: 12 take-offs) to the question you asked:

 cipher <- function(x) chartr( "slkumixjopnqbvwzfytghaedcr", "zebrascdfghijklmnopqtuvwxy", x ) 
+6
source

Source: https://habr.com/ru/post/1447618/


All Articles