[R] Help with multidimensional array

Ben Bolker bbolker at gmail.com
Tue Mar 29 04:48:47 CEST 2011


Giuseppe <neox86 <at> gmail.com> writes:

> 
> Dennis,
> 
> Yes, Reduce works, but unfortunately it does not speed up the
> evaluation time (actually, it makes it a little bit slower).
> 
> Thank you anyway.

  I have an alternate solution that I would have expected to
be faster but is actually much slower for this tiny example.  
I even tried testing it on larger matrices: I thought that there
was an outside possibility that the startup takes longer but that it 
scales better with system size
... ?  (I generally think apply/sweep should be faster than Reduce/lapply?)
Oh well.

m <- array(1:27, c(3, 3, 3))
xx <- 1:3

system.time(replicate(1e5,
                      Reduce('+', lapply(xx, function(k) xx[k] * m[, , k]))))
## 5 seconds

system.time(replicate(1e5,
                      apply(sweep(m,3,xx,"*"),c(1,2),sum)))
## 22 seconds



More information about the R-help mailing list