Zlo
Zlo

Reputation: 1170

Counting edges in a graph by the attribute of nodes they connect

Sorry for the vague question, I'm having difficulties in specifying exactly what I need. I hope the example will make it clearer.

I have a network with various node attributes (like country affiliation, etc.). I am interested in how many of the nodes from a country are connected to the same or a different country.

So, in the example network:

require(igraph)

zach <- graph("Zachary") # the Zachary carate club

V(zach)$new_var <- sample(c('tomato', 'gold', 'steelblue'), gorder(zach), replace = TRUE)

plot(zach, vertex.size=10, vertex.label=NA, vertex.color = V(zach)$new_var)

Example network with some attributes

I am interested here in, for example, how many blue nodes are connected to blue, to red, etc.

Upvotes: 0

Views: 856

Answers (1)

MrFlick
MrFlick

Reputation: 206576

Here's one possible way

ends <- as_edgelist(zach)
e1 <- V(zach)[ends[,1]]$new_var
e2 <- V(zach)[ends[,2]]$new_var

Then you can do (with set.seed(15))

table(e1, e2)
#            e2
# e1          gold steelblue tomato
#   gold         3         9     13
#   steelblue    5         4     12
#   tomato       7        10     15

Or if you want to count gold-tomato the same as tomato-gold, you can do

endcolors <- t(apply(cbind(e1, e2), 1, sort))    
table(endcolors[,1], endcolors[,2])
#             gold steelblue tomato
#   gold         3        14     20
#   steelblue    0         4     22
#   tomato       0         0     15

Upvotes: 3

Related Questions