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

I have an empty raster and point shapefile (points = black dots in the image). For the analysis I use a Digital Elevation Model (DEM) with the same extent and cell size as the empty raster.

I would like to fill the empty raster cells with the elevation difference between every raster cell of the empty raster and the raster cell where the closest point is situated.

The green lines show distance between every raster cell the respective closest point. Result: a raster with every cell filled difference in elevation between the cell elevation and the elevation from the cell where the point is located. The first thing to know is: Which is the closest point? The distance between a raster cell and the closest point can be calculated with the distanceFromPoint tool:

``````r <- raster('./Raster/DEM/DEM_Refocus_5kmBuffer.tif')

dfp <- distanceFromPoints(r, s)
``````

But what I actually need is the elevation differnce between every raster cell of the raster and the the points. Do you have an idea to obtain this?

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)
gives you a raster of the value in `r` for the nearest point in `s`, which looks like a voronoi diagram (as it should). 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.