[英]How to aggregate categorical SpatRaster
I am new to the terra package.我是 terra 包的新手。 I am trying to
aggregate
a categorical raster (or a SpatRaster, to be more precise) that has only one layer.我正在尝试
aggregate
只有一层的分类栅格(或 SpatRaster,更准确地说)。 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.
对于大型栅格数据集(1GB-10GB 数量级)和许多类别,这可能(?)不可行。
So, how would a terra
pro do this?那么,
terra
pro 将如何做到这一点?
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.