【问题标题】:How to create an edge list from a matrix in R?如何从R中的矩阵创建边缘列表?
【发布时间】:2012-10-23 15:10:42
【问题描述】:

关系表示为矩阵x,如下所示:

      A    B    C     D
A     0    2    1     1
B     2    0    1     0
C     1    1    0     1
D     1    0    1     0

条目是指它们拥有的连接数。

谁能告诉我如何将它写成边缘列表?

我更愿意把它写成一个边缘列表:

A B
A B
A C
A D
B C

但是这个边列表可以让我创建一个网络图吗?

【问题讨论】:

    标签: r list matrix social-networking edge-list


    【解决方案1】:

    使用igraph 包:

    x <- matrix(c(0,2,1,1,2,0,1,0,1,1,0,1,1,0,1,0), 4, 4)
    rownames(x) <- colnames(x) <- LETTERS[1:4]
    
    library(igraph)
    g <- graph.adjacency(x)
    get.edgelist(g)
    
    #      [,1] [,2]
    #  [1,] "A"  "B" 
    #  [2,] "A"  "B" 
    #  [3,] "A"  "C" 
    #  [4,] "A"  "D" 
    #  [5,] "B"  "A" 
    #  [6,] "B"  "A" 
    #  [7,] "B"  "C" 
    #  [8,] "C"  "A" 
    #  [9,] "C"  "B" 
    # [10,] "C"  "D" 
    # [11,] "D"  "A" 
    # [12,] "D"  "C"
    

    我还建议您花一些时间阅读http://igraph.sourceforge.net/index.html 上的igraph 文档,因为您最近提出的许多问题都是简单的案例用法。

    (作为奖励,plot(g) 将回答您的其他问题How to plot relationships in R?

    【讨论】:

    • 感谢您的帮助!我现在正在阅读您推荐的文件。
    【解决方案2】:

    试试这个

    M <- matrix( c(0,2,1,1,2,0,1,0,1,1,0,1,1,0,1,0), 4, 4, dimnames=list(c("A","B","C","D"), c("A","B","C","D")))
    
    eList <- NULL
    for ( i in 1:nrow(M) ){
      for ( j in 1:ncol(M)) {
        eList <- c(eList, rep(paste(dimnames(M)[[1]][i], dimnames(M)[[2]][j] ), M[i,j]))
      }
    }
    

    输出

    > eList
     [1] "A B" "A B" "A C" "A D" "B A" "B A" "B C" "C A" "C B" "C D" "D A" "D C"
    

    【讨论】:

    • 您的解决方案反之亦然是什么?我的意思是,如果我们有一个边列表并想按照您的方式将其转换为邻接矩阵?
    【解决方案3】:

    reshape2中使用melt,然后删除权重==0。如果不需要打印重量。只是删除它。

    x
        sample1 sample2 sample3 sample4
    feature1       0       2       1       1
    feature2       2       0       1       0
    feature3       1       1       0       1
    feature4       1       0       1       0
    
    melt(x)
       Var1    Var2 value
    1  feature1 sample1     0
    2  feature2 sample1     2
    3  feature3 sample1     1
    4  feature4 sample1     1
    5  feature1 sample2     2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-06
      • 2018-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多