问题描述
我在R中有一个1 km分辨率的栅格,整个栅格中都有广泛的NA值,但是在不规则的位置(即,具有数据的像元不是连续的,并且NA值始终散布在整个栅格中).我正在尝试使用用户定义的函数(例如,包括在下面)中的用户定义函数,以5km的分辨率(因数= 5)聚合该栅格(在{raster}包中使用gregation()命令).到目前为止,除非栅格具有连续的5x5像元区域,否则我无法弄清楚如何获取aggregate()(或函数,如果有问题的话)以提供结果值.换句话说,在聚合窗口仅具有5个具有数据值的单元格(20个NA单元格)命中5x5单元格区域的情况下,我仍然希望它返回这2个单元格的平均值.我试过修改函数和aggregate()命令的na.action选项,但是没有运气.我对功能不是很熟练,所以问题可能出在这里.
I have a 1km resolution raster in R with widespread NA values throughout, but at irregular locations (i.e. the cells with data are not contiguous and have NA values scattered throughout). I am trying to aggregate this raster (using aggregate() command in the {raster} package) at, say, 5km resolution (factor=5) with a user-defined function for averaging circular angles (included below). As of now, I can't figure how to get aggregate() (or my function, if that's the problem) to provide a result value unless the raster has a contiguous 5x5 cell area. In other words, where the aggregate window hits a 5x5 cell area with only, say, 5 cells with data values (20 NA cells), I still want it to return an average value for those 2 cells. I've tried modifying the na.action options of both the function and the aggregate() command, with no luck. I'm not super experienced with functions, so the problem may be in there.
很抱歉,没有可用的示例,但不确定如何在R中生成类似的示例栅格图层.
Sorry for no working example, but not sure how to generate a similar example raster layer within R.
这是我的循环平均函数:
Here's my circular average function:
library(circular)
avg.ang <- function(x,...){
mean.circular(circular(x, units="degrees", rotation="clock", zero=pi/2, modulo="2pi"))
}
这是我正在使用的汇总代码(其中角度"是1公里的栅格,NA值分散在整个栅格中):
And here's the aggregate code I'm using (where 'angle' is a 1km raster with NA values scattered throughout):
library(raster)
angle5k <- aggregate(angle, fact=5, fun=avg.ang, expand=T)
但这仅在5x5窗口的每个像元包含一个值的聚合位置返回一个具有值的栅格图层.
But this returns a raster layer with a value ONLY at aggregated locations where every cell of the 5x5 window contains a value.
推荐答案
感谢乔希的指导.这是修改后的函数,可以产生我想要的东西:
Thanks Josh for the guidance. Here's the modified function that produces what I'm looking for:
avg.ang <- function(x, ...){
if (sum(is.na(x))==length(x)) {
NA
} else {
round(mean.circular(circular(x, units="degrees", rotation="clock",
zero=pi/2, modulo="2pi"), na.rm=TRUE))
}
}
na.rm=TRUE
是键. if/else语句用于处理所有像元都为NA(否则会因错误而中断)的情况.如果有人能以一种更优雅的方式来处理if/else,那么我无不为之倾心.
The na.rm=TRUE
is the key. The if/else statement is to deal with occurrences where all cells=NA (otherwise breaks with an error). If anyone has a more elegant way to deal with the if/else, I'm all ears.
这篇关于以NA值汇总R中的栅格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!