查找igraph中具有特定属性值的连接节点的比例

Finding the proportion of connected nodes in igraph that have a certain attribute value

所以目前我运行这段代码是为了找到节点属性"a"值为1的连接节点的数量。我将如何修改以下代码,使其输出属性 "a" 值为 1 而不是实际计数的连接节点的比例?

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

你可以只除以邻居的数量,除非有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