Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't drop dimensions when subseting 3-dimensional array

Tags:

Let A be a 1 x 2 x 2-array:

> A <- array(0, dim=c(1,2,2))
> A
, , 1

     [,1] [,2]
[1,]    0    0

, , 2

     [,1] [,2]
[1,]    0    0

Then A[,,1] is dimensionless:

> A[,,1]
[1] 0 0

I would like to have:

     [,1] [,2]
[1,]    0    0

The drop argument does not yield what I want:

> A[,,1,drop=FALSE]
, , 1

     [,1] [,2]
[1,]    0    0

I find that annoying. And buggy, because R identifies vectors to column matrices, not to row matrices.

Of course I could do matrix(A[,,1], 1, 2). Is there a more convenient way?

like image 230
Stéphane Laurent Avatar asked Dec 05 '17 13:12

Stéphane Laurent


2 Answers

We can just assign the dim based on the MARGIN we are extracting

`dim<-`(A[, ,1], apply(A, 3, dim)[,1])
 #     [,1] [,2]
 #[1,]    0    0

Using another example

B <- array(0, dim = c(2, 1, 2))
`dim<-`(B[, ,1], apply(B, 3, dim)[,1])
 #    [,1]
#[1,]    0
#[2,]    0

If we are using a package solution, then adrop from abind could get the expected output

library(abind)
adrop(A[,,1,drop=FALSE], drop = 3)
#      [,1] [,2]
# [1,]    0    0

adrop(B[,,1,drop=FALSE], drop = 3)
#     [,1]
#[1,]    0
#[2,]    0
like image 122
akrun Avatar answered Sep 20 '22 13:09

akrun


t(A[,,1])
 [,1] [,2]
[1,]    0    0

I though of it from your comment that R identifies vector to column matrix. I think transpose it gives what you want, and is a bit more convenient.

like image 22
denis Avatar answered Sep 23 '22 13:09

denis