# Calculate shortest path distance on a network with R, sf and stplanr

I want to estimate a spatial logistic regression model for car crashes in Milan using R. I downloaded data from OSM for several highways segments in Milan using the R package `osmdata`. The response variable of my model is a binary variable which is equal to 1 if at least one car crash happened less than approximately 10m from a street segment, otherwise is 0. I'd like to add to the covariates of the model a new variable that expresses the shortest-path distance between the middle-point of each segment and the nearest roundabout/school/hospital. The shortest-path distance should be estimated on a street network.

This is a small example to show what I mean.

``````# packages
library(dplyr)
library(sf)
library(osmdata)
library(stplanr)
``````

Download highways data from OSM. This is just a small part of the complete dataset of all highways, which means that the resulting street network is not connected. I can also provide the code to create the complete dataset of all connected highways if it's important to answer my question.

``````# highways data
milan_highways <- opq("Milan, Italy") %>%
add_osm_feature(key = "highway", value = "primary") %>%
osmdata_sf() %>%
trim_osmdata(bb_poly = getbb("Milan, Italy", format_out = "sf_polygon")) %>%
magrittr::use_series(osm_lines) %>%
st_transform(crs = 32632) %>%
select(osm_id, name, highway)
``````

``````# roundabout data
osmdata_sf() %>%
osm_poly2line() %>%
magrittr::use_series(osm_lines) %>%
st_transform(crs = 32632)

st_cast("MULTIPOINT") %>%
mutate(at_least_five_points = purrr::map_int(geometry, length) >= 5L) %>%
filter(at_least_five_points) %>%
st_cast("POLYGON") %>%
st_centroid()
#> Warning in st_centroid.sf(.): st_centroid assumes attributes are constant
#> over geometries of x
``````

Now I use the function `SpatialLinesNetwork` of the `stplanr` package to estimate the street network.

``````# highways network
milan_highways_network <- SpatialLinesNetwork(milan_highways)
``````

Now I'm not sure on how to proceed. My idea is to use the function `find_network_nodes` to determine the closest node to each segment and each roundabout and the function `sum_network_links` to estimate the network shortest-path distance between every combination of nodes and take the minimum. The problem is that I'm not sure how to code this idea and if it's good or not.