is it possible to have a matrix with 1 row only in R?
Here is my code:
nas <- which(!is.na(y))
x <- x[nas,]
y <- y[nas]
...
You need to specify drop = FALSE
to stop R
coercing a matrix or array to the lowest possible number of dimensions. See ?`[`
for more details.
x <- matrix(1:4,ncol=2)
x[1,]
## [1] 1 2
x[1,,drop=F]
## [,1] [,2]
## [1,] 1 3
Sure it is, as Patrick Li, notes in the comment, but not if you use the vector()
function to create it.
So:
R> matrix(1:4, nrow=1)
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
R> matrix(1:4, ncol=1)
[,1]
[1,] 1
[2,] 2
[3,] 3
[4,] 4
R> matrix(1:4, ncol=2)
[,1] [,2]
[1,] 1 3
[2,] 2 4
R>
For more options regarding use of matrix()
, see its help page. For more on very basic issues (hint: drop=FALSE
), see the R FAQ.