r - 将整洁的数据框转换为邻接矩阵
问题描述
我有一个包含论文 ID 和作者姓名的数据框,如下所示:
library(tidyverse)
df <- tribble(
~id, ~name,
1, "a",
1, "b",
2, "b",
2, "c",
3, "b",
3, "c"
)
解释是作者 a 和 b 一起写论文 1,而作者 b 和 c 一起写论文 2 和 3。
我想用例如这样来绘制这个ggraph
:
a - b = c
也就是说,我希望将作者作为节点,将共同撰写的论文数量作为边权重。
解决方案
您可以使用 base 定义邻接矩阵R
。尝试这个:
# create a 2-mode sociomatrix
mat <- t(table(df))
# create adjacency matrix as product of the 2-mode sociomatrix
adj.mat <- mat %*% t(mat)
# if you want the diagonal to be 0 use : diag(adj.mat) <- 0. This can also be done directly
# with igraph
# define your network
library(igraph)
net <- graph_from_adjacency_matrix(adj.mat, mode = "undirected", weighted = TRUE,
diag = FALSE)
V(net)$name # vertices (nodes) name
E(net) # edges
E(net)$weight # edges weight
# example of plot
library(ggraph)
ggraph(net, layout = "igraph", algorithm = "kk") +
geom_edge_link(aes(width = weight)) +
geom_node_point(size = 8, colour = "steelblue") +
geom_node_text(aes(label = name)) +
ggforce::theme_no_axes()
# output
推荐阅读
- reactjs - 由于时间戳,当我在 firebase 上添加数据时,null 不是对象
- java - 如何使用协议缓冲区 java 流式传输大对象?
- vue.js - 在Vue循环中动态改变元素的颜色
- python - 如何在字典中获取最大值的键,如果有重复,也返回最高数字键
- laravel - Laravel 多数据查询
- java - 使用递归和回溯对给定字符串进行排列
- c++ - 如何声明一个接受层引用/指针的属性?
- 2sxc - 我无法编辑内容类型字段,错误已添加具有相同键的项目
- matplotlib - 将带有 LaTeX 字体的 Matplotlib 图保存为 eps
- jmeter - 如何在 JMeter 中并行执行多组并行请求?