Search code examples
rraster

Difference between raster R


I have two Raster objects

> x1
class       : RasterLayer 
dimensions  : 36, 72, 2592  (nrow, ncol, ncell)
resolution  : 1.35, 1.291667  (x, y)
extent      : -97.2, 0, 20, 66.5  (xmin, xmax, ymin, ymax)
coord. ref. : NA 
data source : in memory
names       : layer 
values      : -9.527037, 15.03242  (min, max)

> x2
class       : RasterLayer 
dimensions  : 36, 72, 2592  (nrow, ncol, ncell)
resolution  : 1.351389, 1.333333  (x, y)
extent      : -97.3, 0, 20, 68  (xmin, xmax, ymin, ymax)
coord. ref. : NA 
data source : in memory
names       : layer 
values      : -5, 5  (min, max)

And I want to creat a raster of the difference. However, when I try

x <- Reduce("-",list(x1,x2))

I get this error

Error in compareRaster(e1, e2, extent = FALSE, rowcol = FALSE, crs = TRUE, : different origin

Can anyone help?


Solution

  • You need to resample one of the two RasterLayer objects such that both have the same extent and resolution. (Although in many cases you really should go back in your pipeline and assure that this is the case from the start). You can do something like this:

    library(raster)
    # example data
    x1 <- raster(xmn=-97.2, xmx=0, ymn=20, ymx=66.5, nrow=36, ncol=72)
    x2 <- raster(xmn=-97.3, xmx=0, ymn=20, ymx=68, nrow=36, ncol=72)
    values(x1) <- runif(ncell(x1))
    values(x2) <- sample(-5:5, ncell(x2), replace=TRUE)
    
    x1b <- resample(x1, x2)
    dif <- x2 - x1b
    

    Using resample is a function of last resort. In cases where the origin and resolution of two layers are the same, but not the extent, you can use crop. In cases where the extent is the same, but not the resolution, you may be able to use (dis)aggregate. Sometimes a combination of crop and (dis)aggregate is best.