I want to compare 2 rasters and when there is a change from 2 to 1 create a new raster that replaces the cell where the change has been detected with the change variable.

## Finds Cells that have changes from 2 to 1
Test <- (rasterT1==2 & rasterT2==1)
Date <- Test
Date[Test == 1,] <- change

Essentially is if rasterT1 > rasterT2 then add the change value to that cell. With the new raster called year using raster overlay, however I'm not sure how this would be executed.

If you need any more details let me know.

1 Answer 1


A simple "ifelse" statement should suffice in evaluating a condition.

Here we create two random vectors of [1,2] and apply an ifelse to evaluate the condition of if x = 2 and y = 1 THEN change (1) ELSE no change (0).

( x <- round(runif(10, 1, 2)) )
( y <- round(runif(10, 1, 2)) )   
ifelse( x == 2 & y == 1, 1, 0)

Since this is just an evaluation of one vector being greater than another then one can just use an operator and coerce the Boolean result to numeric [0,1] corresponding to FALSE/TRUE.

as.numeric(x > y) 

We can then expand this application of ifelse to a raster stack using overlay. It is best to encode change with an actual value rather than a character. The resulting raster will have the values, as in the above example, 1 for change and 0 for no change.

fn <- system.file("external/test.grd", package="raster")
  s <- stack(fn, fn)
  s[[1]] <- round(runif(ncell(s), 1, 2))
  s[[2]] <- round(runif(ncell(s), 1, 2))

s.change <- overlay(s[[1]], s[[2]], fun = function(x,y) { ifelse( x == 2 & y == 1, 1, 0) } )

If it is always going to be a "> or <" operator, then things are much simpler. The double brackets index a specific raster in the stack.

s.change <- s[[1]] > s[[2]]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.