[R] Lattice plot within a "for" loop does not happen?

Deepayan Sarkar deepayan at stat.wisc.edu
Fri May 13 17:45:06 CEST 2005

On Friday 13 May 2005 09:24 am, Barry Rowlingson wrote:
> > BUT, when I stick this in a loop, I get a bunch of blank graphics
> > devices. This happens even if the loop only executes once. I could  just
> > go through and do these one by one, but I was curious if I was
> > overlooking something obvious. Thank you for any advice.
>   You're overlooking something like line 800 of the documentation for
> xyplot:

As well as the much much shorter help(Lattice), which has: 


     High level Lattice functions (like 'xyplot') are different from
     conventional S graphics functions because they don't actually draw
     anything. Instead, they return an object of class ``trellis''
     which has to be then 'print'ed. This often causes confusion when
     the high level functions are called inside another function (most
     often 'source') and hence don't produce any output.

This page is pointed to from every conceivable place, including the 
Description, which says:

Description:   Implementation of Trellis Graphics. See ?Lattice for a
               brief introduction

> [...]
>   So wrap your xyplot call in a print() function inside your loop:
>   for(i in 1:10){
>     print(xyplot(....whatever....))
>   }
>   Its probably in the R-FAQ as well, since my original feeling was that
> this behaviour was chosen in order to confuse people and see how many
> people read the FAQ... :)

No comments on that :)

However, let's say I want to use pseudo-random numbers to study the behaviour 
of sample correlation in uncorrelated observations. To this end, I do:

> cor(rnorm(10), rnorm(10))
[1] 0.3899596

I do it a few more times:

> cor(rnorm(10), rnorm(10))
[1] 0.6481215
> cor(rnorm(10), rnorm(10))
[1] -0.02100718
> cor(rnorm(10), rnorm(10))
[1] -0.01141006

but then I get tired and try:

> for (i in 1:10) {
+   cor(rnorm(10), rnorm(10))
+ }

resulting in nothing!!! 

Strange how no one ever (or at least any more) complains about this behavour, 
which should be exactly as ``confusing''. 

The upshot, of course, can be summarized by a now famous observation made 
slightly more than a decade ago:



More information about the R-help mailing list