I am trying to find an efficient (i.e. avoid using loops) way to apply a function that iteratively takes as arguments the current and previous (or next) elements of a list and returns a lists of the result (the length of which will necessarily be 1 element shorter). As a concrete example,
I have a list of vertices defining a path in some graph
vlist <- c(1,2,7,12,17)
which come from a lattice graph constructed using the igraph function "lattice"
G <- graph.lattice(c(5,7))
I want to apply the function "get.edge.ids" over vlist so that the list returned yields the ids of the edges connecting the consecutive elements in vlist. E.g. I want the ids of edges 1-->2, 2-->7, 7-->12, 12-->17
This is trivial using a for loop,
findEids <- function(G,vlist) {
outlist=c()
for (i in 1:(length(vlist)-1) {
outlist=append(outlist,get.edge.ids(G,c(vlist[i],vlist[i+1])))
}
return(outlist)
}
but I would like to use a vectorized approach like apply() or reduce() to see if I can get it to work more quickly since I will need to call functions like this repeatedly from a script (for example, to compute the total stretch for a spanning tree of G).