[R] Paste in a FOR loop

Stavros Macrakis macrakis at alum.mit.edu
Wed Dec 31 16:07:14 CET 2008


On Wed, Dec 31, 2008 at 6:12 AM, Michael Pearmain <mpearmain at google.com> wrote:
> summary(z.out.1)
> summary(s.out.1)
> hist(s.out.1$qi$ev)...
> This seemed a rather long winded way of doing things to me and a simple for
> loop should handle this, as later i want it to be dynamic for a number of
> groups so my new code is(not working):
...
> for(group in 1:3){
> paste("summary(z.out.", group, sep = "")
> paste("summary(s.out.", group, sep = "")
> paste("s.out.",group,"$qi$ev", sep = "")

This just constructs strings.  You actually want to call "summary" on
the value of the variable z.out.1 etc., so constructing the string
"z.out.1" or "summary(z.out.1" [sic] doesn't help.  To call summary on
the value of the variables, you can use:

     summary( get(paste("z.out",group,sep="")) ) ...

But in general, if you're not doing real meta-programming, the
presence of a "get" or even worse an "eval" in your code generally
indicates that you're not organizing your data appropriately.  Why not
have z.out be a *list* of values, so you can just write

    for (group in 1:3) { summary(z.out[[group]]); ...}

Hope this helps,

          -s



More information about the R-help mailing list