I have a gridded dataset, with data available at the following locations:
lon <- seq(-179.75,179.75, by = 0.5)
lat <- seq(-89.75,89.75, by = 0.5)
Just use hutils::haversine_distance(lat, lon, mylat, mylon) < 500
directly.
If the points are assumed to be a cross join of the given lat
and lon
, use a cross-join first to obtain them:
library(data.table)
library(hutils)
lon <- seq(-179.75,179.75, by = 0.5)
lat <- seq(-89.75,89.75, by = 0.5)
mylat <- 47.9625
mylon <- -87.0431
Points <- CJ(lon = lon,
lat = lat)
Points[, dist := haversine_distance(lat, lon, mylat, mylon)]
Points[, sum(dist < 500)]
#> [1] 379
Created on 2019-10-24 by the reprex package (v0.3.0)
It improves on the existing answers by its speed and robustness. In particular, it does not rely on the gridded nature of the data and will work with long vectors of coordinates. Below are timings for 100,000 points
# A tibble: 2 x 14
expression min mean median max `itr/sec` mem_alloc n_gc n_itr total_time
1 nicola2 39891.120ms 39891.120ms 39891.120ms 39891.120ms 0.0251 8808.632MB 0 1 39891.120ms
2 hutils 15.492ms 15.591ms 15.578ms 15.728ms 64.1 5.722MB 0 33 514.497ms