How to obtain elevation differences between point and raster cell in R

Outline solution:

  • Install the FNN package from CRAN.
  • Use nni = FNN::knnx.index(coordinates(s), coordinates(r), k=1) to get the index in s of the nearest neighbour for each cell coordinate to the points.

  • Using cellFromXY to get the cell number of each point, index that by the nearest neighbour index to pull out the value in r for each nearest point.

nelev = raster(r) # empty raster of same basis as r
nelev[] = r[cellFromXY(r, coordinates(s))[nni]]     
plot(nelev)
plot(s, add=TRUE)

gives you a raster of the value in r for the nearest point in s, which looks like a voronoi diagram (as it should).

enter image description here

You can then subtract that from r or do whatever you want with it. I've used noise for r so it looks awful if I do so I wont.


  1. Voronoï around points as raster (find nearest raster points to given points)
  2. Migrate point DEM value to corresponding Voronoï cells (reference altitude to use for those raster points)
  3. Difference between DEM and attributed Voronoï cells (to get your required value)

Should do the trick