How to calculate distance between all possible combinations of points within a group

378 Views Asked by At

I have a sf object with 68 observation. In each location I have 4 different points, with different PointIDs(SchlagID) but same LocationIDs(FieldID). I want to now calculate the distance between each point by location in a way that there a total of 6 values for each location (including the diagonal distances, assuming the points are in a square)

Till now I have been able to calculate 4 values but not sure how to calculate the diagonal distances as well.

Here is what the data looks like

Here is the code I am working on

pdist.df = data.frame(trapID=NA,LS=NA,dist=NA)
list.lsFeat = 1
counter=1


for(i in 1:nrow(raps_filtered_sf)){
    
  
  this.trap=raps_filtered_sf[i,]
  
  for(l in list.lsFeat){
    
    this.feat = raps_filtered_sf %>%
      filter(FieldID==this.trap$FieldID)
    
    #ind <- st_nearest_feature(this.trap, this.feat)
    dis <- st_distance(this.trap, this.feat)
    print(paste0("trap: ", this.trap$SchlagID, "//LS: ", this.feat$SchlagID, "//Dist: ", dis))
    
    pdist.df[counter,] = c(trapID=this.trap$SchlagID, LS=l, dist=dis)
    counter=counter+1
  }
}

1

There are 1 best solutions below

1
Jindra Lacko On

I believe you are looking for a sf::st_distance() call. When used on a single sf data frame it will output a distance matrix.

A little finetuning of names makes it easier to interpret, but is not strictly required.

For an example consider this piece of code, built on top of 3 semi-random North Carolina cities (because I am deeply in love with the nc.shp file that ships with {sf}):

library(sf)
library(dplyr)

# 3 semi rancom cities in NC (because I *deeply love* the nc.shp file)
cities <- data.frame(name = c("Raleigh", "Greensboro", "Wilmington"),
                     x = c(-78.633333, -79.819444, -77.912222),
                     y = c(35.766667, 36.08, 34.223333)) %>% 
  st_as_sf(coords = c("x", "y"), crs = 4326)

# prepare a distance matrix
mtx <- st_distance(cities)

# give the rows & cols meaningful names
colnames(mtx) <- cities$name
rownames(mtx) <- cities$name  

# see my work, and find it good...
mtx

# Units: [m]
#             Raleigh Greensboro Wilmington
# Raleigh         0.0   112342.9   183751.2
# Greensboro 112342.9        0.0   269595.9
# Wilmington 183751.2   269595.9        0.0