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
}
}
I believe you are looking for a
sf::st_distance()call. When used on a singlesfdata 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}):