[R] Apply command on vectors

kjetil halvorsen kjetilh at umsanet.edu.bo
Tue May 29 16:59:12 CEST 2001


Hola!try something like

apply(a.matrix[,matrix.mask, drop=FALSE], 1, mean)

and see he help and examples of ?"["

Kjetil Halvorsen

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.
> 
> 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
> _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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