Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: preserving 1-row / -column matrix [duplicate]

Tags:

r

matrix

subset

Given a matrix with one row, one column, or one cell, I need to reorder the rows while keeping the matrix structure. I tried adding drop=F but it doesn't work! What did I do?

test = matrix(letters[1:5]) # is a matrix
test[5:1,,drop=F]           # not a matrix

test2 = matrix(letters[1:5],nrow=1) # is a matrix
test2[1:1,,drop=F]                  # not a matrix

test3 = matrix(1)  # is a matrix
test3[1:1,,drop=F] # not a matrix
like image 569
dasf Avatar asked Jan 28 '23 22:01

dasf


1 Answers

I'd guess it was an overwritten F; F can be set as a variable, in which case it's no longer false. Always write out FALSE fully, it can't be set as a variable.

See Is there anything wrong with using T & F instead of TRUE & FALSE?

Also the R Inferno, section 8.1.32, is a good reference.

> F <- 1
> test = matrix(letters[1:5]) # is a matrix
> test[5:1,,drop=F]           # not a matrix
[1] "e" "d" "c" "b" "a"
> test[5:1,,drop=FALSE]       # but this is a matrix
     [,1]
[1,] "e" 
[2,] "d" 
[3,] "c" 
[4,] "b" 
[5,] "a" 
> rm(F)
> test[5:1,,drop=F]           # now a matrix again
     [,1]
[1,] "e" 
[2,] "d" 
[3,] "c" 
[4,] "b" 
[5,] "a" 
like image 149
Aaron left Stack Overflow Avatar answered Jan 31 '23 10:01

Aaron left Stack Overflow