[R] updating elements of a list of matrixes without 'for' cycles

Matteo Richiardi Matteo.Richiardi at maths.ox.ac.uk
Sat Jan 30 02:03:30 CET 2016

Hi, following an earlier suggestion from the list, I am storing my
data in a "cube", i.e. an array of matrixes.
Is there any smarter way of updating the elements of the cube through
a function, other than the three 'for' cycles in the example below?
(please note that the example is simplistic; in particular, my
function is more complicated).

# parameters
I <- 2L
J <- 2L
H <- 2L

# data container: an array of matrixes
mycube <- array(dim=c(I,J,H))

# initialisation
for (h in 1:H) {
  init <- matrix(c(rep(0,J)),nrow=I,ncol=J)
  mycube[,,h] <- init

# function
foo = function(i,j,h){
  mycube[i,j,h] <<- i*j*h

# update

for(h in 1:H){
  # males:
  for(i in 1:I)
    for(j in 1:J)

Thanks a lot for your help. Matteo

More information about the R-help mailing list