Skip to content

Instantly share code, notes, and snippets.

@ianyfchang
Last active April 1, 2020 04:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ianyfchang/2cd6bf94ae00293fa614e24d4d2bd3c1 to your computer and use it in GitHub Desktop.
Save ianyfchang/2cd6bf94ae00293fa614e24d4d2bd3c1 to your computer and use it in GitHub Desktop.
# https://gist.github.com/bobthecat/5024079
bigcorPar <- function(x, nblocks = 10, verbose = TRUE, ncore="all",pvalue=0.05, ...){
library(ff, quietly = TRUE)
library(psych)
require(doMC)
if(ncore=="all"){
ncore = 30
registerDoMC(cores = ncore)
} else{
registerDoMC(cores = ncore)
}
NCOL <- ncol(x)
## test if ncol(x) %% nblocks gives remainder 0
if (NCOL %% nblocks != 0){stop("Choose different 'nblocks' so that ncol(x) %% nblocks = 0!")}
## preallocate square matrix of dimension
## ncol(x) in 'ff' single format
corMAT <- ff(vmode = "single", dim = c(NCOL, NCOL))
pMAT <- ff(vmode = "single", dim = c(NCOL, NCOL))
## split column numbers into 'nblocks' groups
SPLIT <- split(1:NCOL, rep(1:nblocks, each = NCOL/nblocks))
## create all unique combinations of blocks
COMBS <- expand.grid(1:length(SPLIT), 1:length(SPLIT))
COMBS <- t(apply(COMBS, 1, sort))
COMBS <- unique(COMBS)
## iterate through each block combination, calculate correlation matrix
## between blocks and store them in the preallocated matrix on both
## symmetric sides of the diagonal
results <- foreach(i = 1:nrow(COMBS)) %dopar% {
COMB <- COMBS[i, ]
G1 <- SPLIT[[COMB[1]]]
G2 <- SPLIT[[COMB[2]]]
if (verbose) cat("Block", COMB[1], "with Block", COMB[2], "\n")
flush.console()
#COR <- cor(x[, G1], x[, G2], ...)
tmpCOR <- corr.test(x[, G1], x[, G2], adjust = "none",ci = F,use = "complete", ...)
COR<- tmpCOR$r#[which(tmpCOR$p > pvalue)] <- 0
PVALUE <- tmpCOR$p
corMAT[G1, G2] <- COR
corMAT[G2, G1] <- t(COR)
pMAT[G1, G2] <- PVALUE
pMAT[G2, G1] <- t(PVALUE)
COR <- NULL
PVALUE <- NULL
}
gc()
return(list(cor=corMAT,pvalue=pMAT))
}
@ianyfchang
Copy link
Author

use psych::corr.test to filter p-value less than a threshold

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment