Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top