Reputation: 2763
I am trying to write an efficient script to calibrate hundreds of Landsat 8 images. At a certain point of the calibration steps, I need to apply some coefficients in each layer of a raster stack.
This is one sample stack:
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)
What I need to is to apply each index of the coefficients to the correspondent index of the stack layer, like in this example:
s[[1]] <- (s[[1]] * mult[1]) + add[1]
s[[2]] <- (s[[2]] * mult[2]) + add[2]
This is my poor attempt, which obviously does not work:
cal.fun <- function(x) {
x <- (x * mult) + add
}
s.cal <- calc(s, cal.fun, progress='text')
Any ideas on how to do that?
Many thanks.
Upvotes: 1
Views: 562
Reputation: 162321
raster is a phenomenally well-constructed package and you can simply do:
s2 <- s * mult + add
For quick visual confirmation that that vectorized call "just works", do something like this:
library(gridExtra)
library(rasterVis)
grid.arrange(levelplot(s), levelplot(s2), nrow=2)
Upvotes: 2