对于每个顶点,我感兴趣的是基于条件的其相邻边的数量。在以下示例中,条件是具有不同的性别。
示例:
library(igraph)
library(ggraph)
library(tidyverse)
nodes <- tibble(id = 1:4,
gender = c("M", "F", "F", "M"),
names = c("Bob", "Allie", "Mary", "Johnathon"))
edges <- tibble(from = c(1, 3, 2, 4, 1, 2, 1, 4),
to = c(2, 2, 4, 1, 3, 1, 4, 3))
network <- graph_from_data_frame(d = edges, vertices = nodes, directed = TRUE)
ggraph(network) +
geom_edge_link(arrow = arrow(length = unit(4,
'mm')),
start_cap = circle(4, 'mm'),
end_cap = circle(4, 'mm')) +
geom_node_text(aes(label = names)) +
theme_graph()
期望的结果:
id name adjacent_edges
1 Bob 1
2 Allie 1
3 Mary 2
4 Johnathon 1
最佳答案
这是一种将基础 R 与 igraph 相结合的方法:
nodes %>%
mutate(adjacent_edges = colSums(as.matrix(outer(gender, gender, `!=`) * as_adj(network)) != 0))
# A tibble: 4 x 4
# id gender names adjacent_edges
# <int> <chr> <chr> <dbl>
# 1 1 M Bob 1
# 2 2 F Allie 1
# 3 3 F Mary 2
# 4 4 M Johnathon 1
这里
outer(gender, gender, `!=`)
当性别不同时,构建一个具有TRUE
条目的矩阵,而as_adj(network))
是通常的图邻接矩阵。那么他们的乘积将在我们想要的时候准确地具有非零条目 - 在具有不同性别的连接节点的情况下。对这些情况进行总结可以得到所需的结果。
这是另一个,更长但也更透明:
edges %>% full_join(nodes, by = c("from" = "id")) %>%
full_join(nodes, by = c("to" = "id"), suff = c(".from", ".to")) %>%
group_by(to, names.to) %>% summarise(adjacent_edges = sum(gender.to != gender.from)) %>%
rename(id = to, name = names.to)
# A tibble: 4 x 3
# Groups: id [4]
# id name adjacent_edges
# <dbl> <chr> <int>
# 1 1 Bob 1
# 2 2 Allie 1
# 3 3 Mary 2
# 4 4 Johnathon 1
在这种情况下,我们从边列表开始,两次添加节点列表:一次是为了获得有关 from
边的节点信息,一次是为了获得有关 from
边的节点信息到
边缘,在同一行中。然后剩下的就是通过对所有不同性别的邻居求和来总结数据。
关于r - 基于属性的 igraph 相邻边,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53574078/