Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement ROT-13 in R

Tags:

string

r

I'd like a function, that when passed a string containing only letters, rotates each letter in the string through the alphabet by X characters, where X is a parameter of the function. The famous instance of this is when X=13, which is called ROT-13

function <- ROTx(str,x) { ?? }

It's the kind of thing that I'd expect an R wizard could do in just a few lines, whereas I'd end up with 10 or more.

like image 590
Alex Holcombe Avatar asked Jan 21 '23 16:01

Alex Holcombe


1 Answers

See ?chartr (Examples section):

rot <- function(ch, k = 13) {
   p0 <- function(...) paste(c(...), collapse="")
   A <- c(letters, LETTERS, " '")
   I <- seq_len(k)
   chartr(p0(A), p0(c(A[-I], A[I])), ch)
}

or here http://rosettacode.org/wiki/Rot-13#R:

rot13 <- function(x)
{
  old <- paste(letters, LETTERS, collapse="", sep="")
  new <- paste(substr(old, 27, 52), substr(old, 1, 26), sep="")
  chartr(old, new, x)
}
like image 171
rcs Avatar answered Jan 30 '23 18:01

rcs