Skip to content

compute variance of every column in a matrix without a loop

6 messages · Francisco J Molina, Peter Dalgaard, Jonathan Baron +2 more

#
Is it possible to compute the variance of every column in a matrix
without a loop?
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
#
Francisco J Molina <FJMolina at lbl.gov> writes:
apply(m,2,var)
#
Francisco J Molina wrote:
What about
 apply(X, 2, var)

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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
#
On 03/16/02 19:43, Francisco J Molina wrote:
If the matrix is m1,

apply(m1,2,var)

or, with missing data,

apply(m1,2,var,na.rm=T)

In general, apply() and related functions are well worth
understanding.
#
On Sat, 16 Mar 2002, Francisco J Molina wrote:

            
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
if the reason is to have the loop take place in compiled code and be
faster.


	-thomas


-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
#
Thomas Lumley wrote:
..., 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
R!
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._