[R] Apply command on vectors

Thomas Lumley tlumley at u.washington.edu
Tue May 29 03:39:21 CEST 2001

On Mon, 28 May 2001, Elliot Williams wrote:

> Hi all,
> I keep running into a small problem in my programming, and I'm sure there's
> an elegant way around it...
> I often want to use apply() on a matrix with a variable number of columns. It
> works just fine unless the number of columns is one, in which case the matrix
> becomes a vector, and apply() complains.  Example below:
> -----------------------------
> a.matrix <- matrix(rnorm(6), nc=3)
> matrix.mask <- c(1,2)
> apply(a.matrix[,matrix.mask], 1, mean)  # Works just fine
> matrix.mask <- 1
> apply(a.matrix[,matrix.mask] ,1, mean)  # Fails
> Error in apply(a.matrix[, matrix.mask], 1, mean) :
> 	dim(X) must have a positive length
> -----------------------------
> So what I usually do is explicitly cast the thing as a matrix using,
> as.matrix(), but it's unnecessary in most cases (when the thing is a
> full-fledged matrix)-- extra computation, moving memory around, etc.
> Is there an elegant R fix?  I guess I just want the subset of the matrix to
> retain its matrixiness.

a.matrix[,matrix.mask,drop=FALSE] does what you want.

It's in the FAQ: Why does my matrix lose dimensions?


Thomas Lumley			Asst. Professor, Biostatistics
tlumley at u.washington.edu	University of Washington, Seattle

r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list