对于每个顶点,我对基于条件的其相邻边的数量感兴趣。在以下示例中,条件具有不同的性别。
示例:
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
答案 0 :(得分:2)
这是将基数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
边的节点信息,一次是获取有关{{1 }}边缘,在同一行中。然后剩下的是通过汇总所有不同性别的邻居来汇总数据。