Search code examples
rr-rasterterra

How to calculate aggregate fact parameter in terra package?


The terra package has the aggregate function that allows to create a new SpatRaster with a lower resolution (larger cells) but needs the fact parameter.

When converting many rasters, fact needs to be calculated each time, is there a way to pass the fact parameter based on the target resolution of another raster? Other functions take an existing raster as input, such as function(r1,r2)

library(terra)
r1 <- rast(ncol=10,nrow=10)
r2 <- rast(ncol=4,nrow=4)
values(r1) <- runif(ncell(r1))
values(r2) <- runif(ncell(r2))

I have tried

r3 = aggregate(r1,fact=res(r1)/res(r2))

Error: [aggregate] values in argument 'fact' should be > 0


Solution

  • Found the answer, I had the res(r1)/res(r2) inverted, it should be

    r3 = aggregate(r1,fact=res(r2)/res(r1))

    Still it would be much better just to pass the name of the target's raster resolution.