Is there a way of elegantly specify a slice in a multidimensional array in R, whereby the number of dimensions is not known beforehand?
For instance, for a 5-dimensional array, slicing out the last dimension can be done using
fourdimslice <- fivedimarray[,,,,1]
but I'l like to code this for arbitrary dimensions, something like
slice <- arbitrarydimarray(dim=5, index=1)
I've not been able to understand if do.call('[', ...)
would be an approach. I've also tried named dimensions, but a[fifth=1]
is not interpreted the way I would want here.
I suppose functions like apply()
need to do similar things.
You can use
asub
, from theabind
package.Here is a bizarre solution to extract the first slice
If you don't want to use the
abind
package, it looks like you can use a two-liner based onslice.index
. I don't know which is more efficient ...Or:
This extracts the right elements but the dimensions get lost. To restore them:
(You could obviously wrap this in an appropriate function.) Test: