[R] compute variance of every column in a matrix without a loop

Uwe Ligges ligges at statistik.uni-dortmund.de
Mon Mar 18 08:40:53 CET 2002

Thomas Lumley wrote:
> On Sat, 16 Mar 2002, Francisco J Molina wrote:
> > Is it possible to compute the variance of every column in a matrix
> > without a loop?
> No, but you can make it look as if there's no loop.
> You can hide the for() loop inside a function with
>   apply(m, 2, var)
> if the reason you want to avoid a loop is to make your code look simpler.
> In 1.5.0 you will be able to do
>    colMeans(m*m)-colMeans(m)^2

..., but only for well conditioned problems, because using Steiner's
theorem is risky from the computational point of view. Try this extreme
example several times:

  m <- rnorm(10, 1e8, 1e-7) # large mean, small variance
  mean(m^2) - mean(m)^2     # typical results: -4, -2, 0, 2, 4
  var(m)                    # reasonable, about 1e-14

BTW: Of course this is a computational problem that is *not* related to

> if the reason is to have the loop take place in compiled code and be
> faster.

Uwe Ligges
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