[R-sig-Geo] raster overlay: apply function on multiple RasterBrick
Vijay Lulla
vijaylulla at gmail.com
Wed Jul 20 17:17:13 CEST 2016
I'm not sure that this is the best way but I think this does what you want.
R> b1 <- brick(ncol=10,nrow=10,nl=15)
R> b1[] <- rnorm(length(b1),3,2)
R> b2 <- b1*b2
R> b3 <- stack(b1,b2)
R> fun3 <- function(x) { lm(x[16:30] ~ x[1:15])$coefficients[[2]] }
R> out3 <- calc(b3, fun3)
This is similar to one of the examples under ?`calc`.
HTH,
Vijay
On Wed, Jul 20, 2016 at 6:13 AM, Loïc Dutrieux <loic.dutrieux at wur.nl> wrote:
> 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
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
[[alternative HTML version deleted]]
More information about the R-sig-Geo
mailing list