Skip to content

Instantly share code, notes, and snippets.

@shujishigenobu
Last active August 29, 2015 14:20
Show Gist options
  • Select an option

  • Save shujishigenobu/ebab87656cfed074f305 to your computer and use it in GitHub Desktop.

Select an option

Save shujishigenobu/ebab87656cfed074f305 to your computer and use it in GitHub Desktop.
Uncentered Pearson correlation coefficient = cosine (Eisen correlation)
cosine.coef <- function(x,y){
a <- sum(na.omit(x * y)) / sqrt(sum(na.omit(x)^2) * sum(na.omit(y)^2))
return(a)
}
cosine.table <- function(x) {
numberOfPoints <- ncol(x)
columnNames <- colnames(x)
distanceTable <- matrix(data = NA, nrow = numberOfPoints, ncol = numberOfPoints,
dimnames = list( columnNames, columnNames ) )
for ( i in 1:(numberOfPoints-1) ) {
for ( j in (i+1):numberOfPoints ) {
v1 <- x[ , i]
v2 <- x[ , j]
d <- 1 - cosine.coef(v1, v2)
distanceTable[i, j] <- d
distanceTable[j, i] <- d
}
}
for ( i in 1:numberOfPoints ) { distanceTable[i, i] <- 1 } # fill the diagonal
return(distanceTable)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment