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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With