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?
Making use of a little known usage of [
:
When indexing arrays by
[
a single argumenti
can be a matrix with as many columns as there are dimensions ofx
; the result is then a vector with elements corresponding to the sets of indices in each row ofi
.
you can simply do:
pi[matrix(indexes, 1)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With