Raster – How to Subtract Two Rasters with Discrete Values in R

differencesland-coverrraster

I'm working with these two rasters:

clc_forest18
class      : RasterLayer 
dimensions : 16000, 12000, 1.92e+08  (nrow, ncol, ncell)
resolution : 100, 100  (x, y)
extent     : 4e+06, 5200000, 1200000, 2800000  (xmin, xmax, ymin, ymax)
crs        : +proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs 
source     : r_tmp_2022-02-03_154451_11816_01443.grd 
names      : layer 
values     : 0, 1  (min, max)

clc_forest00
class      : RasterLayer 
dimensions : 16000, 12000, 1.92e+08  (nrow, ncol, ncell)
resolution : 100, 100  (x, y)
extent     : 4e+06, 5200000, 1200000, 2800000  (xmin, xmax, ymin, ymax)
crs        : +proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs 
source     : r_tmp_2022-02-03_152439_11816_04240.grd 
names      : layer 
values     : 0, 1  (min, max)

I want to get the difference between the clc_forest18 and clc_forest00 in order to see where there are values 1 in 2018 that weren't in 2000. Value 1 is where there is forest cover. In other words I want to see where the forest came back.

I used:

forest_cover_diff <- overlay(clc_forest18, clc_forest00, fun=function(r1, r2){return(r1-r2)})
plot(forest_cover_diff, main="Difference between 2018 and 2000 a.k.a. Where forest came back")

and also:

forest_cover_diff <- clc_forest18 - clc_forest00 
plot(forest_cover_diff, main="Difference between 2018 and 2000 a.k.a. Where forest came back", axes=FALSE) 

but I get a yellow image. I guess it's because im working with discrete values.
How can I get the difference then?
My goal is to get an image where only new forest pixels (2018) is colored, to see where a rewilding process happened.

Best Answer

Let's make two tiny rasters of 1s and 0s in slightly different patterns:

clc_forest18 = raster(matrix(c(1,1,0,0),2,2))
clc_forest00 = raster(matrix(c(1,0,1,0),2,2))

enter image description here

plot(clc_forest18 - clc_forest00)

subtracting them gives me this:

enter image description here

ie yellow (0) where they are the same, green (+1) where forest18=1 and forest00=0, and white (-1) where its the other way around.

If you are seeing an all yellow plot then either:

  • Your data are equal everywhere (eg if you plot the difference of the same raster: plot(clc_forest18 - clc_forest18))
  • You're not seeing the difference because the high resolution of your data means R can't plot all the cells. Try:
fdiff = clc_forest18 - clc_forest00
table(values(fdiff))
    
 -1  0  1 
  1  2  1 
Related Question