# How can I both resample and aggregate a raster using Terra?

I essentially have the same issue described here, but this question has not been answered Can I resample a raster in R using "max" as function?.

I have a elevation raster with a resolution of 100m. I would like to resample to create a new dataset that has the same grid as another raster I'm using, lets say landcover, which has a resolution of 4500m. I would like the value in the new dataset to be the standard deviation of elevation within the new grid cell.

It seems to me like both the aggregate and resample functions each do one of the things I need to do, but not the other. Aggregate would allow me to specify the stdev function, but it doesn't seem like I can get the grid to match another raster. Resample would allow me to match the grid of another raster, but I can't use stdev as the resampling function.

How could I approach this problem?

• Resampling doesn't in general result in an exact overlap of source-destination grid cells, so what do you want to do about all the bits of cells that overlap? You could convert to polygons and do intersections and weighted calculations, but I don't really understand what you get out of doing a "resample with summary function" in the general case. Feb 8 at 20:41
• Maybe `exactextractr::exact_resample(elev, landcov, 'stdev')` ? Feb 10 at 0:22

You can first resample to a high resolution raster that is aligned with the low resolution raster and then use aggregate

Example data:

``````library(terra)
f <- system.file("ex/elev.tif", package="terra")
low <- rast(f)
high <- aggregate(rast(r), 5) |> extend(c(2,2)) |> shift(.04, .04)
``````

Solution:

``````dr <- res(high) / res(low)
a <- disagg(high, dr)
# using "near" to avoid smooting
a <- resample(r, a, "near")
b <- aggregate(a, dr, "sd", na.rm=TRUE)
``````

But this should be more precise (thanks to @dbaston's comment):

``````e <- exactextractr::exact_resample(low, high, 'stdev')
``````

The results are similar, see

``````plot(b, e); abline(0,1)
``````
• Thanks. I used the exact_resample method, this was exactly what I was looking for. Mar 18 at 15:50