[R-sig-Geo] raster overlay: apply function on multiple RasterBrick

Loïc Dutrieux loic.dutrieux at wur.nl
Wed Jul 20 12:13:26 CEST 2016


Hi everyone,

I'm struggling to apply a function on multiple RasterBrick with 
raster::overlay.
In the dummy example below the idea is that the function takes two 
numeric vectors and returns the slope of the linear model. Therefore I 
would expect to have a RasterLayer in return with slope for each pixel.
Overlay complains that the function is not vectorized.
I tried to wrap fun in a mapply call to vectorize the function over x 
and y but that did not work either.
Any ideas?

####
library(raster)

b1 <- brick(ncol=10, nrow=10, nl=15)
b1[] <- rnorm(length(b1), 3, 2)
b2 <- b1 * b1

# Define function to compute slope
fun <- function(x, y) {
   model <- lm(y ~ x)
   model$coefficients[[2]]
}

# Test function for two numeric vectors of same length
fun(c(1,2,3,4), c(4,2,6,7))

# Use function within overlay
out <- overlay(b1, b2, fun = fun2)


Cheers,
Loïc



More information about the R-sig-Geo mailing list