I am new to the terra package. I am trying to aggregate a categorical raster (or a SpatRaster, to be more precise) that has only one layer. The result should be a raster with as many layers as categories in the original raster; the cells' values should have the number of original (smaller) cells in each category.
Here's an example showing what I trying to achieve:
library(terra)
# the SpatRaster with 3 categories: 1, 2, 3
set.seed(0)
r <- rast(nrows=4, ncols=4)
values(r) <- sample(3, ncell(r), replace=TRUE)
# create one layer per category with binary indicators
r1 <- subst(r, from=c(2,3), 0)
r2 <- subst(r, from=c(1,3), 0); r2 <- subst(r2, from=2, 1)
r3 <- subst(r, from=c(1,2), 0); r3 <- subst(r3, from=3, 1)
# stack
s <- c(r1, r2, r3)
names(s) <- c("cat1", "cat2", "cat3")
# aggregate
a <- aggregate(s, fact = 2, fun = "sum")
This works for this example. But it is not practical nor efficient. It is probably(?) not feasible with large raster datasets (orders of magnitude 1GB-10GB) and many categories.
So, how would a terra pro do this?