17

I am trying to align two raster grids in R. Once aligned I would like to be able to add them together.

I have tried to check whether making a stack would work:

grid_snap <- stack(habi_sdw, Pop_sdw)

And I get the following error:

Error in compareRaster(x) : different extent

The raster grids have the following properties:

show(habi_sdw)
# class       : RasterLayer 
# dimensions  : 9187, 9717, 89270079  (nrow, ncol, ncell)
# resolution  : 0.00892857, 0.00892857  (x, y)
# extent      : -28.83706, 57.92186, -36.02464, 46.00214  (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=longlat +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +no_defs 
# data source : C:\Users\di39\AppData\Local\Temp\R_raster_di39\raster_tmp_2015-08-12_172902_12860_17067.grd 
# names       : layer 
# values      : 0, 333707.6  (min, max)

show(Pop_sdw)
# class       : RasterLayer 
# dimensions  : 10143, 8858, 89846694  (nrow, ncol, ncell)
# resolution  : 0.008333333, 0.008333333  (x, y)
# extent      : -17.53524, 56.28143, -46.97893, 37.54607  (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0 
# data source : C:\Users\di39\AppData\Local\Temp\R_raster_di39\raster_tmp_2015-08-12_170421_12860_12760.grd 
# names       : pop2010ppp 
# values      : 0, 128925.9  (min, max)

Using alignExtent() in the raster package seems not to be the correct approach.

Do I need to resample because the resolutions are slightly different?

(0.00892857 x 0.00892857) vs (0.008333333 vs 0.008333333)

Aaron
  • 51,658
  • 28
  • 154
  • 317
DI1
  • 311
  • 1
  • 2
  • 4

2 Answers2

25

This question is similar to: Clip raster by raster with data extraction and resolution change, but coming from a different angle. However, I think the answer is likely the same. First off, choose which raster you wish to be definitive. I'll repeat my previous answer here for ease:

Load required libraries:

library(raster)
library(rgdal)

Read rasters:

r1 = raster("./dir/r1.tif")
r2 = raster("./dir/r2.tif")

Resample to same grid:

r.new = resample(r1, r2, "bilinear")

If required (for masking), set extents to match:

ex = extent(r1)
r2 = crop(r2, ex)

Removed data which falls outside one of the rasters (if you need to):

r.new = mask(r.new, r2)

Your rasters now match.

MikeRSpencer
  • 972
  • 6
  • 12
2

Yes. You need to resample your rasters in order for them to be the same size and have the same extent. R doesn't deal with that by itself. Given that neither of your rasters fully contain the other, you should consider creating a minimum-extent raster with your preferred resolution, and then resample and crop the others to match that.

  • 2
    Please elaborate your answer, for example by providing some sample code. –  Aug 14 '15 at 09:01