Search code examples
rpython-3.xgraphnetworkxigraph

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


I have two graph objects made from scratch with Networkx (Python 3.8). To help understanding the situation this is a summary snippet:

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

Now, the problem is that I want to export those objects in order to do some work with RStudio and the package igraph. Until now I've tried the following things (without any luck):

  1. Export to a straightforward adjacency list (but in RStudio I get an error, something related to the fact that it expects a square matrix, I don't remember well)
  2. Export to an edge list (but I get another type of error, it seems that i cannot use the weight representation)
  3. Use a naive approach, export in gml format, then install python-igraph, read the gml file with the function Read_Adjacency() and then re-export with the function Write_Adjacency() (hoping that with this intermediate step it somehow make the format understandable by igraph)
  4. I tried the solutions proposed here but also this time without success

How can I do ?

This is the code I use in 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")

And the error:

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

This is my adjacency list:

link


Solution

  • igraph nowadays support direct conversion from and to networkx objects. See https://igraph.org/python/doc/api/igraph.Graph.html#from_networkx for more details. If you first convert to an igraph object (in Python), write it to a file, and then read it back in using igraph (in R), this should work correctly.