Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use drop = F correctly in R to preserve matrix structure when subsetting [closed]

Tags:

r

subset

I want to preserve the matrix (or array) structure after subsetting, and it was my understanding that this was achieved with the parameter drop = F. However, this does not seem to be the case:

> m = matrix(1:8, 4)             # Toy example
> m
     [,1] [,2]
[1,]    1    5
[2,]    2    6
[3,]    3    7
[4,]    4    8
> is.matrix(m[1:2,])             # Subsetting first 2 rows yields a matrix
[1] TRUE
> is.matrix(m[1,])               # Subsetting just one row yields a vector
[1] FALSE
> is.matrix(m[1,,drop=F])        # drop=F does not help!
[1] FALSE
like image 955
Antoni Parellada Avatar asked Oct 18 '25 16:10

Antoni Parellada


1 Answers

According to ?logical

TRUE and FALSE are reserved words denoting logical constants in the R language, whereas T and F are global variables whose initial values set to these. All four are logical(1) vectors.

So, as we mentioned in the comments, if we create an object with 'F' earlier and then use drop=F, this will result in the specific problem

F <- 1
is.matrix(m[1,,drop=F]) 
#[1] FALSE

It is always better to use TRUE/FALSE instead of substring T/F for this particular problem because we cannot assign the reserved words as object name i.e.

TRUE <- 5

Error in TRUE <- 5 : invalid (do_set) left-hand side to assignment

FALSE <- 1

Error in FALSE <- 1 : invalid (do_set) left-hand side to assignment

is.matrix(m[1,,drop=FALSE]) 
#[1] TRUE
like image 56
akrun Avatar answered Oct 20 '25 05:10

akrun