如何将 Networkx Graph 转换为 igraph 对象(从 python 到 R)

How to convert a Networkx Graph into an igraph object (from python to R)

我有两个用 Networkx (Python 3.8) 从头开始​​制作的图形对象。为了帮助理解情况,这是一个摘要片段:

G = nx.Graph()
Z = nx.Graph()

#some work here to get data for nodes and edges

G.add_nodes_from([(data["id"], {"origin": data["origin"], "text": data["text"]})])

#some other work in order to hash data for improved nodes privacy

G.add_edge(h.hexdigest(), data["x"])
Z.add_edge(h.hexdigest(), data["x"], weight=polarity) #here polarity is a simple double value

现在,问题是我想导出这些对象以便使用 RStudio 和包 igraph 进行一些工作。到目前为止,我已经尝试了以下方法(没有任何运气):

  1. 导出到一个简单的邻接列表(但在 RStudio 中我得到一个错误,与它期望方矩阵的事实有关,我记不太清了)
  2. 导出到边缘列表(但我得到另一种错误,似乎我不能使用权重表示)
  3. 使用比较幼稚的方法,导出gml格式,然后安装python-igraph,用函数Read_Adjacency()读取gml文件,然后重新- 使用函数 Write_Adjacency() 导出(希望通过这个中间步骤它能以某种方式使 igraph 可以理解格式)
  4. 我尝试了提出的解决方案here,但这次也没有成功

我该怎么办?

这是我在 RStudio 中使用的代码:

ADJACENCY=read.csv("myadjlist.csv",header=FALSE,row.names=NULL,sep=";")
ADJACENCY=as.matrix(ADJACENCY)
#then we create the graph
G=graph_from_adjacency_matrix(ADJACENCY, mode="undirected")

错误:

Error in graph.adjacency.dense(adjmatrix, mode = mode, weighted = weighted, : At structure_generators.c:274 : Non-square matrix, Non-square matrix

这是我的邻接表:

link

igraph 现在支持从 networkx 对象直接转换。有关详细信息,请参阅 https://igraph.org/python/doc/igraph.Graph-class.html#from_networkx。如果您首先转换为 igraph 对象(在 Python 中),将其写入文件,然后使用 igraph(在 R 中)将其读回,这应该可以正常工作。