Data
I have 2 data sets:
* segments dataset represents the road segments (lhrs.)
* hwys dataset represents the highways that contain individual lhrs.
> segments
# A tibble: 1 x 5
lhrs mto_collision_ref_number latitude longitude highway_number
<dbl> <dbl> <dbl> <dbl> <dbl>
1 10004 1549630 42.9 -78.9 1
> hwys
# A tibble: 5 x 3
STREET longitude latitude
<fct> <dbl> <dbl>
1 HIGHWAY 3 -80.0 42.9
2 ADELAIDE AVE E -78.9 43.9
3 HOWARD AVE -83.0 42.2
4 HIGHWAY 12 -79.7 44.7
5 CORONATION BLVD -80.3 43.4
The problem
As you can see, the STREET column is missing in the segments dataset. I want to create this column in the segments dataset by finding the distance between a given lhrs and a STREET based on the longitude and latitude values. This means that I need to compare one set of long, lat of lhrs to all 5 STREET locations and find the one that has the minimum distance. I think this can be done using purrr package.
My code
I can find the distances between each lhrs and STREET using the geosphere::distVincentyEllipsoid() distance as follows:
library(tidyverse)
segments_nested <- segments %>% group_by(mto_collision_ref_number) %>% nest()
segments_nested %>%
mutate(diztances = purrr::map(
data, ~ distVincentyEllipsoid(hwys %>% select(longitude, latitude),
c(.$longitude, .$latitude)))) %>%
unnest(.preserve = data)
# A tibble: 5 x 3
mto_collision_ref_number data diztances
<dbl> <list> <dbl>
1 1549630 <tibble [1 x 4]> 85316.
2 1549630 <tibble [1 x 4]> 110700.
3 1549630 <tibble [1 x 4]> 342921.
4 1549630 <tibble [1 x 4]> 213961.
5 1549630 <tibble [1 x 4]> 125547.
HOWEVER, I can't still figure out how to connect these distances with the STREET. Please guide me how I can use purrr::map to calculate the distances AS WELL AS the corresponding STREET. Once I have that, I can just group_by(mto_collision_ref_number) and get the summarize(min(diztances)).
dputto post your dataunnest()called with no arguments gets a data frame of the references, distances, and then the columns that make up the contents ofdata. Final dimensions are 5x6STREET.