Skip to content

Instantly share code, notes, and snippets.

@explodecomputer
Created November 22, 2015 17:46
Show Gist options
  • Save explodecomputer/326e35693131adb681dd to your computer and use it in GitHub Desktop.
Save explodecomputer/326e35693131adb681dd to your computer and use it in GitHub Desktop.
row correlations between two matrices
rowCors = function(x, y)
{
sqr = function(x) x*x
if(!is.matrix(x)||!is.matrix(y)||any(dim(x)!=dim(y)))
stop("Please supply two matrices of equal size.")
x = sweep(x, 1, rowMeans(x))
y = sweep(y, 1, rowMeans(y))
cor = rowSums(x*y) / sqrt(rowSums(sqr(x))*rowSums(sqr(y)))
return(cor)
}
# make two matrices each with 100 CpGs and 200 individuals
matrix1 <- matrix(rnorm(100*200), 100, 200)
matrix2 <- matrix(rnorm(100*200), 100, 200)
# Get the correlation of CpG1 in matrix1 against CpG1 in matrix2
# Get the correlation of CpG2 in matrix1 against CpG2 in matrix2
# Get the correlation of CpG3 in matrix1 against CpG3 in matrix2
# etc
rowCors(matrix1, matrix2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment