# Raster calculation with conditions in R

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
}
}
}
``````
• 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

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 Oct 28, 2021 at 17:48
• Most arithmetic and logical operators and functions will work on raster objects to produce more raster objects. Oct 28, 2021 at 18:32