[R] Lost backslashes in parse()

Thomas Lumley tlumley at u.washington.edu
Fri Nov 2 17:27:12 CET 2001

On Fri, 2 Nov 2001, David Brahm wrote:

> Hi all,
>    Yesterday I gave this 5-line example of a script that returns TRUE in Unix
> (R-1.3.0 on Solaris 2.6) but FALSE in NT (R-1.3.1):
> R> fnam <- tempfile()
> R> file.create(fnam)
> R> txt <- paste("file.exists(\"", fnam, "\")", sep="")
> R> expr <- parse(text=txt)
> R> eval(expr)
> Thanks to Thomas Lumley <tlumley at u.washington.edu> and Brian D. Ripley
> <ripley at stats.ox.ac.uk> for responding.  Both asked why lines 3-5 weren't
> just replaced by the much simpler:
> R> file.exists(fnam)
> The short answer is that this was a toy, and in the real situation I need to
> eval() in a different environment.
> If nobody else is disturbed by this behavior in parse(), I can easily work
> around it, so don't worry about it.  For anyone masochistic enough to dig
> further, though, here's a snippet of the real code:
> R> for (i in obj) {
> R>  file <- file.path(dir, "data", paste(i,"RData",sep="."))
> R>  expr <- parse(text=paste("save(list=\"",i,"\", file=\"",file,"\")",sep=""))
> R>  eval(expr, pos.to.env(pos))
> R> }
> Since the object named in "i" may exist somewhere besides "pos", I need to
> eval() the save() command in the environment of position "pos".  But in that
> environment, "i" and "file" don't exist, so I need to build the command ahead
> of time as a text string [i.e. evalq() won't work].  Again, this all works OK
> for me except for backslash dropping in NT.  Thanks again for listening!

That makes a lot more sense.

You can often do this sort of thing more easily with substitute rather
than deparsing and reparsing.
  file<-file.path(dir, "data", paste(i,"RData",sep="."))
  expr<-substitute(save(list=i,file=file), list(i=i,file=file))
  eval(expr, pos.to.env(pos))


Thomas Lumley			Asst. Professor, Biostatistics
tlumley at u.washington.edu	University of Washington, Seattle

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