1

I have a multidimensional array, and I (finally) know I can subset it with a matrix, which has as many columns as there are dimensions in the array. But I need to skip a dimension in the process, to get/set not one element of that dimension, but all of them. How to?

array5d[matrix(c(3,15,2,7,9),1)]

is equivalent to

array5d[3,15,2,7,9]

but what is the matrix-based equivalent of

array5d[ ,15,2,7,9]

The goal here is to be able to subset an array with values of a bunch of vectors, that are generated separately. I don't always need to subset with the first dimension left open, this (or rather, these) changes from case to case. I have a very ugly solution with eval(str2lang(paste0(...))), but I would really like a healthier approach

  • Please provide full examples including input in reproducible form and expected output. Please read the information at the top of of the [tag:r] tag page. – G. Grothendieck May 14 '21 at 14:46
  • I asked a similar question at https://stackoverflow.com/questions/53013962/subset-an-array-using-a-vector-of-indices – user2957945 May 14 '21 at 14:58

1 Answers1

3

Simpler reproducible example:

array3d <- array(1:27,dim=c(3,3,3))
x <- array3d[,1,1]

In the comments @user2957945 points out that setting the 'blank' elements of the index vector to TRUE will allow do.call('[',...) to select all of the elements from that dimension.

i <- list(TRUE, 1, 1);  do.call('[', c(list(array3d), i))

Previous (suboptimal) answer:

I don't know if there's a simpler/better way, but this works without using str2lang/eval/etc.:

i <- c(NA,1,1)  ## NA denotes "get all elements from this dimension"
getfun <- function(a,i) {
   i <- as.list(i)
   for (j in seq_along(i)) {
     if (all(is.na(i[[j]]))) i[[j]] <- seq(dim(a)[j])
   }
   v <- as.matrix(do.call(expand.grid,i))
   a[v]
}
getfun(array3d,i)
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453