1
votes

Here's an example of a data frame you can convert to an edgelist and then into a graph. Notice that I have added 'km' as an attribute to the edgelist.

I'm not sure how to add 'km' as an edge attribute (so the distance between two nodes), but pretend that it's been done.

inst2 = c(2, 3, 4, 5, 6) 
motherinst2 = c(7, 8, 9, 10, 11) 
km = c(20, 30, 40, 25, 60)
df2 = data.frame(inst2, motherinst2)
edgelist = cbind(df2, km)
g = graph_from_data_frame(edgelist)

Now, how can I calculate the path lengths based on those km distances? I'm not interested in the number of edges or vertices in the path, just the sum of those km from a root to a leaf.

1

1 Answers

1
votes

The km edge attribute already exists. When using graph_from_data_frame() any information stored in the 3rd column and up are stored in the edge. You can pull information from an edge with the igraph::E() function.

E(g) #identifies all of the edges
E(g)$km #identifies all of the `km` attributes for each edge
E(g)$km[1] #identifies the `km` attribute for the first edge (connecting 2 -> 7)

For completeness, let's say you have a node path that is greater than 1.

#lets add two more edges to the network 
#and create a new and longer path between vertex named '2', and vertex named '7'
g <- g + 
  edge('2', '6', km = 10) +
  edge('6', '7', km = 120)


#find all paths between 2 and 7
#don't forget that the names of vertices are strings, not numbers
paths <- igraph::all_simple_paths(g, '2', '7')
paths

#find the edge id for each of the connecting edges
#the below function accepts a vector of pairwise vectors. 
#the ids are the edges between each pair of vectors
connecting_267 <- igraph::get.edge.ids(g, c('2','6' , '6','7'))
connecting_267

#get the km attribute for each of the edges
connecting_kms <- igraph::E(g)[connecting_267]$km
connecting_kms

sum(connecting_kms)

igraph is pretty powerful. It is definitely worth spending time and exploring its documentation. Also, Katherine Ognyanova created an AWESOME tutorial that is definitely worth everyone's time.