ira
ira

Reputation: 2644

how to scale edge related number by a vertex related number in igraph?

I have a graph data frame as created by the function graph.data.frame from the igraph package. My edges contain information about the "strength of the relation" and my nodes contain information about the "strength of the node".

What I would like to do is to scale the strength of the relationship by the strength of the individual nodes they relate to.

For my reproducible example, i am going to use the setup from the igraph documentation (type ?graph.data.frame and scroll down). I plot a relationship between individual actors and use advice column as an indicator of the strength of the relationship. For some wild reason, i would like to scale the values of the quality of the advice by the average of the age of the recipient and provider of the advice.

I am able to do the scaling before I create the graph data frame(i have my edges and nodes as two separate data.tables so all i would have to do is bunch of joining + some sorcery as my real case is a bit more complicated than the example below), but I am curious how to do it after the igraph data frame is created.

actors <- data.frame(name=c("Alice", "Bob", "Cecil", "David",
                            "Esmeralda"),
                     age=c(48,33,45,34,21),
                     gender=c("F","M","F","M","F"))
relations <- data.frame(from=c("Bob", "Cecil", "Cecil", "David",
                               "David", "Esmeralda"),
                        to=c("Alice", "Bob", "Alice", "Alice", "Bob", "Alice"),
                        same.dept=c(FALSE,FALSE,TRUE,FALSE,FALSE,TRUE),
                        friendship=c(4,5,5,2,1,1), advice=c(4,5,5,4,2,3))


# create graph data frame
# note that i treat the network as undirected here
g <- graph.data.frame(relations, directed=FALSE, vertices=actors)
print(g, e=TRUE, v=TRUE)

# plot a graph of the network
plot(g,
     edge.label = edge_attr(g, 'advice'),
     vertex.label = paste0(vertex_attr(g, 'name'),
                           '\nage = ',
                            vertex_attr(g, 'age')))

Upvotes: 0

Views: 236

Answers (1)

G5W
G5W

Reputation: 37641

The key to what you are trying to compute is the ends function which gives the two ends of an edge.

E(g)$ScaledAdvice = 0
for(e in E(g)) {
    E(g)$ScaledAdvice[e] =  E(g)$advice[e] / mean(V(g)[ends(g, e)]$age)
}

Upvotes: 1

Related Questions