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

时间:2017-11-10 01:07:07

标签: r igraph

所以目前我运行此代码来查找节点属性值为1的连接节点数" a"。我如何修改以下代码,以便输出连接节点的比例与属性" 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

1 个答案:

答案 0 :(得分:2)

你可以除以邻居的数量,除非没有邻居。

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