[R] single row/column-indexing on matrices

Murat Tasan mmuurr at gmail.com
Sat Jul 25 00:34:25 CEST 2009


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?




More information about the R-help mailing list