Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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?

like image 837
nietaki Avatar asked Jun 02 '12 19:06

nietaki


1 Answers

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)]
like image 199
flodel Avatar answered Sep 22 '22 19:09

flodel