Skip to content

Instantly share code, notes, and snippets.

@lendle
Created June 3, 2014 20:14
Show Gist options
  • Save lendle/b88d6c39ab56dc68b668 to your computer and use it in GitHub Desktop.
Save lendle/b88d6c39ab56dc68b668 to your computer and use it in GitHub Desktop.
Calculates the variance of columns of a matrix in a single pass, implemented with Rcpp. Much faster than `apply(x, 2, var)`
library(Rcpp)
cppFunction('NumericVector colVars(NumericMatrix x) {
int nrow = x.nrow(), ncol = x.ncol();
NumericVector out(ncol);
for (int j = 0; j < ncol; j++) {
double mean = 0;
double M2 = 0;
int n;
double delta, xx;
for (int i = 0; i < nrow; i++) {
n = i+1;
xx = x(i,j);
delta = xx - mean;
mean += delta/n;
M2 = M2 + delta*(xx-mean);
}
out(j) = M2/(n-1);
}
return out;
}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment