awesome! thanks much! On Jul 24, 6:41 pm, Duncan Murdoch <murd...@stats.uwo.ca> wrote: > 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 > > ______________________________________________ > r-h...@r-project.org mailing listhttps://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guidehttp://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code.
______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.