r - Geosphere/dplyr: create matrix of distance between coordinates -
i want create "matrix" of distance between multiple coordinates each other. preferably using dplyr/geosphere. saw geosphere package offers this. managed create distance between 2 vectors have difficulties creating full matrix.
this sample table multiple coordinates.
df <- data.frame(latitude = c(49.48609,-8.14671,11.28625), longitude = c(8.463678,143.05793,-11.18285)) latitude longitude 1 49.48609 8.463678 2 -8.14671 143.057930 3 11.28625 -11.182850
and output looking for:
latitude longitude distance-latlon1 distance-latlon2 distance-latlon3 1 49.48609 8.463678 na *latlon2><latlon1 *latlon3><latlon1 2 -8.14671 143.057930 *latlon1><latlon2 na *latlon3><latlon2 3 11.28625 -11.182850 *latlon1><latlon3 *latlon2><latlon3 na
i tried out using geosphere found way calculate distance between 2 columns (which in snippet results in 0).
library(geosphere) df$distance <- distvincentyellipsoid(df[,c('longitude','latitude')], df[,c('longitude','latitude')])
you need distm
function of geosphere
-package. with:
# create distance matrix m <- distm(df[2:1], df[2:1], fun = distvincentyellipsoid) # replace diagonal na diag(m) <- na # make column names distance matrix colnames(m) <- paste0('r',1:nrow(df)) # bind distance matrix dataframe cbind.data.frame(df, m)
you get:
latitude longitude r1 r2 r3 1 49.48609 8.463678 na 13792423 4606658 2 -8.14671 143.057930 13792423 na 17189185 3 11.28625 -11.182850 4606658 17189185 na
Comments
Post a Comment