how to get adjacency matrix where values are the difference of nodes' attributes

StackOverflow https://stackoverflow.com/questions/22807542

  •  26-06-2023
  •  | 
  •  

Question

I have a network like this:

g1 <- erdos.renyi.game(10, 0.5)
V(g1)$time <- seq(1:10)

I know that igraph has a get.adjacency() to retrieve an adjacency matrix from a graph, where values in the matrix are either 0 (no link) or 1 (a link is present), or this value can be one out of every edge attributes available... I have to retrieve an adjacency matrix, but instead of the traditional 0/1 value or the edge attribute, I need to have the difference of $time between the sender and the receiver of each dyad:

adj <- get.adjacency(g1)
dims <- dim(adj)
for(i in 1:dims[1]){
    for(ii in 1:dims[2]){
    adj[i,ii] <- (V(g1)[V(g1)==i]$time - V(g1)[V(g1)==ii]$time)
    }
}

Is there a better way to accomplish this task?

Was it helpful?

Solution

It seems that what you are calculating in your loop is not the adjacency matrix, but the weighted distance of the shortest path. Anyway, the way to do either of these operations is to add a weight attribute to the edges, which represents the difference in times. This is then much easier to deal with than the attributes of the vertices. Here's an idea:

# your code
require(igraph)
g1 <- erdos.renyi.game(10, 0.5)
V(g1)$time <- 1:10
# adding a weight (difference in times)
E(g1)$weight <- apply(get.edgelist(g1), 1, function(i){
  abs(V(g1)$time[i[1]]-V(g1)$time[i[2]])
})
# calculate adjacency and/or shortest path. 
get.adjacency(g1, attr="weight")
shortest.paths(g1)

EDIT It seems that the difference you would like to calculate has nothing to do with the graph at all. You are probably just looking for outer:

outer(V(g1)$time, V(g1)$time, "-")

OTHER TIPS

It is actually easier to work with the edge list in this case:

require(igraph)
require(Matrix)
g1 <- erdos.renyi.game(10, 0.5)
V(g1)$time <- 1:10

el <- get.edgelist(g1)
sparseMatrix(el[,1], el[,2], x=abs(el[,1]-el[,2]),
             dims=rep(vcount(g1), 2), symmetric=TRUE)
# 10 x 10 sparse Matrix of class "dsCMatrix"

#  [1,] . 1 2 3 . 5 6 . . .
#  [2,] 1 . 1 . 3 4 5 6 7 8
#  [3,] 2 1 . 1 2 3 4 . 6 7
#  [4,] 3 . 1 . . 2 . . 5 .
#  [5,] . 3 2 . . . 2 3 4 .
#  [6,] 5 4 3 2 . . . . . 4
#  [7,] 6 5 4 . 2 . . 1 . .
#  [8,] . 6 . . 3 . 1 . 1 .
#  [9,] . 7 6 5 4 . . 1 . .
# [10,] . 8 7 . . 4 . . . .
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top