[tech-spec] Re: Nested Loops

  • From: Tom McCubbin <tmccubbin@xxxxxxxxxxxxxxxx>
  • To: tech-spec@xxxxxxxxxxxxx
  • Date: Sun, 14 Nov 2004 10:08:23 -0500

Not to beat a dead horse w/ Dirk, but where performance is critical,
when using an interpreted language such as R, avoid explicit looping in favor of implicit loops.

outer(...) also loops, but not w/in the interpreted construct of the R runtime. It would appear here in fact there there is an exceedingly large difference (~100x) which is considerably worse than many other interpreted languages.


ps - Dirk, that's not pathological...that's proper. Achieving a result through brut force does not make it correct, imho.

Dirk Eddelbuettel wrote:

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) {

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


[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 ...


Other related posts: