如何根据id和post创建网络图?

问题描述

我是 R 新手,想创建一个网络图基本上就是这样做的

postid 用户名
3 2
3 4
3 5
1 1
1 2
2 1
2 4
-------- --------------

用户 1 和用户 2 相互连接,用户 2、4、5 也相互连接,用户 1 和用户 4 之间应该有一个边缘,因为他们都在帖子 2 中发帖 基本上我想要的只是生成一个网络图来显示在同一帖子中发言的用户

提前致谢

解决方法

df <- read.table(text="postid   userid
3   2
3   4
3   5
1   1
1   2
2   1
2   4",header = TRUE)

library(tidyverse)
library(igraph)
df %>%
  left_join( df,by = "postid" ) %>%
  select(-postid) %>%
  graph_from_data_frame(directed = FALSE) %>%
  simplify( remove.multiple = TRUE,remove.loops = TRUE) %>%
  plot()

enter image description here

,

你可以试试下面的代码

glst <- lapply(
  with(df,split(as.character(userid),postid)),function(x) graph_from_data_frame(t(combn(x,2)),directed = FALSE)
)

lapply(
  with(df,function(x) simplify(graph_from_data_frame(expand.grid(x,x),directed = FALSE))
)

生成图形对象列表

$`1`
IGRAPH 125b424 UN-- 2 1 --
+ attr: name (v/c)
+ edge from 125b424 (vertex names):
[1] 1--2

$`2`
IGRAPH 125bde9 UN-- 2 1 --
+ attr: name (v/c)
+ edge from 125bde9 (vertex names):
[1] 1--4

$`3`
IGRAPH 125bde9 UN-- 3 3 --
+ attr: name (v/c)
+ edges from 125bde9 (vertex names):
[1] 2--4 2--5 4--5

如果要聚合所有子图,可以使用graph.union

> (g <- do.call(graph.union,glst))
IGRAPH 7c8e074 UN-- 4 5 --
+ attr: name (v/c)
+ edges from 7c8e074 (vertex names):
[1] 4--5 2--5 2--4 1--4 1--2

enter image description here

数据

> dput(df)
structure(list(postid = c(3L,3L,1L,2L,2L),userid = c(2L,4L,5L,4L)),class = "data.frame",row.names = c(NA,-7L))