Search code examples
rif-statementraster

create new raster from raster using if statement in R


I have a raster layer showing SST during present, but only showing pixels where I know is suitable habitat for a species. All other pixels are set NA.

Now I have the same raster layer, but showing predicted SST for 2050. In this raster layer, all pixels have a value (except NA on land surfaces).

Now I want to do the following: I want to search the second raster layer for the values given in the first raster layer and set all other values 0. So the result should be a raster showing only pixels which have values that can also be found in the first raster.

I think the right function to use would be if else function.

Is there a way to use all values of a raster in an if else function? The code should be something like the following then:

    if(raster1==raster2){
      raster3 <- 1
      }else{
      raster3 <- 0
      }

Solution

  • Here is some example data, so that the you get a minimal self-contained reproducible example.

    library(raster)
    s <- r <- raster(ncol=5, nrow=5)
    values(r) <- rep(c(1,NA,1,NA,1), 5)
    values(s) <- 1:25
    

    You can do what you are after (set all values in s, where r is NA, to 0) like this

    x <- mask(s, r, updatevalue=0)
    

    You could also use algebra

    y <- (!is.na(r)) * s
    

    There actually is a (hidden) ifel method, but that is less efficient

    z <- raster:::.ifel(!is.na(r), s, 0)