Home > database >  Calculating minimum and maximum distance between points in meters, R
Calculating minimum and maximum distance between points in meters, R

Time:10-22

I have a data frame with two columns including coordinates in meters (about 45.000 locations). What I want to do is to calculate the minimum and maximum distances between the locations. I have tried to calculate the minimum distance as follow:

library(sf)

xco<-c(320963.6,421813.6,315423.6,405733.6,365603.6)
yco<-c(172137.7,165287.7,232197.7,138917.7,183697.7)
mydata<-data.frame(xco,yco)

mydata_sf<-st_as_sf(mydata, coords = c("coords.x1", "coords.x2"), crs = 2100)

dist_df<-as.data.frame(st_distance(mydata_sf))

min(dist_df[dist_df> 0])

However, that gives me a value which I can not see in my data. Can anyone suggest a faster and better way to do that?

Thank you!

CodePudding user response:

You have an error in your code. The fifth line should be

mydata_sf <- st_as_sf(mydata, coords = c("xco", "yco"), crs = 2100)

Then

dist_df <- as.data.frame(st_distance(mydata_sf))

Gives you a labeled distance matrix. You just need the upper or lower triangle:

range(dist_df[lower.tri(dist_df)])
# [1]  30885.97 129834.72

The first value is the minimum distance and the second is the maximum.

  • Related