[R-sig-Geo] Run focal function on a multi-layer raster

Loïc Dutrieux loic.dutrieux at wur.nl
Sat May 21 22:54:09 CEST 2016


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:
> I have a multi-layer raster, in this case a rasterbrick, on which I would like to apply a focal function on each layer, and get another rasterbrick as a result.
>
> I am trying to use calc, but apparently I am not assembling my function in the proper way:
>
> require(raster)
> r <- raster(ncol=50, nrow=50)
> r[]=1:ncell(r)
> b <- brick(r,r,r,r,r,r)
> b <- b * 1:6
>

multiFocal(b, w=matrix(1, 5, 5), mean)

Cheers,
Loïc

> myfocalfun <- function(x){
> b.f <- focal(x, w=matrix(1, 5, 5), mean)
> return(b.f)
> }
>
> b1 <- calc(b, myfocalfun)
>
> Error in .calcTest(x[1:5], fun, na.rm, forcefun, forceapply) :
> cannot use this function
>
> What am I missing here?
>   Greetings,
>   -- Thiago V. dos Santos
>
> PhD student
> Land and Atmospheric Science
> University of Minnesota
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>



More information about the R-sig-Geo mailing list