LukaszJ
LukaszJ

Reputation: 123

Obtaining matrix row as matrix

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

Answers (2)

Josh O&#39;Brien
Josh O&#39;Brien

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

alexwhan
alexwhan

Reputation: 16036

t(as.matrix(x[1,]))

Should do the trick...

Upvotes: 1

Related Questions