0

我正在使用包中的一个非常基本的聚合aggregate操作terra。主要思想是使用以下函数计算具有值的像素占整数的百分比:

nofun = function(x){ length(na.omit(x))/length(x) * 100 }

不幸的是,aggregate在不同的条件下失败 - 甚至更简单 - 我无法弄清楚我做错了什么。

第一次尝试:aggregate(chm, fact=20, fun=length, na.rm=T) # w/o na.rm=T

Error in FUN(X[[i]], ...) : 2 arguments passed to 'length' which requires 1

第二次尝试:

aggregate(chm, fact=20, fun=function(x){ length(x) } )

Error: [aggregate] this function does not return the correct number of values

应用上述根据本回复修改的最终函数的结果相同,如下:

function(x){ if(any(is.numeric(x))){length(na.omit(x))/length(x) * 100} else {NA_real_}}

terra 1.4.22在 W10 中和1.5.12在 W10 上进行的所有测试。

4

1 回答 1

0

示例数据

library(terra)
f <- system.file("ex/elev.tif", package="terra")
r <- rast(f)

您可以计算不NA使用简单聚合函数的单元格的百分比

a <- aggregate(!is.na(r), 2, mean) * 100 

或者,更高效

a <- aggregate(is.finite(r), 2, mean) * 100 

但这似乎也适用于您的功能

nofun <- function(x){ 100 * length(na.omit(x)) / length(x)}
b <- aggregate(r, 2, nofun)
plot(b, plg=list(title="NA (%)"))

在此处输入图像描述

通过添加na.rm=TRUE,您可以提供一个length它没有的附加参数。它只有一个论点x

于 2022-01-13T19:48:28.493 回答