开发者

Implement ROT-13 in 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.


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)
}


rotX <- function(ch,x) 
{ #rotate each letter of a string ch by x letters thru the alphabet, as long as x<=13
  old <- paste(letters, LETTERS, collapse="", sep="")
  new <- paste(substr(old, 2*x+1, 26*2), substr(old, 1, 26), sep="")
  chartr(old, new, ch)
}

This fixes both of the problems I noted in my comment.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜