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?

A <- raster("A.tif")
B <- raster("B.tif")
C <-  stack(A, B)

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){
  • 1
    Take a look at the terra package, there is a terra::ifels method that mirrors ifelse. The terra package is intended to be the replacement for raster. There is only one raster class and the interface function is terra::rast Oct 28, 2021 at 17:19

1 Answer 1


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.

  • That does exactly the same as my code but it only takes some seconds. Thanks
    – sfetan
    Oct 28, 2021 at 17:48
  • 1
    Most arithmetic and logical operators and functions will work on raster objects to produce more raster objects.
    – Spacedman
    Oct 28, 2021 at 18:32

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.