Re: [Rd] Fwd: Generating valid R code using R

From: Peter Dalgaard <p.dalgaard_at_biostat.ku.dk>
Date: Sun 16 Jul 2006 - 12:26:30 GMT

"Henrik Bengtsson" <hb@stat.berkeley.edu> writes:

> Sorry, this question was supposed to go to r-devel; move it there now. /HB
>
> ---------- Forwarded message ----------
> From: Henrik Bengtsson <hb@stat.berkeley.edu>
> Date: Jul 16, 2006 11:11 AM
> Subject: Generating valid R code using R
> To: R-help <r-help@stat.math.ethz.ch>
>
>
> Hi,
>
> I'm trying to generate valid R code using R. Parts of the task is to
> read a sequence of characters from file and escape them such that they
> can be put in quotation marks to form a valid R code string. Example:
>
> Let the input file be (four rows containing ASCII 0-255 characters):
> abcdef<tab>ghijk\nlmno
> second row\t\a\\
>
> fourth and so on...
> <EOF>
>
> Now, find escapeString() such that the following piece of code
> generates a second file called 'file2.txt' which is identical to
> 'file1.txt':
>
> inStr <- readChar("file1.txt", nchars=999)
> esStr <- escapeString(inStr)
> rCode <- sprintf('cat(file="file2.txt", "%s")', esStr)
> cat(file="foo.R", rCode)
> source("foo.R")
>
> For instance, quotation marks has to be escaped in order for 'rCode'
> to be valid, same with newlines etc. What's the best way to do this?
> Currently I use an ad hoc sequence of gsub() substitutions to do this,
> but is there a better way to create the 'rCode' string?

I'd look in the direction of deparse/dput, as in

> X

[1] "abc\t\nfoobar\"\n"
> cat(X)

abc
foobar"
> deparse(X)

[1] "\"abc\\t\\nfoobar\\\"\\n\""

-- 
   O__  ---- Peter Dalgaard             ุster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard@biostat.ku.dk)                  FAX: (+45) 35327907

______________________________________________
R-devel@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel
Received on Sun Jul 16 22:29:01 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Sun 16 Jul 2006 - 20:27:56 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.