Skip to content
Prev 27891 / 29559 Next

How to find distance between grid cell and point that lies in specified radius?

Hi,

I think you'll enjoy sf once you get going with it.

I am not familiar with the Cressman scheme, but you maybe able to do
step 1 with raster (either pointDistance() or distanceFromPoints() - I
can't quite recall).  In sf you could something like this..

library(raster)
library(sf)
library(units)
library(dplyr)

crs <- "+proj=poly +lat_0=0 +lon_0=-54 +x_0=5000000 +y_0=10000000
+ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs"
r <- raster(nrows=9, ncols=18,
            xmn=5153337, xmx=6570069,
            ymn=7462732,ymx=8060416,
            crs = crs)
r[] <- runif(ncell(r))

xy <- raster::xyFromCell(r, seq_len(ncell(r)))
xy <- lapply(seq_len(nrow(xy)), function(i) sf::st_point(xy[i,]))
xy <- sf::st_sfc(xy, crs = crs)

pts <- sampleRandom(r, 10, na.rm = TRUE, sp = TRUE) %>%
  sf::st_as_sfc()

d <- sf::st_distance(xy, pts)
threshold <- units::set_units(100000, m)
d_within <- d <= threshold


d will be a [ncell x npoints] numeric matrix of distance from cell
locations to points
d_within will be a matrix [ncell x npoints] of logicals flagging which
are within your threshold (I used 100km)

Hope that helps start you off.

Cheers,
Ben



On Wed, Feb 5, 2020 at 9:12 PM Thiago V. dos Santos via R-sig-Geo
<r-sig-geo at r-project.org> wrote: