如何在R中将一个图的边添加到另一图两个图的顶点相同?

问题描述

我正在努力了解如何将两个图与igraph合并在一起。

似乎可以将一个图形的顶点添加到另一个图形(由于add_vertices()函数),但是不可能将一个图形的边缘添加到另一个图形(尽管add_edges()函数

这是重现我的问题的代码,以及我得到的最终错误消息。

我首先创建两个图,每个图都有特定的顶点和边。

library(dplyr)
library(igraph)

d1 <- data.frame(from = c(1,1,2,3,4,6),to = c(5,6,5))
graph1 <- graph_from_data_frame(d1,directed = FALSE,vertices = NULL)
V(graph1)
E(graph1)

d2 <- data.frame(from = c(7,7,8,9,10,12),to = c(11,11,11))
graph2 <- graph_from_data_frame(d2,vertices = NULL)
V(graph2)
V(graph2)$Size <- c(56,58,75,81,65,45)
vertex.attributes(graph2)
E(graph2)

现在,我想获得一个包含前两个图的顶点和边的图。

对顶点工作正常:

graph3 <- add_vertices(graph1,length(V(graph2)),attr = vertex.attributes(graph2))
V(graph3)
vertex.attributes(graph3)

但是不管我尝试什么,我都会失败:

# 1st try
graph3 <- add_edges(graph1,E(graph2))

# 2nd try
E(graph3) <- add_edges(graph1,E(graph2))

# 3rd try (very cumbersome)
edges2 <- get.edgelist(graph2)
edges2 <- data.frame(source = edges2[,1],target = edges2[,2])

edges2for3 <- NULL
for (i in 1:length(edges2$source)) {
  edges2for3 <- append(edges2for3,as.numeric(edges2[i,]))
}

# edges2for3 is indeed a vector,which seems to me very close to the "vertex sequence" referred to in ?add_edges
edges2for3

add_edges(graph1,edges2for3)

我总是出现以下消息错误,我不理解:

Error in add_edges(graph1,E(graph2)) : 
  At type_indexededgelist.c:272 : cannot add edges,Invalid vertex id

为什么顶点ID无效?所有边都来自现有顶点...

欢迎任何帮助:-)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)