我的栅格堆栈中有四个层,并且想要在这四个层中的每个单元格中选取最常见的值。
这是数据集和代码:
require(raster)
a <- raster(matrix(c(12,11,11,
NA,11,11,
11,11,13),nrow=3))
b <- raster(matrix(c(12,12,12,
NA,12,12,
14,12,13),nrow=3))
c <- raster(matrix(c(13,9,13,
NA,13,13,
13,NA,13),nrow=3))
d <- raster(matrix(c(10,10,10,
NA,10,10,
10,10,10),nrow=3))
stk <- stack(a,b,c,d)
我想知道是否可以用类似的代码来做到这一点?
which.freqV <- function(x, ...){
???
}
max <- stackApply(stk,1,which.freqV,na.rm=NULL)
我必须在我的脚本中做到这一点(计算堆栈的模式)并发现一些可以完美工作的东西:
Mode <- function(x) {
ux <- unique(x)
ux=ux[!is.na(ux)]
ux[which.max(tabulate(match(x, ux)))]
}
layers_mode=calc(stack, fun=Mode)
现在,如果您想计算每个单元格的模式频率,请使用以下命令:
###calculate proportion of layers that have mode value as measure of uncertainty
Mode_count <- function(x) {
ux <- unique(x)
ux=ux[!is.na(ux)]
mode=ux[which.max(tabulate(match(x, ux)))]
sum(x==mode, na.rm=T)
}
layers_mode_freq=calc(stack, fun=Mode_count)
您还可以考虑模态函数,它也提供了一些处理关系的方法。
光栅包:
# S4 method for Raster
modal(x, ..., ties='random', na.rm=FALSE, freq=FALSE)
terra 套餐:
# S4 method for SpatRaster
modal(x, ..., ties="first", na.rm=FALSE, filename="", overwrite=FALSE, wopt=list())
一些非常基本的东西
a <- freq(stk, merge=TRUE)
a$nt <- rowSums(a[, -1], na.rm = T)
with(a, a[order(nt, decreasing = T), ])