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

Convert tidy dataframe to adjacency matrix

我有一个论文 ID 和作者姓名的数据框,如下所示:

library(tidyverse)

df <- tribble(
  ~id, ~name,
  1, "a", 
  1, "b", 
  2, "b", 
  2, "c",
  3, "b",
  3, "c"
)

解释是作者a和b一起写了paper 1,而作者b和c一起写了paper 2和3

我想用例如ggraph 像这样:

a - b = c

也就是说,我想将作者作为节点,将合着的论文数量作为边权重。

您可以定义基数为 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