R 基于属性值计算节点度量
我经常想为图中的所有顶点计算一个度量,但仅基于它们与具有特定属性的顶点的连接,以图为例R 基于属性值计算节点度量,r,igraph,R,Igraph,我经常想为图中的所有顶点计算一个度量,但仅基于它们与具有特定属性的顶点的连接,以图为例 library(igraph) set.seed(2) g <- erdos.renyi.game(8, 0.5) V(g)$name <- paste0("ID", 1:8) V(g)$rand_attr <- rep(c("A", "B"), 4) plot(g, vertex.label = paste(V(g)$name, V(g)$rand_attr),
library(igraph)
set.seed(2)
g <- erdos.renyi.game(8, 0.5)
V(g)$name <- paste0("ID", 1:8)
V(g)$rand_attr <- rep(c("A", "B"), 4)
plot(g,
vertex.label = paste(V(g)$name, V(g)$rand_attr),
vertex.shape = "none")
库(igraph)
种子(2)
g我会尝试获取“B”顶点的名称。然后使用函数“相邻顶点”可以返回每个顶点的相邻顶点的名称。然后,计算每个连接的vertice中有多少个在我们的列表中
# your code, just to store the numbers
n <- vector("numeric",length(V(g)))
names(n) <- V(g)$name
for(i in V(g)$name){
subg <- induced_subgraph(g,
vids = c(which(V(g)$name == i), which(V(g)$rand_attr == "B")))
d <- degree(subg, v = which(V(subg)$name == i))
n[i] <- d
}
n
ID1 ID2 ID3 ID4 ID5 ID6 ID7 ID8
3 2 3 3 1 2 1 3
#names of B vertices
Bvert = vertex.attributes(g)$name[vertex.attributes(g)$rand_attr=="B"]
#number of B vertices connected per vertice
N = sapply(adjacent_vertices(g,1:8),function(i)sum(names(i) %in% Bvert))
N
ID1 ID2 ID3 ID4 ID5 ID6 ID7 ID8
3 2 3 3 1 2 1 3
table(N==n)
#您的代码,仅用于存储数字
n我会尝试获取“B”顶点的名称。然后使用函数“相邻顶点”可以返回每个顶点的相邻顶点的名称。然后,计算每个连接的vertice中有多少个在我们的列表中
# your code, just to store the numbers
n <- vector("numeric",length(V(g)))
names(n) <- V(g)$name
for(i in V(g)$name){
subg <- induced_subgraph(g,
vids = c(which(V(g)$name == i), which(V(g)$rand_attr == "B")))
d <- degree(subg, v = which(V(subg)$name == i))
n[i] <- d
}
n
ID1 ID2 ID3 ID4 ID5 ID6 ID7 ID8
3 2 3 3 1 2 1 3
#names of B vertices
Bvert = vertex.attributes(g)$name[vertex.attributes(g)$rand_attr=="B"]
#number of B vertices connected per vertice
N = sapply(adjacent_vertices(g,1:8),function(i)sum(names(i) %in% Bvert))
N
ID1 ID2 ID3 ID4 ID5 ID6 ID7 ID8
3 2 3 3 1 2 1 3
table(N==n)
#您的代码,仅用于存储数字
n除了显示答案外,您的解决方案看起来不错。除了显示答案外,您的解决方案看起来不错。