# Substract one raster from another based on coordinates

As the title suggests im trying to substract the values of one Raster (r2) from another Raster (r1) based on the locations of points (GPS coordinates). To show my problem ive created 2 rasters and a matrix for the points

``````r1<-extent(0, 50, 0, 50)
r1<-raster(r1)
values(r1)<-10
r2<-extent(0, 50, 0, 50)
r2<-raster(r2)
values(r2)<-6
pts <- matrix(1:20, nrow=20, ncol=2)
``````

Now i want to create a third Raster (r3) that contains in every pixel the values of r1 except for the pixels who intersect with the points (so value 4 for those 20 rastervalues and 10 for all the others.

``````for (i in seq(1, length(pts[,1]))) {
r3<-r1-r2
}
``````

With this code im getting a 4 for all the pixels, any ideas? ;)

Let me interpret this:

Now i want to create a third Raster (r3) that contains in every pixel the values of r1 except for the pixels who intersect with the points (so value 4 for those 20 rastervalues and 10 for all the others

Pixels free of intercept: value of `r1`, so 10

Pixels with intercept: value of `r1` - `r2` = 4

If I interpreted it well: Use `mask` function, `inverse` argument ease the procedure. You need to convert `pts` into a `SpatialPoints` object as well:

``````points <- SpatialPoints(pts)

r1_b <- mask(r1,points, inverse = T)

r1_c <- mask(r1 - r2,points,inverse = F)

r3 <- mosaic(r1_b, r1_c, fun = 'sum')

plot(r3)
``````

• perfect, thank you :) Dec 21, 2021 at 17:56