Reputation: 203
So currently I run this code to find the number of connected nodes with a value of 1 for the node attribute "a". How would I modify the following code so that it outputs proportion of connected nodes with attribute "a" value of 1 rather than the actual count?
library(igraph)
g <- make_empty_graph (2) %>%
set_vertex_attr("a", value = 1) %>%
set_vertex_attr("xyz", value = 1) %>%
add_vertices(2, color = 2, "a" = 1) %>%
add_vertices(2, color = 4, "a" = 1) %>%
add_edges(c(1,2, 2,1, 1,5, 5,1, 1,4 ,4,1))
V(g)$xyz <- sapply(V(g), function(x) { NeighborList = neighbors(g, x) ; length(NeighborList[NeighborList$a == 1]) } )
V(g)$xyz
Upvotes: 2
Views: 90
Reputation: 37641
You can just divide by the number of neighbors, except when there are none.
sapply(V(g), function(x) {
NeighborList = neighbors(g, x) ;
ifelse(length(NeighborList) > 0,
length(NeighborList[NeighborList$a == 1])/length(NeighborList),0) } )
[1] 1 1 0 1 1 0
Upvotes: 2