我不知道如何表达这个问题,这使得很难找到解决方案。
我有一张用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
我的图形通过图形连接用户。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