How to create weighted adjacency list/matrix from edge list?

前端 未结 4 810
一生所求
一生所求 2020-12-07 18:21

My problem is very simple: I need to create an adjacency list/matrix from a list of edges.

I have an edge list stored in a csv document with column1 = node1 and col

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 18:34

    This response uses base R only. The result is a standard matrix used to represent the adjacency matrix.

     el  <- cbind(a=1:5, b=5:1) #edgelist (a=origin, b=destination)
     mat <- matrix(0, 5, 5)
     mat[el] <- 1
     mat
     #    [,1] [,2] [,3] [,4] [,5]
     #[1,]    0    0    0    0    1
     #[2,]    0    0    0    1    0
     #[3,]    0    0    1    0    0
     #[4,]    0    1    0    0    0
     #[5,]    1    0    0    0    0
    

    Here mat is your adjacency matrix defined from edgelist el, which is a simple cbind of the vectors 1:5 and 5:1.

    If your edgelist includes weights, then you need a slightly different solution.

    el <- cbind(a=1:5, b=5:1, c=c(3,1,2,1,1)) # edgelist (a=origin, b=destination, c=weight)
    mat<-matrix(0, 5, 5)
    for(i in 1:NROW(el)) mat[ el[i,1], el[i,2] ] <- el[i,3]  # SEE UPDATE
    mat
    #     [,1] [,2] [,3] [,4] [,5]
    #[1,]    0    0    0    0    3
    #[2,]    0    0    0    1    0
    #[3,]    0    0    2    0    0
    #[4,]    0    1    0    0    0
    #[5,]    1    0    0    0    0
    

    UPDATE

    Some time later I realized that the for loop (3rd line) in the previous weighted edgelist example is unnecessary. You can replace it with the following vectorized operation:

    mat[el[,1:2]] <- el[,3]
    

提交回复
热议问题