Search code examples
rconditional-statementsraster

Conditional statement using two raster in R


I am trying to create this grid "To divide the population grid into two segments: (A) population with lighting detected, and (B) population with no lighting detected". I have two raster data, a population.tif and a nighttimelights.tif. Basically, I want to meet two conditions:

population > 1 and nighttimelights > 20, this is segment A population > 1 and nighttimelights < 20, this is segment B I want to create the conditional statement in R. What I have tried so far is:

    library(raster)
    
    ntl = raster("path/ntl_atprk.tif")
    
    pop = raster("path/pop.tif")  
    
    pop = resample(pop, ntl, method = 'bilinear')
    
    if('pop' > 1 && 'ntl' >= 20) {
      *make the pop.tif raster's cell = 1*
    }
if('pop' > 1 && 'ntl' < 20) {
      *make the pop.tif raster's cell = 2*
    }

Solution

  • You can use terra::ifel for that.

    Example data

    library(terra)
    set.seed(0)
    ntl <- rast(nrow=50, ncol=20, val=sample(40, 1000, replace=TRUE))
    pop <- rast(nrow=50, ncol=20, val=sample(0:10, 1000, replace=TRUE))
    

    Solution

    x <- ifel(pop <= 1, NA, 
           ifel(ntl >= 20, 1, 2))
    

    You did not specify what you would like to do with cells that have pop <= 1. I have assumed that you want to assign NA to these cells

    Here is an alternative approach that achieves the same for these data

     pm <- pop > 1
     nm <- ntl < 20
     y <- mask(pm + nm, pm, maskvalue=FALSE)