Q:

Substitution Encryption/Decryption in R

Using the variables alpha and key, encrypt ptext into a variable named ctext. Using substitution cipher
So I have a text file separated in a vector

ptext <- strsplit(ptext,split = "", fixed = TRUE)
ptext <- unlist(ptext)

I also created a key for this cipher
key <- "ZGYHXIWJVKULTMSARBQCPDOENF"
key <- unlist(strsplit(key,""))
and an Alphabet vector for the key

alpha <- "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
alpha <= toupper(alpha)
alpha <- unlist(strsplit(alpha,""))

Now my goal is to try to replace all the character in the ptext vector corresponding to the letters in the key in relation to alpha (Example: A in alpha in relation to Z in the key. So all A's in the text would be replaced by a Z)
I know I am supposed to match the alpha in key
cipher <- match(key,alpha)

Now my issue is, the ptext file is over 1000 characters in it. How would I be able to replace all the letters in that vector?

A:

You could use chartr which will avoid splitting the string and pasting back.
ptext <- 'REQWDSFFFSLK'
alpha <- 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
key   <- 'ZGYHXIWJVKULTMSARBQCPDOENF'

chartr(alpha, key, ptext)
#[1] "BXROHQIIIQLU"

Here, all R is replaced with B, E with X and so on for every character value. 

