[tech-spec] Re: Nested Loops

  • From: Dirk Eddelbuettel <edd@xxxxxxxxxx>
  • To: tech-spec@xxxxxxxxxxxxx
  • Date: Sat, 13 Nov 2004 09:30:58 -0600

On Fri, Nov 12, 2004 at 11:43:06AM -0800, BBands wrote:
> Is this what you are after?
> 
> for(i in 1:3) {
>     for(j in 2:4) {
>         print(i*j)
>         }
>     }

Which stacks to as many dimensions as you'd like. 

The obligatory comment is of course on loop-alike structures in R. I'm
nowhere as proficient in these as I'd like to be -- loop structures are
conceptually simple, and make following the code easier.  That said, the
above example also works as 

> outer(1:3, 2:4, "*")
     [,1] [,2] [,3]
[1,]    2    3    4
[2,]    4    6    8
[3,]    6    9   12
> 

Where it gets interesting is in the timing. For simplicity, system.time()
will do:

> system.time({for(i in 1:n) for (j in 1:n) a<-i*j})
[1] 160.58   0.20 242.63   0.00   0.00
> system.time(outer(1:n,1:n,"*"))
[1]  1.83  2.64 33.58  0.00  0.00
> 

This is a pathological example, but at least it illustrates that there are
always different ways of writing R code ...

Dirk

-- 
If your hair is standing up, then you are in extreme danger.
      -- http://www.usafa.af.mil/dfp/cockpit-phys/fp1ex3.htm

Other related posts: