# ROT cipher generator/cracker in R

The ever-clever Alex (my wife, dontcha know) sent me a sweet message of garbled gibberish letters with “ROT-13” at the end of it. Naturally, I googled. She used a ROT-13 cipher, which is a simple letter substitution cipher.

Of course, I could have just written the alphabet down on a piece of paper, taken two minutes, and read her (very sweet, as it turns out) message, but where’s the fun in that? Instead, I wrote an R function to generate or crack ROT-style ciphers.

To use this, you enter two arguments: the cipher text and then an integer indicating how many letters to the right (positive integer) or left (negative integer) the function should look for the “right” letter.

Example: My name, Darrin Rogers, is “yvmmdi mjbzmn” if I substitute each letter with the one 5 to the “left” of it in the alphabet. That message can be decrypted (after loading the function in R) with this code:

rot.n(“yvmmdi mjbzmn”, 5)

You can further test out the function with this string, each character encoded with the letter 9 positions away from it in the alphabet:

“evmvi xfeer xzmv pfl lg, evmvi xfeer cvk pfl xf”

Here’s the code.

No guarantees my code is very good; in fact, I’m sure it has problems and definitely lots of inefficiency. But here it is, anyway ðŸ™‚

```# rot cipher encrypter/decrypter
# specify how many letters displaced (i.e., before or after cipher letter)

rot.n <- function(x, displacement) {
Â  # x = string
Â  # displacement = number of characters to displace (can be + or - I think)

Â  # get multiplier (1 or -1) for "wrapping" around ends of alphabet later
Â  dsign <- displacement / abs(displacement)
Â  # lowercase
Â Â  x <- tolower(x)
Â Â  # split characters into individuals
Â Â  xs <- unlist(strsplit(x, split=""))
Â Â  # get number positions (original)
Â Â  xn <- sapply(xs, function(n) {
Â Â Â Â  ifelse(n %in% letters, {
Â Â Â Â Â Â Â  which(letters == n)
Â Â Â Â Â Â  }, {
Â Â Â Â Â Â Â Â  NA
Â Â Â Â Â Â  })
Â Â Â Â  })
Â Â  # raw displacement (can go outside 1:26 range)
Â Â  xd <- xn + displacement

Â Â  # replace with new letternumber index values
Â Â  xnn <- sapply(xd, function(d) {
Â Â Â Â  ifelse(d %in% (1:26), {
Â Â Â Â Â Â Â Â Â  d
Â Â Â Â Â Â Â  }, {
Â Â Â Â Â Â Â Â Â  d - 26 * dsign
Â Â Â Â Â Â Â Â  })
Â Â  })

Â Â  xl <- letters[xnn]
Â Â  xl[which(is.na(xl))] <- xs[which(is.na(xl))]
Â Â  out <- paste(xl, collapse="")
Â Â  return(out)

}```