Installing Necessary Packages
#install.packages("philentropy")
library(philentropy)
#install.packages("RColorBrewer")
library(RColorBrewer)
#install.packages("pheatmap")
library(pheatmap)
Establishing a Color Palette
colpal <- RColorBrewer::brewer.pal(9,"YlGnBu")
Bhattacharyya Distance:
calcbhatdist <- function(p,q) {
#p and q are the clusters
dist <- bhattacharyya(p,q,testNA = T,
unit = "log2", epsilon = 0.00001)
return(dist)
}
bhatdist <- function(mat) {
#create empty matrix: it'll be the result matrix
#it's dimensions are nrow(mat)xnrow(mat)
final_bhdist <- matrix(, nrow= ncol(mat), ncol=ncol(mat))
#need 2 loop
#1st: to select P
#2nd: make Bhat. calc with with q
for (i in 1:ncol(mat)) {
#select the cluster and calculate it's distance with the rest of the clusters
p <- c(mat[,i])
for (j in 1:ncol(mat)) {
#Perform the calculation
q <- c(mat[,j])
final_bhdist[i,j] <- calcbhatdist(p,q)
}
}
rownames(final_bhdist) <- colnames(mat)
colnames(final_bhdist) <- colnames(mat)
return(final_bhdist)
}
Plot the Heatmap:
#pheatmap(bhatdist(), display_numbers=T, color = colpal)
Example
GeneB <- c(0.1000,0.1001,1500)
GeneM<- c(0.2000,0.2500,500)
GeneG <- c(0.800,0.81,300)
GeneL<- c(0.5,0.510,2000)
matr <- matrix(c(GeneB,GeneM,GeneG,GeneL), nrow = 4, ncol=3, byrow=T)
rownames(matr) <- c("GeneB","GeneM","GeneG","GeneL")
colnames(matr) <- c("c1","c2","c3")
matr
## c1 c2 c3
## GeneB 0.1 0.1001 1500
## GeneM 0.2 0.2500 500
## GeneG 0.8 0.8100 300
## GeneL 0.5 0.5100 2000
bhatdist(matr)
## c1 c2 c3
## c1 -0.6780719 -0.7080693 -6.116077
## c2 -0.7080693 -0.7399345 -6.148930
## c3 -6.1160769 -6.1489302 -12.070121
#bhatdist(clu_me)
pheatmap(bhatdist(matr), display_numbers=F, color = colpal, show_rownames= T, cluster_col=F)
pheatmap(bhatdist(matr), display_numbers=T, color = colpal)