[R] code to turn T into TRUE

Peter Wolf pwolf at wiwi.uni-bielefeld.de
Fri Oct 18 18:29:54 CEST 2002


Mark wrote:

> Does anyone have code that will methodically process R sourcecode,
turning
> T's into TRUE and F's into FALSE? I got bored doing this by hand,
after the
> first 30-odd functions-- there are hundreds left to do. I don't want
to
> simply deparse everything, because that would destroy my beautiful
> formatting.

Here is another solution based on an R function. You can use it
to change a name of a variable:

rename <- function(name,oldname="T",newname="TRUE"){
  # pw 10/02
  abc1<-c("",".",LETTERS,letters); abc2<-c(abc1,as.character(0:9))
  dump(name); fns<-scan("dumpdata.R","",sep="\n")
  if(0==length(matches<-grep(oldname,fns))) return("no changes")
  match.lines<-fns[matches]; changes<-0
  for(i in 1:length(match.lines)){
    line<-strsplit(paste("",match.lines[i],""),oldname)[[1]]
    h1<-sapply(line,function(x)any(substring(x,1,        1)
==abc2))

h2<-sapply(line,function(x)any(substring(x,nchar(x),nchar(x))==abc1))
    h <- h1[-1] | h2[-length(h2)]; changes<-changes+sum(!h)

line<-paste(rbind(c("",c(newname,oldname)[1+h]),line)[-1],collapse="")
    match.lines[i]<-substring(line,2,nchar(line)-1)
  }
  fns[matches]<-lapply(match.lines,paste,collapse="")
  eval(parse(text=unlist(fns)),envir=sys.parent())
  return(paste(changes,"changes"))
}

Example:

> rename("rename","oldname","OLD")
Read 18 items
[1] "4 changes"
> rename
function(name,OLD="T",newname="TRUE"){
  # pw 10/02
  abc1<-c("",".",LETTERS,letters); abc2<-c(abc1,as.character(0:9))
  dump(name); fns<-scan("dumpdata.R","",sep="\n")
  if(0==length(matches<-grep(OLD,fns))) return("no changes")
  match.lines<-fns[matches]; changes<-0
  for(i in 1:length(match.lines)){
    line<-strsplit(paste("",match.lines[i],""),OLD)[[1]]
    h1<-sapply(line,function(x)any(substring(x,1,        1)
==abc2))

h2<-sapply(line,function(x)any(substring(x,nchar(x),nchar(x))==abc1))
    h <- h1[-1] | h2[-length(h2)]; changes<-changes+sum(!h)
    line<-paste(rbind(c("",c(newname,OLD)[1+h]),line)[-1],collapse="")
    match.lines[i]<-substring(line,2,nchar(line)-1)
  }
  fns[matches]<-lapply(match.lines,paste,collapse="")
  eval(parse(text=unlist(fns)),envir=sys.parent())
  return(paste(changes,"changes"))
}


Peter Wolf

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list