Aggregate raster in R with NA values

≡放荡痞女 提交于 2019-12-11 02:25:22

问题


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.

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"))
}

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)

But this returns a raster layer with a value ONLY at aggregated locations where every cell of the 5x5 window contains a value.


回答1:


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)) 
  }
}

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.



来源:https://stackoverflow.com/questions/23369579/aggregate-raster-in-r-with-na-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!