簡體   English   中英

如何在R中將圖形轉換為其等效的折線圖/邊線圖/互換圖?

[英]How to convert graph to its equivalent Line Graph/ Edge Graph/ Interchange graph in R?

看圖片 我有一個圖G及其鄰接矩陣。 我想將其轉換為線圖L(G),以使圖G的節點成為L(G)中的邊,反之亦然。
R中是否有任何程序包可以執行從節點到邊以及從邊到節點的互換?

我寫了一個小函數來計算折線圖的鄰接矩陣:

LineGraph <- function(A)      # A: adjacency matrix
{
  n <- nrow(A)
  m <- sum(A)/2               # m: number of edges

  X <- lower.tri(A)*A         # X: still the adjacency matrix,
  X[which(X!=0)] <- 1:m       #    but edges are numbered

  p <- which(X!=0)-1
  edgeNames <- apply(matrix(c((p %% n)+1,p %/% n+1),m),1,
                     function(v){paste(sort(v),collapse=".")})      # names of the edges

  X <- X + upper.tri(X)*t(X)

  A.line <- matrix(0,m,m)     # A.line will become the adjacency matrix of the line graph
  rownames(A.line) <- edgeNames
  colnames(A.line) <- edgeNames

  apply(X,1,
        function(x)
        {
          p <- which(x!=0)
          q <- outer(x[p],m*(x[p]-1),"+")
          A.line[c(q)] <<- 1        
        } )

  A.line[(1:m)+m*(0:(m-1))] <- 0

  return(A.line)
}

例:

> A <- matrix( c(0,1,1,1,0,
+                1,0,0,0,1,
+                1,0,0,1,0,
+                1,0,1,0,1,
+                0,1,0,1,0), 5, 5 )
> LineGraph(A)
    1.2 1.3 1.4 2.5 3.4 4.5
1.2   0   1   1   1   0   0
1.3   1   0   1   0   1   0
1.4   1   1   0   0   1   1
2.5   1   0   0   0   0   1
3.4   0   1   1   0   0   1
4.5   0   0   1   1   1   0
> 

igraph軟件包中的make_line_graph將圖形轉換為其相應的線形圖。

所以從上面使用鄰接矩陣

library(igraph)
m <- make_line_graph(graph_from_adjacency_matrix(A, mode="undirected"))

as_adjacency_matrix(m, sparse=FALSE)
#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]    0    1    1    1    0    0
#[2,]    1    0    1    0    1    0
#[3,]    1    1    0    0    1    1
#[4,]    1    0    0    0    0    1
#[5,]    0    1    1    0    0    1
#[6,]    0    0    1    1    1    0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM