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@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


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

Reply via email to