R avoid coercion from matrix to numeric [duplicate]
-
06-07-2021 - |
Question
Possible Duplicate:
1-dimensional Matrix is changed to a vector in R
I work with matrix
objects in R and many times it happens that I want to select only one column of a matrix a use it as a matrix
of one column !!! Yes, I mean I don't want R to coerce it automatically to a numeric
class because the meaning is a matrix of 1 column in that case. How to avoid R doing this silly conversion all the time at a general level. I don't want to clutter my code with as.matrix
everywhere !
Solution
Use drop=FALSE
> matrix(1:10, ncol=2)
[,1] [,2]
[1,] 1 6
[2,] 2 7
[3,] 3 8
[4,] 4 9
[5,] 5 10
> matrix(1:10, ncol=2)[, 2]
[1] 6 7 8 9 10
> matrix(1:10, ncol=2)[, 2, drop=FALSE]
[,1]
[1,] 6
[2,] 7
[3,] 8
[4,] 9
[5,] 10
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow