Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subsetting R array: dimension lost when its length is 1

Tags:

r

subset

When subsetting arrays, R behaves differently depending on whether one of the dimensions is of length 1 or not. If a dimension has length 1, that dimension is lost during subsetting:

ax <- array(1:24, c(2,3,4))
ay <- array(1:12, c(1,3,4))
dim(ax)
#[1] 2 3 4
dim(ay)
#[1] 1 3 4
dim(ax[,1:2,])
#[1] 2 2 4
dim(ay[,1:2,])
#[1] 2 4

From my point of view, ax and ay are the same, and performing the same subset operation on them should return an array with the same dimensions. I can see that the way that R is handling the two cases might be useful, but it's undesirable in the code that I'm writing. It means that when I pass a subsetted array to another function, the function will get an array that's missing a dimension, if I happened to reduce a dimension to length 1 at an earlier stage. (So in this case R's flexibility is making my code less flexible!)

How can I prevent R from losing a dimension of length 1 during subsetting? Is there another way of indexing? Some flag to set?

like image 621
Mars Avatar asked Oct 05 '12 23:10

Mars


1 Answers

As you've found out by default R drops unnecessary dimensions. Adding drop=FALSE while indexing can prevent this:

> dim(ay[,1:2,])
[1] 2 4
> dim(ax[,1:2,])
[1] 2 2 4
> dim(ay[,1:2,,drop = F])
[1] 1 2 4
like image 131
Dason Avatar answered Nov 09 '22 01:11

Dason