Michael Schubert
Michael Schubert

Reputation: 2796

R: subsetting N-dimensional arrays

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?

Upvotes: 4

Views: 336

Answers (2)

flodel
flodel

Reputation: 89057

There is the asub function from the abind package:

library(abind)
asub(arr, ll)

which can also do a lot more, in particular extract along a subset of the dimensions (https://stackoverflow.com/a/17752012/1201032). Worth having in your toolbox.

Upvotes: 1

Ricardo Saporta
Ricardo Saporta

Reputation: 55350

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

Upvotes: 3

Related Questions