Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to extract 1x1 array slice as matrix in R?

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, I don't get a matrix but retain the original array:

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...

like image 271
Ott Toomet Avatar asked Dec 25 '22 03:12

Ott Toomet


1 Answers

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
like image 64
alistaire Avatar answered Jan 08 '23 13:01

alistaire