Skip to content
Prev 22284 / 29559 Next

How to apply this function on each raster stack layer?

Hi Thiago,

The approach you took seems correct. See example below.

library(raster)
fn <- system.file("external/test.grd", package="raster")
s  <- stack(fn, fn)

# And these are sample coefficients:
mult <- c(0.0003342, 0.0005534) 
add  <- c(0.1, 0.2) 

# define calc function
fun <- function(x) {
    y <- x * mult + add
    return(y)
}

out <- calc(x = s, fun = fun)

# For each band individually
s2 <- s
s2[[1]] <- (s2[[1]] * mult[1]) + add[1]
s2[[2]] <- (s2[[2]] * mult[2]) + add[2]

all.equal(out, s2)


Best regards,
---
Lo?c Dutrieux
PhD student
Laboratory of Geo Information Science and Remote Sensing
Wageningen University
The Netherlands