6

The drop function and the drop argument in the [ subsetting function both work completely or not at all. If I have, for example, a four-dimensional array whose 2nd and 4th dimensions are length 1 only, then drop will return a 2-dimensional array with both these dimensions removed. How can I drop the 4th dimension but not the 2nd?

e.g.

arr <- array(1:4, c(2, 1, 2, 1))
drop(arr)
arr[,,, 1, drop = TRUE]

The reason for doing this in my case is so that I can set up the array correctly for binding to other arrays in abind. In the example given, one might wish to bind arr[,,, 1] to a 3-dimensional array along dimension 2.

CJB
  • 1,759
  • 17
  • 26

1 Answers1

5

I've thought about it some more and come up with a solution. The below function defines the new target dimensions and fits the data into a new array of those dimensions. omit is a vector of dimension numbers never to drop.

library("abind")
drop.sel <- function(x, omit){
  ds <- dim(x)
  dv <- ds == 1 & !(seq_along(ds) %in% omit)
  adrop(x, dv)
}

If anyone thinks they have a more elegant solution, I'd be happy to see it.

CJB
  • 1,759
  • 17
  • 26
  • 3
    Additionally, I've just seen the `adrop` function in the `abind` package. That seems to be designed for this. – CJB Dec 17 '15 at 12:17
  • Edited to incorporate `adrop`, in case anyone's watching! This question was a lonely experience.... Someone obviously liked it though. – CJB Dec 18 '15 at 14:58
  • 1
    I think you've answered your own question well, but another way to do it is to just create a new array, using the old array as data, and specifying whatever dimensions you choose. See my answer here: https://stackoverflow.com/a/53554390/8436923 – Montgomery Clift Nov 30 '18 at 09:23
  • Also check the answers to this question: https://stackoverflow.com/questions/47654316/dont-drop-dimensions-when-subseting-3-dimensional-array – Montgomery Clift Nov 30 '18 at 09:29
  • Good idea. Do you know if either is more memory efficient, in the case of a big array? I suspect it might be similar. On a similar theme, I generally avoid using the `abind` function, preferring just to use `c` and then redefine the dimensions (if binding on the highest dimension). – CJB Nov 30 '18 at 11:10
  • I don't know whether there's a difference in memory-efficiency; sorry. – Montgomery Clift Nov 30 '18 at 11:39