R - how to get a value of a multi-dimensional array by a vector of indices

r

Solution

Making use of a little known usage of `[`:

When indexing arrays by `[` a single argument `i` can be a matrix with as many columns as there are dimensions of `x`; the result is then a vector with elements corresponding to the sets of indices in each row of `i`.

you can simply do:

pi[matrix(indexes, 1)]

Problem

Let's say I have a multi-dimensional array called `pi`, and its number of dimensions isn't known until the runtime: ``` dims <- rep(3, dim_count) pi <- array(0, dims) ``` As you can see the dimension count depends on `dim_count`. How do I retrieve a value from the array when I have a vector of the indexes? For example when I have: ``` dim_count <- 5 indexes <- c(1, 2, 3, 3, 3) ``` I want to retrieve ``` pi[1, 2, 3, 3, 3] ``` Is there a short, effective and hopefully elegant way of doing this?

Original source