使用自定义函数聚合栅格失败
aggregate raster with custom function fails
我正在使用 terra
包中的 aggregate
进行非常基本的聚合操作。主要思想是使用以下函数计算具有值的像素占整数的百分比:
nofun = function(x){ length(na.omit(x))/length(x) * 100 }
不幸的是,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
将上述最终函数根据this reply修改后的结果相同,如下:
function(x){ if(any(is.numeric(x))){length(na.omit(x))/length(x) * 100} else {NA_real_}}
W10 上 terra
1.4.22
和 1.5.12
中的所有测试。
示例数据
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
.
我正在使用 terra
包中的 aggregate
进行非常基本的聚合操作。主要思想是使用以下函数计算具有值的像素占整数的百分比:
nofun = function(x){ length(na.omit(x))/length(x) * 100 }
不幸的是,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
将上述最终函数根据this reply修改后的结果相同,如下:
function(x){ if(any(is.numeric(x))){length(na.omit(x))/length(x) * 100} else {NA_real_}}
W10 上 terra
1.4.22
和 1.5.12
中的所有测试。
示例数据
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
.