Created
June 3, 2014 20:14
-
-
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)`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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