[R] Generating valid R code using R

Henrik Bengtsson hb at stat.berkeley.edu
Sun Jul 16 11:11:02 CEST 2006


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):
second row\t\a\\

fourth and so on...

Now, find escapeString() such that the following piece of code
generates a second file called 'file2.txt' which is identical to

inStr <- readChar("file1.txt", nchars=999)
esStr <- escapeString(inStr)
rCode <- sprintf('cat(file="file2.txt", "%s")', esStr)
cat(file="foo.R", rCode)

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?



More information about the R-help mailing list