0

I'm working with data.frames with columns "from" and "to" and I would like to create network graphs from them.

For example:

mydata <- data.table(from=c("John", "John", "Jim", "Jesse"),
   to=c("John", "Jim", "Jack", NA))
mygraph <- graph_from_data_frame(d=mydata, directed=T)
plot(mygraph, vertex.label.dist=2) 

The presence of that NA produces an error.

If I just remove the NA row the lonely node is not plotted.

mydata <- data.table(from=c("John", "John", "Jim"),to=c("John", "Jim", "Jack"))
mygraph <- graph_from_data_frame(d=mydata, directed=T)
plot(mygraph, vertex.label.dist=2) 

enter image description here

I would like to get the same result than with:

g4 <- graph( c("John", "Jim", "Jim",  "Jack", "John", "John"), isolates=c("Jesse") )  
plot(g4,  vertex.label.dist=2) 

enter image description here

but working with two columns, from and to. How can I get the same result? When any of the "from" or "to" is NA then just plot the node without edges and without producing errors.

skan
  • 7,423
  • 14
  • 59
  • 96
  • 1
    https://stackoverflow.com/questions/42673949/creating-igraph-with-isolated-nodes/42675086 is one approach. Another `tab <- table(lapply(mydata, factor, levels=na.omit(unique(unlist(mydata))))) ; g <- graph_from_adjacency_matrix(tab)` – user20650 Jun 25 '17 at 23:14

1 Answers1

1

One way to get what you want is to leave out the single node, but then add it using add_vertices

library(igraph)
mydata <- data.frame(from=c("John", "John", "Jim"),
   to=c("John", "Jim", "Jack"))
mygraph <- graph_from_data_frame(d=mydata, directed=T)
mygraph = add_vertices(mygraph, 1, name="Jesse")
plot(mygraph, vertex.label.dist=2) 

enter image description here

G5W
  • 36,531
  • 10
  • 47
  • 80
  • OK, I'll try to automatize it for larger datasets and see if any problem arises – skan Jun 25 '17 at 13:49
  • I think we will have a problem when the same node appear twice, as a single node and as a connected node. – skan Jun 25 '17 at 13:51
  • 1
    I think that you are saying that you will get a list of "from" and "to nodes. Some will be NA. You can scan the lists for NA to add those nodes separately, but Some of those node may also be in the lists with connections. That is OK, remove the ones that match an NA, then use `setdiff` to remove any that are still on the two lists. – G5W Jun 25 '17 at 13:58