r - 使用 tidygraph 将来自相同两个节点的两条边合并为一条
问题描述
我正在努力弄清楚如何将相同的 2 个节点之间的 2 条边折叠成 1 条,然后计算这些边的总和。
我相信有一种方法可以做到igraph
:
simplify(gcon, edge.attr.comb = list(weight = "sum", function(x)length(x)))
但如果可能的话,我想这样做,tidygraph
因为到目前为止我已经成功地实施了,tidygraph
而且我对tidyverse
工作方式更加熟悉。
我的数据如下所示:
from to Strength Dataframe Question Topic
1 0 32 4 weekly 1 Connection Frequency
2 0 19 5 weekly 1 Connection Frequency
3 0 8 3 weekly 1 Connection Frequency
4 0 6 5 weekly 1 Connection Frequency
5 0 2 4 weekly 1 Connection Frequency
6 0 14 5 weekly 1 Connection Frequency
'from' 和 'to' 包含相同的 id(例如 from-to;0-1 和 1-0)。我想浓缩,以便只存在 0-1 关系的一次迭代,并Strength
计算总和。
到目前为止,这是我的代码:
graph <- data %>%
filter(Dataframe == "weekly" & Question == 1) %>%
as_tbl_graph(directed = FALSE) %>%
activate(edges) %>% # first manipulate edges
filter(!edge_is_loop()) %>% # remove any loops
activate(nodes) %>% # now manipulate nodes
left_join(node.group, by = "name") %>%
mutate(
Popularity = centrality_degree(mode = 'in'),
Centre = node_is_center(),
Keyplayer = node_is_keyplayer(k = 5))
是否可以将两条对应的边合并为一条边?我搜索了论坛,但只遇到了相同节点在相同列中重复的引用(即跨多行的 0-1)。
解决方案
library(tidygraph) # v1.2.0
library(dplyr) # v0.8.5
library(purrr) # v0.3.4
dat <- data.frame(
from = c("a", "a", "b", "c"),
to = c("b", "b", "a", "b"),
n = 1:4
)
调用to_simple()
insideconvert()
折叠平行边。相应的边和权重.orig_data
作为小标题列表存储。然后,从 中提取折叠边的权重总和.orig_data
。
dat %>%
as_tbl_graph() %>%
convert(to_simple) %>%
activate(edges) %>%
mutate(n_sum = map_dbl(.orig_data, ~ sum(.x$n)))
# A tbl_graph: 3 nodes and 3 edges
#
# A directed simple graph with 1 component
#
# Edge Data: 3 x 5 (active)
from to .tidygraph_edge_index .orig_data n_sum
<int> <int> <list> <list> <dbl>
1 1 2 <int [2]> <tibble [2 x 3]> 3
2 2 1 <int [1]> <tibble [1 x 3]> 3
3 3 2 <int [1]> <tibble [1 x 3]> 4
#
# Node Data: 3 x 2
name .tidygraph_node_index
<chr> <int>
1 a 1
2 b 2
3 c 3
推荐阅读
- firebase - 检查在 Firestore 中在线的用户列表
- javascript - TypeError:未定义不是对象(评估'_reactNativeReanimated.EasingNode.linear')
- uber-api - 未找到服务器令牌
- javascript - 如何从 Typescript 单元测试中导入 Javascript
- javascript - $.trim().val 不是函数
- list - 如何在flutter / Dart的List中的where子句中运行IN条件?
- php - laravel 点雄辩的关系
- reactjs - 如何在 nextjs 中使用 react-router 创建单页应用程序?
- node.js - 如何防止 Node.js 子进程运行恶意代码?
- python - 登录适用于请求会话,但不适用于 request_html 会话