R: a subset of N-dimensional arrays

Consider the following three-dimensional array:

set.seed(123)
arr = array(sample(c(1:10)), dim=c(3,4,2))

what gives

> arr
, , 1

     [,1] [,2] [,3] [,4]
[1,]   10    9    8    2
[2,]    5    1    4   10
[3,]    6    7    3    5

, , 2

     [,1] [,2] [,3] [,4]
[1,]    6    7    3    5
[2,]    9    8    2    6
[3,]    1    4   10    9

I would like to multiply it as

arr[c(1,2), c(2,4), c(1)]

but the trick is that I don’t know (a) which indexes or (b) the dimension of the indexes.

What is the best way to access an N-dimensional array with index variables?

ll = list(c(1,2), c(2,4), c(1))

arr[ll]              # doesn't work
arr[grid.expand(ll)] # doesn't work
# ..what else?
+4
source share
2 answers

use do.callfor example:

do.call(`[`, c(list(arr), ll))

or more cleanly using the wrapper function:

getArr <- function(...) 
   `[`(arr, ...)

do.call(getArr, ll)

     [,1] [,2]
[1,]   10    5
[2,]    7    3
+3
source

The package abindhas a function asub:

library(abind)
asub(arr, ll)

, , (fooobar.com/questions/352003/...). .

+1

Source: https://habr.com/ru/post/1524379/