Map from sfnetwoks package in R

Hello, I'm making a map using the sfnetworks package in software R. It's working properly. The code is doing the shortest distance between two points, as you can see in the code below. For this, the Points and Roads shapefile is used. My question is if I don't want to use my points file (that is in shapefile) but a data frame. I want, for example, to see the distance between property 1 and 7 from my df database, but without directly using the coordinates in from and to as I did below. Is it possible to do it in some other way? For example use for from = c(df[1,c("Longitude")], df[1,c("Latitude")]) and to = c(df[7,c("Longitude")], df[7,c("Latitude")]) ?

To download the Points and Roads shapefile file: https://github.com/JovaniSouza/JovaniSouza5/raw/master/Example.zip

For those who do not have the sfnetworks package: GitHub - luukvdmeer/sfnetworks: Tidy Geospatial Networks in R

library(sf)
library(sfnetworks)
library(tidygraph)
library(tmap)

  df<-structure(list(Property = c(1,2,3,4,5,6,7), 
                     Latitude = c(-24.779225, -24.789635, -24.763461, -24.794394, -24.747102,-24.781307,-24.761081), 
                     Longitude = c(-49.934816, -49.922324, -49.911616, -49.906262, -49.890796,-49.8875254,-49.8875254), 
                     Waste = c(526, 350, 526, 469, 285, 433, 456)), class = "data.frame", row.names = c(NA, -7L))

roads = st_read("C:/Users/Jovani/Desktop/Example/Roads/Roads.shp",quiet=TRUE)
points = st_read("C:/Users/Jovani/Desktop/Example/Points/Points.shp",quiet=TRUE)
roads_trf = st_transform(roads, st_crs(points)) %>% 
  st_cast("LINESTRING")

# build sfnetwork
net = as_sfnetwork(roads_trf, directed = FALSE) %>%
  activate("edges") %>%
  dplyr::mutate(weight = edge_length())

# routing
from = c(-49.87, -24.80)
to = c(-49.92, -24.78)
p1 = sf::st_as_sf(data.frame(x = from[1], y = from[2]), coords = c("x", "y"), crs = sf::st_crs(net))
p2 = sf::st_as_sf(data.frame(x = to[1], y = to[2]), coords = c("x", "y"), crs = sf::st_crs(net))
r = tidygraph::convert(net, to_spatial_shortest_paths, p1, p2)

# Extract the bbox for r 
bbox_r = st_as_sfc(r %>% activate(edges) %>% st_bbox())

# filter the net
small_net = st_filter(net, bbox_r)

# plot
tm_shape(small_net %>% activate(edges) %>% st_as_sf()) +
  tm_lines() + 
  tm_shape(rbind(p1, p2)) + 
  tm_dots(col = "red", size = 0.5) + 
  tm_shape(r %>% activate(edges) %>% st_as_sf()) + 
  tm_lines(col = "red", lwd = 3)

Map created by code above

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.