Raster Calculation – How to Use Conditions in R for Raster Calculations

gdallooprrasterrasterbrick

I have two rasters (A,B) with the same resolution, extent and crs. Now I would like to generate a raster C with the value 1 for each cell that have a value of 30 or higher in A and B. I use a loop, but this approach takes ages, are there faster solutions?

library(raster)
A <- raster("A.tif")
B <- raster("B.tif")
C <-  stack(A, B)
C$result<-as.numeric(NA)
C<-brick(C)

for (li in 1:length(C$result)){
  if (!is.na(C$A[li])&!is.na(C$B[li])){
    if (C$A[li]>=30 & dfa$C$B[li]>=30){
      C$result[li]<-1
    } 
  }
}

Best Answer

It should be a one-liner:

C <- A >= 30 & B >= 30

That gets you a raster of 0/1. If you want NAs for 0, then do:

C[C==0] = NA

as well.