4

I have a multi-dimensional array, and the number of its dimensions are unknown until the runtime, for example:

dims <- rep(3, dim_count)
arr <- array(0, dims)

Now, having the dims vector I would like to iterate by all the indexes of the array, for example, having

dims <- c(2,3)

I would like to be able to get a series of vectors:

c(1,1)
c(1,2)
c(1,3)
c(2,1)
c(2,2)
c(2,3)

Or just a function generating the next one from the previous one.

The only three ways I could think of were:

  1. iterate over 1:length(arr) and translate those numbers to the index vectors - in the above example I would be looking for a (preferably built-in) function doing indexesOf(arr, 4) -> c(2,1).

  2. Get the last generated index vector, increment the element on its last position, and make sure it is in the bounds given by dims.

  3. Generate a matrix, the columns of which would contain all the indexes I need.

But, sadly, neither of the first two approaches is fast or elegant. The third one looks like a decent idea, I can do it on paper, but i can't code it in R using rbind and so on.

Is there a good way of doing this, preferably without nested loops?

Just for comparison, my ugly looped implementation of #3:

getAllIndexes = function(dims) {
  dimCount <- length(dims)
  ret <- array(1:dims[1], c(1,dims[1]))
  for(i in 2:length(dims)){
    curdims <- dims[i]

    a <- array(rep(ret, curdims), c(nrow(ret), curdims * ncol(ret) ))
    b <- rep(1:curdims, each=ncol(ret))
    ret <- rbind(a, b, deparse.level=0)
  }
  ret
}
0

1 Answer 1

2

If I'm interpreting your request correctly then

as.matrix(do.call(expand.grid,lapply(dim(arr),seq)))

appears to do #3 ...

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, expand.grid was just what I was looking for :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.