[R] matrix with ncol=1

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri Feb 1 19:15:46 CET 2002


On Fri, 1 Feb 2002, Christian Hennig wrote:

> Hello list,
>
> I try to optimize some R code and it turns out that the function as.matrix
> takes a lot of time in my code. There is only one reason why I need
> as.matrix: My code should work for matrices with ncol=p and p should be
> allowed to be 1 or larger.
>
> Now I have a matrix x with dim(x)=(n,p), and
> I need to work with the submatrix y <-x[gv,], (gv a vector of
> n logicals) and to calculate cov(y) and other functions for matrices.
> Unfortunately, if p=1, y is no longer a matrix, cov(y) gives an error,
> and therefore I use y <- as.matrix(x[gv,]) which makes my program
> surprisingly slower (this is because lots of gv-vectors are needed).

You intended x[gv,,drop=FALSE], I believe.

> Is there any way to handle submatrices of matrices with p=1 in the same
> manner than with p>1 without using as.matrix?

Yes.  Omitting drop=F(ALSE) is a common mistake in S/R programming.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

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