Search code examples
rgraphnodesadjacency-matrixedges

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


Look at the imageI have a graph G and its adjacency matrix. I want to convert it into Line Graph L(G) such that nodes of graph G becomes edges in L(G) and vice-versa.
Is there any package in R which can perform such interchange from nodes to edges and edges to nodes?


Solution

  • I wrote a little function that computes the adjacency matrix of the line graph:

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

    Example:

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