[R] single row/column-indexing on matrices

Duncan Murdoch murdoch at stats.uwo.ca
Sat Jul 25 00:41:40 CEST 2009


On 24/07/2009 6:34 PM, Murat Tasan wrote:
> hi all - quick question:
> 
> i have a matrix m, say nrow=5, ncol=4.
> in a function i'd like to retrieve certain rows or columns from m, but
> which rows/cols are not known ahead of time.
> the function should return a sub-matrix (i.e. still of class
> 'matrix').
> 
> when selecting a single column (or row), the indexing operation
> converts the object of class 'matrix' into a vector of it's mode.
> 
> e.g.:
> 
> myfun <- function(m, cols) m[,cols];
> m <- matrix(1:20, nrow=5);
> sm <- myfun(m, c(2));
> 
> the last line returns a vector, but i'd like to still get back a
> matrix (of dimensions 5,1).  most of the time i'll be selecting groups
> of rows or cols, so this isn't a problem (as the return value remains
> a matrix), but on rare occasions a single selecting index will be
> passed, causing a problem for code further down that expects the 'sm'
> to be in matrix form (e.g. using the 'apply' function).
> 
> is there any way to preserve the class of the matrix object when
> performing indexing?

Yes, use "drop=FALSE" when doing the indexing:

 > m <- matrix(1:10, 2,5)
 > m[1,]
[1] 1 3 5 7 9
 > m[1,,drop=FALSE]
      [,1] [,2] [,3] [,4] [,5]
[1,]    1    3    5    7    9

Duncan Murdoch




More information about the R-help mailing list