将整洁的数据帧转换为邻接矩阵

时间:2018-08-29 14:12:40

标签: r ggraph

我有一个纸质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

就是说,我想让作者作为节点,并让论文数量作为边缘权重。

1 个答案:

答案 0 :(得分:3)

您可以使用基数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

enter image description here