如何获得将顶点转换为顶点类别的新图?
How can I get a new graph translating the vertices to categories of vertices?
我不知道如何表述这个问题,这让我很难找到解决方案。
我在 igraph 中有一张人物及其关系图。我在数据框中也有这个人的位置。
> # graph.id is their id in the graph
> people
user.name graph.id location.cell
1 perez 654 54
2 garcia 123 54
3 fernandez 771 32
4 rodriguez 11 81
我的图表通过 graph.id:
连接用户
user 654 <-> user 11
user 123 <-> user 11
我想要一个新的区域图表,
cell 54 <- weight 2-> cell 81
(there are two connections between cells 54 and 81,
one between users 11 and 654,
and another between users 11 and 123,
so weight=2)
我如何在 R 中执行此操作(我使用的是 igraph)?我已经尝试了几次,遍历了图中的边缘,但我最终得到了太多的代码,这些代码的速度和维护速度都无法令人接受,而且它看起来不像是一个应该很难的问题(我想用我更习惯的语言做这种事情不会有任何问题)。
非常感谢。
您可以使用 igraph
中的 graph.data.frame
函数执行此操作,根据与当前图形中每条边关联的区域创建新图形。
首先,这是您描述的设置:
# 654 <-> 11; 123 <-> 11; 123 <-> 771
library(igraph)
g <- graph.data.frame(cbind(c(654, 123, 123), c(11, 11, 771)))
people <- data.frame(graph.id=c(654, 123, 771, 11), location.cell=c(54, 54, 32, 81))
现在您可以将每个顶点的位置存储在 g
中,并使用该顶点属性获取每个边端点的位置:
V(g)$location <- people$location.cell[match(V(g)$name, people$graph.id)]
g2 <- graph.data.frame(cbind(V(g)$location[get.edges(g, E(g))[,1]],
V(g)$location[get.edges(g, E(g))[,2]]), directed=F)
E(g2)
# str(g2)
# IGRAPH UN-- 3 3 --
# + attr: name (v/c)
# + edges (vertex names):
# [1] 54--81 54--81 54--32
要将多条边转换为具有更高权重的单条边,可以使用simplify
:
E(g2)$weight <- 1
g2 <- simplify(g2)
str(g2)
# IGRAPH UNW- 3 2 --
# + attr: name (v/c), weight (e/n)
# + edges (vertex names):
# [1] 54--81 54--32
E(g2)$weight
# [1] 2 1
我不知道如何表述这个问题,这让我很难找到解决方案。
我在 igraph 中有一张人物及其关系图。我在数据框中也有这个人的位置。
> # graph.id is their id in the graph
> people
user.name graph.id location.cell
1 perez 654 54
2 garcia 123 54
3 fernandez 771 32
4 rodriguez 11 81
我的图表通过 graph.id:
连接用户user 654 <-> user 11
user 123 <-> user 11
我想要一个新的区域图表,
cell 54 <- weight 2-> cell 81
(there are two connections between cells 54 and 81,
one between users 11 and 654,
and another between users 11 and 123,
so weight=2)
我如何在 R 中执行此操作(我使用的是 igraph)?我已经尝试了几次,遍历了图中的边缘,但我最终得到了太多的代码,这些代码的速度和维护速度都无法令人接受,而且它看起来不像是一个应该很难的问题(我想用我更习惯的语言做这种事情不会有任何问题)。
非常感谢。
您可以使用 igraph
中的 graph.data.frame
函数执行此操作,根据与当前图形中每条边关联的区域创建新图形。
首先,这是您描述的设置:
# 654 <-> 11; 123 <-> 11; 123 <-> 771
library(igraph)
g <- graph.data.frame(cbind(c(654, 123, 123), c(11, 11, 771)))
people <- data.frame(graph.id=c(654, 123, 771, 11), location.cell=c(54, 54, 32, 81))
现在您可以将每个顶点的位置存储在 g
中,并使用该顶点属性获取每个边端点的位置:
V(g)$location <- people$location.cell[match(V(g)$name, people$graph.id)]
g2 <- graph.data.frame(cbind(V(g)$location[get.edges(g, E(g))[,1]],
V(g)$location[get.edges(g, E(g))[,2]]), directed=F)
E(g2)
# str(g2)
# IGRAPH UN-- 3 3 --
# + attr: name (v/c)
# + edges (vertex names):
# [1] 54--81 54--81 54--32
要将多条边转换为具有更高权重的单条边,可以使用simplify
:
E(g2)$weight <- 1
g2 <- simplify(g2)
str(g2)
# IGRAPH UNW- 3 2 --
# + attr: name (v/c), weight (e/n)
# + edges (vertex names):
# [1] 54--81 54--32
E(g2)$weight
# [1] 2 1