Reputation: 1935
For example, how would I calculate, for each vertex, the percentage of ties directed outward toward males?
g <- erdos.renyi.game(20, .3, type=c("gnp"), directed = TRUE)
V(g)$male <- rbinom(20,1,.5)
V(g)$male[10] <- NA
Upvotes: 3
Views: 692
Reputation: 48101
A possible (not necessary optimal) solution is as follows (this is one single line, I just break it down for sake of readability):
unlist(lapply(get.adjlist(g, mode="out"),
function (neis) {
sum(V(g)[neis]$male, na.rm=T)
}
)) / degree(g, mode="out")
Now let's break it up into smaller pieces. First, we get the adjacency list of the graph using get.adjlist(g, mode="out")
. This gives you a list of vectors, each vector containing the out-neighbors of a vertex. Then we apply a function to each vector in this list using lapply
. The function being applied is as follows:
function (neis) {
sum(V(g)[neis]$male, na.rm=T)
}
The function simply takes the neighbors of a node in neis
and uses that to select a subset of vertices from the entire vertex set V(g)
. Then the male
attribute is retrieved for this vertex subset and the values are summed, removing NA
values on the fly. Essentially, this function gives you the number of males in neis
.
Now, returning to our original expression, we have applied this function to the adjacency list of the graph using lapply
, obtaining a list of numbers, each number containing the number of male neighbors of a given vertex. We convert this list into a single R vector using unlist
and divide it elementwise by the out-degrees of the vertices to obtain the ratios.
Upvotes: 3