Skip to content
Prev 24421 / 29559 Next

Run focal function on a multi-layer raster

Hi Thiago,

calc is not aware of neighbouring pixels in the x,y dimensions, so 
functions like focal cannot work.

I found the function below in an old repos of mine. It still seems to 
work fine :)

#' Focal for RasterBrick or RasterStack
#'
#' @param x RasterBrick/Stack or character pointing to multilayer raster 
object written on disk
#' @param w See \code{\link{focal}}
#' @param ... Arguments to be passed to \code{\link{focal}}
#'
#' @import raster
#' @export
#'

multiFocal <- function(x, w=matrix(1, nr=3, nc=3), ...) {

   if(is.character(x)) {
     x <- brick(x)
   }
   # The function to be applied to each individual layer
   fun <- function(ind, x, w, ...){
     focal(x[[ind]], w=w, ...)
   }

   n <- seq(nlayers(x))
   list <- lapply(X=n, FUN=fun, x=x, w=w, ...)

   out <- stack(list)
   return(out)
}
On 05/21/2016 10:02 PM, Thiago V. dos Santos via R-sig-Geo wrote:
multiFocal(b, w=matrix(1, 5, 5), mean)

Cheers,
Lo?c