How to combine a large list of igraphs into one igraph - R

Viewed 601

I have a large graph which I need to filter. After filtering (sub-graphing) I end up with a list of subgraphs. I need to combine all these subgraphs into one graph again. I don't know how to combine the large list (nearly a million subgraphs)

> require(igraph)
> graph <- make_ring(7)  #this is my original graph
> V(graph)$name <- c("A", "B", "C", "D", "E", "F", "G")  #name of vertices
> V(graph)$att1 <- c(1,2,NA,1,2,3,NA)  #some attribute
> selected_vertices <- V(graph)$name[which(V(graph)$att1 == 1)] #let's say i need to subgraph the graph to include only vertices with att1 == 1 (and their first order neighbours)
> subgraph_list <- make_ego_graph(graph, order=1, selected_vertices)  #this creates a list of igraphs but I need one graph containing all the graphs

This fails:

> subgraph <- induced_subgraph(graph, unlist(subgraph_list ))
Error in as.igraph.vs(graph, vids) : 
  (list) object cannot be coerced to type 'double'

I've tried other means to ego subgraph the graph but since it's a fairly large graph it takes a very long time and the one function that's worked well and relatively fast is make_ego_graph, which creates a list.

2 Answers

I assume you want the union of these graphs:

do.call(union, subgraph_list)

OK, i found a solution that works for me (quite fast and doesn't crash my computer).

> #first convert the list of igrpahs to list of data.frames
> subgraph_list_df <- lapply(subgraph_list, as_data_frame)
> # then combine all the data.frames in the list into one data.frame
> subgraph_df <- do.call(rbind, subgraph_list_df)
> #then make a graph out of the one combined data.frame
> subgraph <- graph_from_data_frame(subgraph_df , directed = FALSE)

for my purposes I know that the subgraphs are isolated (there are no shared edges between them). But if they are connected, should just do a unique(subgraph_df) to get rid of duplicate edges before converting to graph.

Related