Augustin
Augustin

Reputation: 327

Dropping dimensions in R array

The problem

Let K >= 2 and d >= 3. I have a 3-dimensional array with dimensions c(K,K-1,d).

For example, if K = d = 3,

A <- array(1:18,dim = c(3,2,3)).

Now I want to get a (K-1) x d matrix by selecting an index along the first dimension, e.g.

M <- A[1,,].

If K > 2 it works fine. But if K = 2, the second dimension is 1 and the default behaviour of R is to drop it. Hence, the following code will return a length d vector instead of a matrix.

K <- 2
d <- 3
A <- array(1:6,dim = c(K,K-1,d))
A[1,,]

I need a matrix because I want to do a matrix product.

What I tried

One can force R not to drop dimensions, by using the drop option.

M <- A[1,,,drop = FALSE]
dim(M)

But this returns a 3-dimensional array, as the first dimension is not dropped either.

I also tried to use as.matrix.

M <- as.matrix(A[1,,])
dim(M)

This returns a d x (K-1) matrix instead of the desired (K-1) x d matrix. Well, I could use transposition t() but then it wouldn't work anymore as soon as K>2. Is there an efficient way to get this work whatever the value of K?

Upvotes: 8

Views: 2810

Answers (1)

sieste
sieste

Reputation: 9027

Create an array and explicitly specify the desired dimensions:

array(A[1, , ], dim=c(K-1, d)) 

Upvotes: 4

Related Questions