【问题标题】:How to convert data.frame into distance matrix for hierarchical clustering?如何将 data.frame 转换为距离矩阵进行层次聚类?
【发布时间】:2018-01-18 15:34:14
【问题描述】:

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

> 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 作为距离矩阵?

【问题讨论】:

    标签: r hclust


    【解决方案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))
    

    数据

    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】:

      既然你称你的对象为 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
      

      【讨论】:

        猜你喜欢
        • 2019-01-11
        • 2016-06-03
        • 2016-08-21
        • 2012-09-05
        • 2014-10-24
        • 1970-01-01
        • 2011-04-13
        • 2020-01-23
        • 1970-01-01
        相关资源
        最近更新 更多