[R] paste an unevaluated expression

Gabor Grothendieck ggrothendieck at gmail.com
Mon Oct 18 09:34:00 CEST 2010


On Mon, Oct 18, 2010 at 3:12 AM, Lorenzo Cattarino
<l.cattarino at uq.edu.au> wrote:
> Thanks for your reply. However, I have only told you half of the story.
>
> My intention was to create a function that outputs 10 different .RData
> file. These output files need to contain similar command lines (one
> "apply" and one "save" command) but with slightly different arguments.
> This is what I wrote:
>
> Start <- 1
> End <- 120
>
> for (i in 1:10)
> {
>  object.result <- paste('Result', i, sep="")
>
>  section <- paste('apply', '(', 'exp.des[', Start, ':', End, ',], 1,
> one.row, parms=parameters)')
>
>  Apply <- paste(object.result, section, sep=" <- ")
>
>  Save <- format(substitute(save(result1,
> file='/home/uqlcatta/pbs/result1.RData')))
>
>  path <- '//atlas2/Research/Lorenzo Cattarino/PhD/myR/R_laboratory/'
>  output <- paste(path, object.result, sep = "")
>
>  write(paste(Apply,Save), paste(output, 'R', sep = "."))
>
>  Start <- Start + 120
>  End <- End + 120
> }
>
> As you can see, apart from an extremely repetitive use of "paste", the
> function works. However there are several problems:
>
> 1. I could not find the way to change the arguments of the Save object
> (e.g. result1 and .../result1.RData for first output file; result2 and
> .../result2.RData for second output, and so forth)
> 2. I did not know how to put together the Apply and Save objects in the
> final command, in a way that resemble two executable lines (each on a
> different line, and not one behind each other on the same line, like
> they    are now)
> 3. I was also wondering about a more elegant way to write the function
> (which looks sort of inefficient to me???).
>
> Thanks very much for your help

Get rid of the substitute and format and just construct whatever
strings you need using paste or sprintf.   Use \n for a newline.  File
names can be constructed the same way.

i <- 1; Start <- 1; End <- 100
s <- sprintf("Result%d <- apply(exp.des[%d:%d,], ...\nMore stuff", i,
Start, End)
s

-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list