Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using drop [R] selectively - only remove specified length-1 dimensions

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.

like image 734
CJB Avatar asked Dec 10 '15 11:12

CJB


1 Answers

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.

like image 110
CJB Avatar answered Oct 18 '22 11:10

CJB