[R] array construction, avoiding for loop

ripley@stats.ox.ac.uk ripley at stats.ox.ac.uk
Tue Jul 16 19:39:17 CEST 2002

```On Tue, 16 Jul 2002, David Firth wrote:

> Suppose X has dimensions (I,J), and Y has dimensions (J,K).  To construct
> a 3-way array whose (i,j,k)th element is X[i,j]*Y[j,k], is there something
> much more economical than
>
> XY <- outer(X,Y)
> result <- array(0, c(I,J,K))
> for (j in 1:J){
>      result[,j,] <- XY[,j,j,]
> }
>
> This is faster than using three nested for loops, but it still has a for
> loop and a fair amount of redundant calculation/storage for the 4-way
> array XY.
>
> I need to do this lots of times (hence interested in speed), but my arrays
> are typically not large (I, J, K of the order of 10).
>
> I feel I must be missing some trick here.  Any hints welcomed.

You can treat them as vectors:

res <- as.vector(X) * rep(Y, each=I)
dim(res) <- c(I, J, K)

--
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```