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:
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 doingindexesOf(arr, 4) -> c(2,1).Get the last generated index vector, increment the element on its last position, and make sure it is in the bounds given by
dims.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
}