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

偶尔善良 提交于 2021-01-28 06:08:35

问题


I have a data frame defined in a format of distance matrix:

> 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

I want to use it as distance matrix in hclust function. But when I try to convert it to a dist object, it changes:

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

You can see that DA is no longer part of the matrix. If I try to use df directly in hclust, it does not work:

> 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

How can I use df as distance matrix?


回答1:


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))

DATA

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"))



回答2:


Since you call your object df, I am a little worried that it is a data.frame and not a matrix. However, proceeding as if it is a matrix ...

## 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))

You just need to give it the zero diagonal as well.

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


来源:https://stackoverflow.com/questions/48324940/how-to-convert-data-frame-into-distance-matrix-for-hierarchical-clustering

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!