I would like to aggregate a population raster by a factor of 1.5, summing the values of the cells.
While aggregate()
allows me to sum values when aggregating, its factor
parameter accepts only integer values. projectRaster()
and resample()
allow me to adjust the resolution precisely, but (as far as I know) I am restricted to the prepackaged bilinear-interpolation and nearest-neighbor computation methods.
Is there a way to aggregate a raster by a non-integer factor AND specify the function to use when aggregating?
library(raster)
set.seed(10)
proj <- "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"
r <- raster(resolution = 1, nrow = 100, crs = proj)
r[] <- round(rnorm(ncell(r), 100, 10))
# Doesn't accept non-integer factors
aggregate(r, fact = 1.5, fun = sum)
template <- raster(extent(r), crs = crs(r), resolution = 1.5)
# Correct resolution, but incorrect / impossible values for population
projectRaster(r, to = template, method = "ngb")
projectRaster(r, to = template, method = "bilinear")
Possible workaround
So far, the only method I've been able to come up with is to coerce the template to a SpatialPoints
object; extract values from the original, higher-resolution raster; and rasterize()
the result:
pts <- as(template, "SpatialPoints")
vals <- extract(r, pts)
pts2 <- SpatialPointsDataFrame(pts, data.frame(vals))
rasterize(pts2, template, field = "vals", fun = sum)
However, if the points are created at the centroids of the raster cells, I'm not sure how they are handled when extracting with a resolution of 1.5x the original raster. My preferred method would be to create a SpatialPolygonsDataFrame
and rasterize with fun = mean
, but (in my experience) extracting raster values using polygons is very inefficient.