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
[
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("[")
.)
t(as.matrix(x[1,]))
Should do the trick...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With