R: subsetting N-dimensional arrays

indexing, multidimensional-array, r

Solution

use `do.call`, such as:

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

or more cleanly, using a wrapper function:

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

do.call(getArr, ll)

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

Problem

Consider the following 3-dimensional array: ``` set.seed(123) arr = array(sample(c(1:10)), dim=c(3,4,2)) ``` which yields ``` > 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'd like to subset it like ``` arr[c(1,2), c(2,4), c(1)] ``` but the catch is that I don't know (a) which indices or (b) which dimension the indices are. 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? ```

Original source

Related problems