Search code examples
rgpsgeospatialspatial

How to find the maximum distance between any pair of GPS points?


I am trying to determine the maximum distance between any two pairs of GPS points in a data frame containing 1000's of GPS points. I am not sure what I have done thus far is correct. How can I accomplish this? Thanks

structure(list(Id = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L), .Label = "A628", class = "factor"), DateTime = structure(c(1557401400, 
1557403200, 1557405000, 1557406800, 1557408600, 1557410400, 1557417600, 
1557419400, 1557421200, 1557423000), class = c("POSIXct", "POSIXt"
), tzone = "CST6CDT"), Longitude = c(-97.4468676, -97.4760327, 
-97.4766244, -97.4768354, -97.4766027, -97.4762566, -97.4756206, 
-97.4760795, -97.4757018, -97.4758084), Latitude = c(26.5649515, 
26.5864111, 26.5874319, 26.5874866, 26.5874287, 26.5878552, 26.5881477, 
26.588534, 26.5879895, 26.5876414)), row.names = c(NA, 10L), class = "data.frame")
library(sp)
library(adehabitatHR)
library(raster)
library(rgdal)
library(sf)

collars <- read.csv('C:\\Users\\kujld016\\Desktop\\All\\Projects\\Thermal_Deer\\all_data\\collars_clean.csv')

collars <- collars %>%
  mutate_if(is.character, as.factor) %>%
  mutate(DateTime=as.POSIXct(DateTime, format="%Y-%m-%d %H:%M:%S",tz='CST6CDT'))

for(j in 1:length(collars)) {
  collarIDs <- unique(collars$Id)
  
  for(i in 1:length(collarIDs)) { 
    collarID <- collarIDs[i]
    collar <- filter(collars, Id == collarID)
    
    #coerce to spatialpointsdataframe and reproject
    dat.sp<-SpatialPointsDataFrame(coords=collar[c('Longitude', 'Latitude')],data=collar,
                                   proj4string=CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"))
    
    dat.proj <- spTransform(dat.sp, CRS("+proj=utm +zone=14 +ellps=GRS80 +datum=NAD83 +units=m +no_defs"))

aref <- (max(spDists(dat.proj))) ###is this calculating the maximum distance between any 2 points in the data frame

Solution

  • Easier with the sf package, rather than sp:

    library(sf)
    library(dplyr)
    
    # the_data <- from posted sample data in question
    # make data.frame an sf object with lat/lon projection
    data_sf <- st_as_sf(the_data, coords = c("Longitude", "Latitude")) %>%
      st_set_crs(4326)
    
    # distance matrix for all the points
    dist_mat <- st_distance(data_sf)
    
    # where's the longest distance?
    which(dist_mat == max(dist_mat), arr.ind = TRUE)
    #>      row col
    #> [1,]   8   1
    #> [2,]   1   8
    
    dist_mat[8,1]
    #> 3913.472 [m]
    

    Created on 2022-04-08 by the reprex package (v2.0.1)