如何将data.frame转换为距离矩阵进行层次聚类?

How to convert data.frame into distance matrix for hierarchical clustering?

我有一个以距离矩阵格式定义的数据框:

> df
     DA   DB   DC  DD
DB 0.39   NA   NA  NA
DC 0.44 0.35   NA  NA
DD 0.30 0.48 0.32  NA
DE 0.50 0.80 0.91 0.7

我想用它作为 hclust 函数中的距离矩阵。但是当我尝试将它转换为 dist 对象时,它发生了变化:

> as.dist(df)
     DB   DC   DD
DC 0.44          
DD 0.30 0.48     
DE 0.50 0.80 0.91  

可以看到DA不再是矩阵的一部分。如果我尝试在 hclust 中直接使用 df,它不起作用:

> hclust(d = df)
Error in if (is.na(n) || n > 65536L) stop("size cannot be NA nor exceed 65536") : 
  missing value where TRUE/FALSE needed

如何使用 df 作为距离矩阵?

既然你称你的对象为 df,我有点担心它是 data.frame 而不是矩阵。但是,就好像它是一个矩阵一样......

## creating your data
df = as.matrix(read.table(text="DA   DB   DC  DD
0.39   NA   NA  NA
0.44 0.35   NA  NA
0.30 0.48 0.32  NA
0.50 0.80 0.91 0.7",
header=TRUE))

你只需要给它零对角线。

DM = matrix(0, nrow=5, ncol=5)
DM[lower.tri(DM)] = df[lower.tri(df, diag=TRUE)]
as.dist(DM)
     1    2    3    4
2 0.39               
3 0.44 0.35          
4 0.30 0.48 0.32     
5 0.50 0.80 0.91 0.70
temp = as.vector(na.omit(unlist(df1)))
NM = unique(c(colnames(df1), row.names(df1)))
mydist = structure(temp, Size = length(NM), Labels = NM,
                   Diag = FALSE, Upper = FALSE, method = "euclidean", #Optional
                   class = "dist")
mydist
#     DA   DB   DC   DD
#DB 0.39               
#DC 0.44 0.35          
#DD 0.30 0.48 0.32     
#DE 0.50 0.80 0.91 0.70

plot(hclust(mydist))

数据

df1 = structure(list(DA = c(0.39, 0.44, 0.3, 0.5), DB = c(NA, 0.35, 
0.48, 0.8), DC = c(NA, NA, 0.32, 0.91), DD = c(NA, NA, NA, 0.7
)), .Names = c("DA", "DB", "DC", "DD"), class = "data.frame", row.names = c("DB", 
"DC", "DD", "DE"))