Created
June 12, 2023 19:11
-
-
Save rafapereirabr/19383acd8880c82bfe3da0aa6ddacb87 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(sfdep) | |
library(data.table) | |
library(cppRouting) | |
# get distance between neighbors | |
geo <- sf::st_geometry(guerry) | |
nb <- sfdep::st_contiguity(geo) | |
dists <- sfdep::st_nb_dists(geo, nb) | |
# fun to convert nb dist to a data.frame in long format | |
nb_list_to_df <- function(nb, dists) { | |
mtrx <- sfdep::wt_as_matrix(nb, dists) | |
matrix_length <- 1:length(mtrx[1,]) | |
# FULL MATRIX | |
mtrx_long <- cbind( | |
as.data.table( | |
data.table::CJ(matrix_length, matrix_length)), # df two columns | |
'dist' = as.vector(mtrx) # matrix values in a vector | |
) | |
# keep only dist between neighbors | |
mtrx_long <- subset(mtrx_long, dist >0) | |
setnames(mtrx_long, c('from', 'to', 'dist')) | |
return(mtrx_long) | |
} | |
# convert nb dist to a data.frame in long format | |
od_df <- nb_list_to_df(nb, dists) | |
# create graph | |
graph <- cppRouting::makegraph(od_df, directed = F) | |
# distances | |
dist_link <- cppRouting::get_distance_matrix(Graph=graph, | |
from = unique(od_df$from), | |
to = unique(od_df$from), | |
algorithm = 'mch') | |
head(dist_link) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment