This is my dataset
df<-tribble(
~"shop.x",~"shop.y", ~"cust.x", ~"cust.y",
78.100378, 9.944226, 78.096318, 9.954789,
78.101155, 9.932190, 78.089824, 9.929975,
78.141887, 9.928319, 78.110863, 9.952235,
78.100381, 9.944226, 78.104066, 9.97013,
78.097206, 9.948872, 78.11631, 9.947862
)
The df dataset has locations of shops and the customers.
I want to create shortest path route for each row (for every shop to customer location) using OSM map in R. Is it possible using sfnetworks?
The local road networks data is here
First, since this dataframe contains mainly coordinates in X and Y for shops and customers, I convert them into
sf
objects. Two objects for each set.The roads are
LINESTRINGS
which can be converted into asfnetwork
object. The network needs to be cleaned. More info on how to do network pre-processing here.To calculate the paths we can use an mapply function to the
st_network_paths()
function passing the from argument with the locations of the shops, and the to argument with the locations of the customers. Hence, the paths are calculated in order for each combination.The output is a list with five elements containing the node indices for each route, which correspond to the nodes in the original network.
If we want to get the path as a network itself, we can slice the original network as: