我如何计算两棵树内(而不是两棵整棵树之间)的个体的行间距离?
我想计算两个树状图中每个人的位置相似/不相似,并使用R包dendextend和heatmaply在组合的热图和树状图的行颜色中显示结果。
答案 0 :(得分:1)
已被聚类的两个观测值之间的显着距离被定义为组间不相似性,在该处,两个观测值首先被组合为一个聚类。在here中找到一个可行的示例。有关深入的讨论,我建议使用此SO post。并且here可以看到R
的实现。
答案 1 :(得分:0)
感谢所有帮助,基于vilisSO提供的链接和Grant的回答,我编写了以下代码,根据完整数据和数据子样本计算两棵树的同色距离之间的相关性。对于树状图中的每个休假,将计算两棵树中的同位距矢量之间的相关性: enter image description here
## Compare cophenetic similarity between leaves in two trees build on full data and subsample of the data
# 1 ) Generate random data to build trees
set.seed(2015-04-26)
dat <- (matrix(rnorm(100), 10, 50)) # Dataframe with 50 columns
datSubSample <- dat[, sample(ncol(dat), 30)] #Dataframe with 30 columns sampled from the dataframe with 50
dat_dist1 <- dist(datSubSample)
dat_dist2 <- dist(dat)
hc1 <- hclust(dat_dist1)
hc2 <- hclust(ddat_dist2)
# 2) Build two dendrograms, one based on all data, second based a sample of the data (30 out of 50 columns)
dendrogram1 <- as.dendrogram(hc1)
dendrogram2 <- as.dendrogram(hc2)
# 3) For each leave in a tree get cophenetic distance matrix,
# each column represent distance of that leave to all others in the same tree
cophDistanceMatrix1 <- as.data.frame(as.matrix(cophenetic(dendrogram1)))
cophDistanceMatrix2 <- as.data.frame(as.matrix(cophenetic(dendrogram2)))
# 4) Calculate correlation between cophenetic distance of a leave to all other leaves, between two trees
corPerLeave <- NULL # Vector to store correlations for each leave in two trees
for (leave in colnames(cophDistanceMatrix1)){
cor <- cor(cophDistanceMatrix2[leave],cophDistanceMatrix1[leave])
corPerLeave <- c(corPerLeave, unname(cor))
}
# 5) Convert cophenetic correlation to color to show in side bar of a heatmap
corPerLeave <-corPerLeave/max(corPerLeave) #Scale 0 to 1 correlation
byPal <- colorRampPalette(c('yellow','blue')) #blue yellow color palette, low correlatio = yellow
colCopheneticCor <- byPal(20)[as.numeric(cut(corPerLeave, breaks =20))]
# 6) Plot heatmap with dendrogram with side bar that shows cophenetic correlation for each leave
row_dend <- dendrogram2[enter image description here][1]
x <- as.matrix(dat_dist)
heatmaply(x,colD = row_dend,row_side_colors=colCopheneticCor)