所以目前我运行此代码来查找节点属性值为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
答案 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