Skip to content

Instantly share code, notes, and snippets.

@daskelly
Created September 27, 2017 18:07
Show Gist options
  • Save daskelly/e015eeb8514b7c5e3140ad8374e74f62 to your computer and use it in GitHub Desktop.
Save daskelly/e015eeb8514b7c5e3140ad8374e74f62 to your computer and use it in GitHub Desktop.
mini <- matrix(rnorm(4000*50), nrow=4000, ncol=50)
system.time(M <- cor(t(mini), t(mini), method='pearson'))
fastcorr <- function(x) {
# fast correlation between rows of x
# from http://stackoverflow.com/questions/18964837/fast-correlation-in-r-using-c-and-parallelization
if (!is.matrix(x)) x <- as.matrix(x)
x <- x - rowMeans(x)
x <- x/sqrt(rowSums(x^2))
tcrossprod(x)
}
system.time(M2 <- fastcorr(mini))
all.equal(M, M2) # fastcorr is significantly faster. Even better if you compile R using fast BLAS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment