[R] Apply command on vectors

Elliot Williams ewilliams at ucsd.edu
Tue May 29 02:38:48 CEST 2001


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.

Thanks,
	Elliot.

-- 
Elliot Williams (ewilliams at ucsd.edu)
Economics Department, UC San Diego
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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