Ott Toomet - 10 months ago 44

R Question

I am working with 3D arrays. A function takes a 2D array slice (matrix) from the user and visualizes it, using row and column names (the corresponding dimnames of the array). It works fine if the array dimensions are > 1.

However, if I have 1x1x1 array, I cannot extract the slice as a matrix:

`a <- array(1, c(1,1,1), list(A="a", B="b", C="c"))`

a[1,,]

[1] 1

It is a scalar with no dimnames, hence part of the necessary information is missing. If I add

`drop=FALSE`

`a[1,,,drop=FALSE]`

, , C = c

B

A b

a 1

The dimnames are here but it is still 3-dimensional. Is there an easy way to get a matrix slice from 1x1x1 array that would look like the above, just without the third dimension:

`B`

A b

a 1

I suspect the issue is that when indexing an array, we cannot distinguish between 'take 1 value' and 'take all values' in case where 'all' is just a singleton...

Answer

The `drop`

parameter of `[`

is all-or-nothing, but the `abind`

package has an `adrop`

function which will let you choose which dimension you want to drop:

```
abind::adrop(a, drop = 3)
## B
## A b
## a 1
```