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
CodePudding user response:
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.
CodePudding user response:
You cannot aggregate r2 to r1 because res(r2)/res(r1)
does not return whole numbers.
res(r2)/res(r1)
#[1] 2.5 2.5
More generally, you cannot assume that you can aggregate one raster to another, so having another raster as second argument is not as obvious as with other methods such as resample.
In this special case you can do
x <- aggregate(disagg(r2, 5), 2, mean)