Computing the variance of each column of a matrix

In a previous blog post about computing confidence intervals for rankings, I inadvertently used the VAR function in SAS/IML 9.22, without providing equivalent functionality for those readers who are running an earlier version of SAS/IML software. (Thanks to Eric for pointing this out.)

If you are using a version of SAS/IML prior 9.22, the following module computes the variance of each column of a matrix, and correctly handles missing values in the data:

/** Var: return sample variance of each column of a data matrix **/
/** For this module
  x is a matrix that contains the data
start Var(x);
   mean = x[:,];
   countn = j(1, ncol(x)); /** allocate vector for counts **/
   do i = 1 to ncol(x); /** count nonmissing values **/
      countn[i] = sum(x[,i]^=.); /** in each column **/
   var = (x-mean)[##,] / (countn-1);
return ( var );

This module appears in Appendix D of my book, Statistical Programming with SAS/IML Software.

tags: Data Analysis


  1. Anthony Bongard
    Posted April 24, 2014 at 5:06 pm | Permalink

    This is calculating the variance of each column of the matrix but I am not getting any sort of output.
    Is it just in my log? how to I get the variance to show up in an output/results form?

    • Posted April 25, 2014 at 6:21 am | Permalink

      You can print the matrix to display its contents:
      v = var(x);
      print v;

One Trackback

  1. [...] to SAS/IML 9.22, statistical programmers could use a module to compute the sample variance of each column of a matrix. The VAR function is more efficient, but the results are the same. The following statement computes [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>