Reputation: 123
What is the shortest way to obtain row from matrix as matrix?
> x<-matrix(1:9,nrow=3,byrow=TRUE)
> x
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
> x[1,]
[1] 1 2 3
> is.vector(x[1,])
[1] TRUE
where I'd like to get
[,1] [,2] [,3]
[1,] 1 2 3
Upvotes: 6
Views: 381
Reputation: 162411
[
takes a drop
argument controlling whether the extracted subset will be coerced (if possible) to a lower dimensional object (in this case a plain vector). To ensure that a subset of a matrix will always be a matrix, set it drop=FALSE
, like this:
x[1,,drop=FALSE]
[,1] [,2] [,3]
[1,] 1 2 3
(And for the full set of subsetting rules and arguments, try help("[")
.)
Upvotes: 17