# rotrw -- a func to read from a file, rot, and write to # a new file # file: name of source file # rot: number to rot by # field: ascii or alpha, selects what characters to rot thru # If select alpha, only alphas are rotted. # If select ascii, all ascii chars are rotted # Set field to either 'ascii' or 'alpha' for charset # # Oct08: embedded all flavors of "rot" into one source file. # Future upgrade: allow an arb. vector to be passed as FIELD, # and in the ELSE clause set "old" to FIELD and do same rot # rotrw<-function(file,rot=13,field=ascii) { readLines(file)->fin if(field=='alpha') { source('rot13.R') rot13(fin,rot)->tempf } else if(field=='ascii') { source('rotit.R') rotit(fin,rot)->tempf } else { stop("Error: ",field,' is unknown type.\n') } # strip the .extension so can get file name and build # output name 'file'[rot].ext strsplit(file,split='\\.')->splitfil# to get file name alone unlist(splitfil)->unfil # makes it a char vector, # so unlist[1] is name, unlist[2] is ext paste(unfil[1],rot,field,'.',unfil[2],sep="")->outname writeLines(tempf,con=outname) } rot13 <- function(string,rot=13){ # Just coerce it. I will only shift alpha chars anyway cstr<-as.character(string) #get fancy: force ROT into 0-25, by shifting negative values and # taking a modulus: rtm<-(rot+(rot<0)*26)%%26 old<-paste(c(letters,LETTERS),collapse="") # this is legal: letters[c(20:26,1:3)], so just fix start and end shift<-c(rtm+1,26,1,rtm) new<-paste(c(letters[shift[1]:shift[2]],letters[shift[3]:shift[4]],LETTERS[shift[1]:shift[2]],LETTERS[shift[3]:shift[4]]),collapse="") rotted<-chartr(old = old, new = new, x = string) return(rotted) } #modified from the seqinr package, allows user to set any rot value rotit <- function(string,rot=13){ library(sfsmisc) #needed for chars8bit() # Just coerce it. cstr<-as.character(string) #get fancy: force ROT into 0-95, by shifting negative values and # taking a modulus: rtm<-(rot+(rot<0)*95)%%95 # OLD is full baseline ASCII char set. Note that it's a vector old<-c(chars8bit(seq(32,126))) # this is legal: x[c(20:26,1:3)], so just fix start and end indices shift<-c(rtm+1,95,1,rtm) new<-paste(c(old[shift[1]:shift[2]],old[shift[3]:shift[4]]),collapse="") rotted<-chartr(old = paste(old,collapse=""), new = new, x = string) return(rotted) }