【问题标题】:Reconstruct symmetric matrix from values in long-form从长格式的值重建对称矩阵
【发布时间】:2015-09-14 17:17:40
【问题描述】:

我有一个看起来像这样的 tsv(长格式):

  one   two   value
  a     b     30
  a     c     40
  a     d     20
  b     c     10
  b     d     05
  c     d     30

我正在尝试将其放入 R(或 pandas)的数据框

    a  b  c  d 
a   00 30 40 20
b   30 00 10 05 
c   40 10 00 30
d   20 05 30 00

问题是,在我的 tsv 中,我只定义了 a, b 而没有定义 b,a。所以我的数据框中有很多 NA。

最终目标是获得一个用于聚类的距离矩阵。任何帮助将不胜感激。

【问题讨论】:

  • 如果您需要对分类变量进行聚类,您可能会发现 cluster 包中的 daisy 函数很有帮助,例如cutree(hclust(daisy(data)), k=2) 返回向量 1 1 1 2 2 1。
  • 请使用dput()发布可重现的代码示例。

标签: r matrix reshape


【解决方案1】:

您在数据框中读取的igraph 解决方案,其值假定为边权重。然后您可以将其转换为邻接矩阵

dat <- read.table(header=T, text=" one   two   value
  a     b     30
  a     c     40
  a     d     20
  b     c     10
  b     d     05
  c     d     30")

library(igraph)

# Make undirected so that graph matrix will be symmetric
g <- graph.data.frame(dat, directed=FALSE)

# add value as a weight attribute
get.adjacency(g, attr="value", sparse=FALSE)
#   a  b  c  d
#a  0 30 40 20
#b 30  0 10  5
#c 40 10  0 30
#d 20  5 30  0

【讨论】:

    【解决方案2】:

    另一种方法是reshape::cast

    df.long = data.frame(one=c('a','a','a','b','b','c'),
                         two=c('b','c','d','c','d','d'),
                         value=c(30,40,20,10,05,30) )
    
    # cast will recover the upper/lower-triangles...
    df <- as.matrix( cast(df.long, one ~ two, fill=0) )
    #    b  c  d
    # a 30 40 20
    # b  0 10  5
    # c  0  0 30
    

    所以我们用全索引构造矩阵,然后插入:

    df <- matrix(nrow=length(indices), ncol=length(indices),dimnames = list(indices,indices))    
    diag(df) <- 0
    # once we assure that the full upper-triangle is present and in sorted order (as Robert's answer does), then we
    df[upper.tri(df)] <- as.matrix( cast(df.long, one ~ two, fill=0) )
    df[lower.tri(df)] <- df[upper.tri(df)]
    

    更新:原始草图包括这些手动组件

    然后用同样的方法添加缺失的行 'd' 和列 'a',并通过添加转置 t(df) 来填充下三角:

    df <- cbind(a=rep(0,4), rbind(df, d=rep(0,3)))
    #   a  b  c  d
    # a 0 30 40 20
    # b 0  0 10  5
    # c 0  0  0 30
    # d 0  0  0  0
    
    df + t(df)
    #    a  b  c  d
    # a  0 30 40 20
    # b 30  0 10  5
    # c 40 10  0 30
    # d 20  5 30  0
    

    【讨论】:

    • 我知道,这只是一个草图,@Robert 的回答很好。从levels(unlist(df.long[,1:2]))获取完整的索引很容易
    • 我已经这样做了。填补空白并不难。我指的是reshape::cast。
    • 完成。在我开始我的之前,我知道你的更普遍。为了社区,我只是指出reshape::cast 的实用性。
    【解决方案3】:

    确保您的数据已排序 tsv=tsv[with(tsv,order(one,two)),],然后试试这个:

    n=4
    B <- matrix(rep(0,n*n), n)
    dimnames(B) <- list(letters[1:n],letters[1:n])
    B[lower.tri(B)] <- tsv$value
    B[upper.tri(B)]=tsv$value
    B 
    

    【讨论】:

      【解决方案4】:

      你可以试试

       un1 <- unique(unlist(df1[1:2]))
       df1[1:2] <- lapply(df1[1:2], factor, levels=un1)
       m1 <- xtabs(value~one+two, df1)
       m1+t(m1)
       #    two
       #one  a  b  c  d
       #a    0 30 40 20
       #b   30  0 10  5
       #c   40 10  0 30
       #d   20  5 30  0
      

      或者你使用row/col索引

        m1 <- matrix(0, nrow=length(un1), ncol=length(un1),
                                    dimnames=list(un1, un1))
        m1[cbind(match(df1$one, rownames(m1)), 
                     match(df1$two, colnames(m1)))] <- df1$value
        m1+t(m1)
        #   a  b  c  d
        #a  0 30 40 20
        #b 30  0 10  5
        #c 40 10  0 30
        #d 20  5 30  0
      

      【讨论】:

        【解决方案5】:

        这是一个基本的R 解决方案,适用于不想学习新功能的人。它创建了一个对称矩阵。

        df.long = data.frame(one=c('a','a','a','b','b','c'),
                             two=c('b','c','d','c','d','d'),
                             value=c(30,40,20,10,05,30) )
        
        v <- unique(c(df.long$one, df.long$two))
        mx <- sapply(v, function(x) {
            sapply(v, function(y) {
                df.long[df.long$one %in% c(x, y) & df.long$two %in% c(x, y), "value"]
            })
        })
        diag(mx) <- 0
        
          a  b  c  d 
        a 0  30 40 20
        b 30 0  10 5 
        c 40 10 0  30
        d 20 5  30 0 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-06-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多