How to resample a raster snapping to an existing grid?

Wraf picture Wraf · Oct 8, 2013 · Viewed 7.2k times · Source

I would like to resample a raster from a high resolution to a low resolution (with different extent) in a defined grid cell. Is there a way of using an existing raster file as input for the snapping?

In the raster package, aggregate and resample seem to be adequate but I can't find how to do it.

Answer

Simon O'Hanlon picture Simon O'Hanlon · Oct 8, 2013

You can use projectRaster for this if you have a raster in one projection and resolution and you need output in a different particular resolution and projetion.

The from argument is your high resolution raster and the to argument is your low res raster. Make sure you choose the correct method for aggregation (i.e. bilinear for continuous data and ngb (nearest neighbour) for categorical data.

require( raster )

#  Projection info
proj1 <- CRS("+proj=laea +lon_0=20 +lat_0=5 +ellps=sphere +unit=km +to_meter=1e3")
proj2 <-  CRS("+proj=longlat +datum=WGS84 +ellps=WGS84")
#  High res raster
r1km <- raster( nrows = 1515 , ncols = 2300 , xmn = -4000 , xmx = -1700 , ymn = -15 , ymx = 1500 , crs = proj1 )

#  Low res raster
r5km <- raster( nrows = 303 , ncols = 460 , xmn = -20 , xmx = -5 , ymn = 4 , ymx = 15 , crs = proj2 )

#  Set some values in high res raster
pts <- rasterToPoints(r1km)
values( r1km ) <-  0.01*pts[,1] + sin(0.02*pi*pts[,2])

#  Reproject using the attributes of the low res raster for output
out <- projectRaster( from = r1km , to = r5km , method = "bilinear" )

#  Plot - extent of second raster doesn't fully cover first so some data is missing
par( mfrow = c(1,2) )
plot( r1km )
plot( out )

enter image description here

If your input and output data are the same except in resolution you can use aggregate...

#  If same extent and resolution require use aggregate
r1 <- raster(system.file("external/rlogo.grd", package="raster"))
r5 <- aggregate( r1 , fact = 5 , method = "bilinear" )
par( mfrow = c(1,2) )
plot( r1 )
plot( r5 )

enter image description here