Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining matrix row as matrix

Tags:

r

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
like image 943
LukaszJ Avatar asked May 05 '13 23:05

LukaszJ


2 Answers

[ 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("[").)

like image 177
Josh O'Brien Avatar answered Oct 24 '22 07:10

Josh O'Brien


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

Should do the trick...

like image 34
alexwhan Avatar answered Oct 24 '22 07:10

alexwhan