Reputation: 1013
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?
Upvotes: 3
Views: 991
Reputation: 47026
Here is a more streamlined approach
Your example data:
library(terra)
set.seed(0)
r <- rast(nrows=4, ncols=4)
values(r) <- sample(3, ncell(r), replace=TRUE)
solution:
s <- segregate(r)
a <- aggregate(s, 2, sum)
It is also possible to do this:
b <- list()
for (i in 1:3) {
b[[i]] <- aggregate(r, 2, function(v) sum(v==i,na.rm=TRUE))
}
b <- rast(b)
Which you can also write like this (I wouldn't recommend it)
bb <- lapply(1:3, \(i) aggregate(r, 2, \(v) sum(v==i,na.rm=TRUE))) |>
rast()
Upvotes: 2