0

I have two data sets including coordinates of certain points. I want to write a function that calculates the distance between the closest coordinate points that exist between both data sets.

How would I write this function that gives me a list of the distance between each of the closest coordinate points?

I have mapped the points so far on a ggplot map in R. But I want to calculate the distance between these points to make statistical inference.

Pelles
  • 9
  • Check out the sf package – Just James Feb 23 '23 at 22:00
  • 1
    Relevant info if you're considering the map as a flat 2D surface - https://stackoverflow.com/questions/40668623/find-closest-value-for-every-row-in-a-matrix-from-another-matrix/40669071 - otherwise using `sf` and the geographic calculations should do it: https://stackoverflow.com/questions/49853696/distances-of-points-between-rows-with-sf – thelatemail Feb 23 '23 at 22:10
  • 1
    Please provide enough code so others can better understand or reproduce the problem. – Community Feb 23 '23 at 22:15
  • The function `rdist()` in package `fields` does this. Is there a reason you want to compute your own function? – dcarlson Feb 24 '23 at 04:07
  • Yes, so what I want is to measure the distance between coordinates to eventually measure how long it would take to travel between these points. But I cannot seem to find a loop function that will calculate this row by row between both data sets containing the coordinates I have – Pelles Feb 24 '23 at 18:23

1 Answers1

0

This might work, although it's hard to know without seeing your data.

If it's not already, make sure your data is set up for use with the sf package (i.e., has a geometry column) using the st_as_sf() function

library(sf)

a <- <your-data_set_1>
b <- <your-data_set_2>

near <- st_nearest_feature(a, b)
dist <- st_distance(a, b[near,], by_element = T)

dist will then be a list of the distance to the nearest feature b for each obervation in a

ttalVlatt
  • 138
  • 6
  • My code includes data of longitude and latitude data that I have created into a data frame. I am just getting an error when trying to run the code. – Pelles Feb 24 '23 at 01:41
  • To be able to make this kind of calculation, you need the long and lat to be converted into geometry r can recognize. To do that, you use `df %>% st_as_sf(coords = c("", "")) %>% st_set_crs(4326)` – ttalVlatt Feb 24 '23 at 03:11
  • Also, if you want to account for curvature of the earth in your distance calculation, after running the above, you can use `df <- st_transform(df, crs = )` – ttalVlatt Feb 24 '23 at 03:18