0

Pretend the dataframe below is an edgelist (relation between inst2 and motherinst2), and that km is an attribute I want to calculate as a path that's been assigned to the edges. I'm too new at coding to make a reproducible edge list.

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)

I know how to calculate the path length of vertices in a graph, but I have some attributes attached to the edges that I want to sum up as path lengths. They are simple attributes (distance in km, time in days, and speed as km/day).

This is how I was calculating the path of vertices (between roots and terminals/leaves):

roots = which(sapply(sapply(V(g),
                    function(x) neighbors(g, x, mode = 'in')), length) == 0)

#slight tweaking this piece of code will also calculate 'terminal' nodes (or leaves). (11):

terminals = which(sapply(sapply(V(g),
                    function(x) neighbors(g, x, mode = 'out')), length) == 0)


paths= lapply(roots, function(x) get.all.shortest.paths(g, from = x, to = terminals, mode = "out")$res)

named_paths= lapply(unlist(paths, recursive=FALSE), function(x) V(g)[x])

I just want to do essentially exactly as I did above, but summing up the distance, time, and rate (which I will compute the mean of) incurred between each of those paths. If it helps to know how the edges have been added as attributes, I've used cbind like so:

edgelist_df = cbind(edgelist_df, time, dist, speed)

and my graph object (g) is set up like this:

g <- graph_from_data_frame(edgelist_df, vertices = vattrib_df) 

vattrib_df is the attributes of the vertices, which is not of interest to us here.

TylerH
  • 20,799
  • 66
  • 75
  • 101
hmnoidk
  • 545
  • 6
  • 20
  • It would be easier to help you if you provided a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and the desired output so that possible solutions can be tested and verified. – MrFlick Dec 01 '17 at 21:30
  • Hm. The trouble is I am new to R and I'm not sure how to go about producing a sample edgelist. Mine is based on a dataframe of 266 observations. I'm just looking for the edge attributes along a path to be added together and return a sum. – hmnoidk Dec 01 '17 at 21:37
  • Maybe make a fake dataframe with 5 observations? The more simple the example, the better. – MrFlick Dec 01 '17 at 21:37
  • Just a dataframe? I genuinely can't figure out how to make an edgelist from a dataframe. Mine was set up for me from a pile of observations (266). – hmnoidk Dec 01 '17 at 22:25

0 Answers0