1

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? ;)

1 Answer 1

2

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)

enter image description here

1
  • perfect, thank you :)
    – DennyCrane
    Commented Dec 21, 2021 at 17:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.