Search code examples
rmultidimensional-arraysub-array

R - How to get matrix from multidimensional array


Suppose I've got 5D array arr. To get 2d matrix with fixed 3rd, 4th and 5th indices I do something like: matr = arr[,,3,2,3]. Suppose I've got list of indices idx = c(3,2,3). Is there any way to get same result using idx? Something like matr = arr[,,idx]? I've tried to do it like

idx = c(,, 3, 2, 3);
matr = arr[idx];

But it is obviously wrong.

UPD in a common case array may be more than 5 dimensional. So I need to do this for idx of any size.


Solution

  • You can try:

    do.call("[",c(list(arr,TRUE,TRUE),as.list(idx)))
    

    An example on some data:

    set.seed(123)
    arraydims<-c(5, 3, 6, 3, 4)
    arr<-array(runif(prod(arraydims)),arraydims)
    idx<-c(2,3,2)
    identical(arr[,,2,3,2],do.call("[",c(list(arr,TRUE,TRUE),as.list(idx))))
    #[1] TRUE
    

    You can also exploit the column-major order used by R:

    array(arr[sum(c(1,cumprod(dim(arr)))[3:length(dim(arr))]*(idx-1))+
                seq_len(prod(dim(arr)[1:2]))],dim(arr)[1:2])