如何根据id和post创建网络图?
How to create a network diagram based on id and post?
我是 R 的新手,想创建一个网络图基本上可以做到这一点
postid
userid
3
2
3
4
3
5
1
1
1
2
2
1
2
4
--------
--------------
其中用户 1 和用户 2 相互连接,用户 2、4、5 也相互连接,并且用户 1 和用户 4 之间应该有一条边,因为他们都 post post 2
基本上我想要的只是生成一个网络图来显示在相同 post.
中交谈的用户
提前致谢
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()
您可以试试下面的代码
glst <- lapply(
with(df, split(as.character(userid), postid)),
function(x) graph_from_data_frame(t(combn(x, 2)), directed = FALSE)
)
或
lapply(
with(df, split(as.character(userid), postid)),
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
数据
> dput(df)
structure(list(postid = c(3L, 3L, 3L, 1L, 1L, 2L, 2L), userid = c(2L,
4L, 5L, 1L, 2L, 1L, 4L)), class = "data.frame", row.names = c(NA,
-7L))
我是 R 的新手,想创建一个网络图基本上可以做到这一点
postid | userid |
---|---|
3 | 2 |
3 | 4 |
3 | 5 |
1 | 1 |
1 | 2 |
2 | 1 |
2 | 4 |
-------- | -------------- |
其中用户 1 和用户 2 相互连接,用户 2、4、5 也相互连接,并且用户 1 和用户 4 之间应该有一条边,因为他们都 post post 2 基本上我想要的只是生成一个网络图来显示在相同 post.
中交谈的用户提前致谢
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()
您可以试试下面的代码
glst <- lapply(
with(df, split(as.character(userid), postid)),
function(x) graph_from_data_frame(t(combn(x, 2)), directed = FALSE)
)
或
lapply(
with(df, split(as.character(userid), postid)),
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
数据
> dput(df)
structure(list(postid = c(3L, 3L, 3L, 1L, 1L, 2L, 2L), userid = c(2L,
4L, 5L, 1L, 2L, 1L, 4L)), class = "data.frame", row.names = c(NA,
-7L))