Skip to content
Prev 24422 / 29559 Next

Run focal function on a multi-layer raster

Hi Lo?c,

Thanks for the hint - it worked like a charm!
 Greetings,
 -- Thiago V. dos Santos

PhD student
Land and Atmospheric Science
University of Minnesota
On Saturday, May 21, 2016 3:54 PM, Lo?c Dutrieux <loic.dutrieux at wur.nl> wrote:
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

            
_______________________________________________
R-sig-Geo mailing list
R-sig-Geo at r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo