1

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.

am-real
  • 54
  • 6

2 Answers2

3

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])
nicola
  • 24,005
  • 3
  • 35
  • 56
1

I have this one, but I am also sure there should be something more adequate...

A <- array(1:72, dim=c(2,2,3,2,2))
res <- eval(parse(text=paste0("A[,,",paste0(idx,collapse=",")),"]")))

Basically prepare your indexing as string. Opportunity to create a function there.

Eric Lecoutre
  • 1,461
  • 16
  • 25
  • Yeah, I got the idea. I thought about something like this before, but I'm very new in R, so didn't know there is `eval` in R. Sadly, but I thing eval is the only way:( UPD: nicola proposed more adequate solution. But thank you anyway. – am-real Jun 20 '16 at 10:06