I want to modify a subset of layers in a raster brick by multiplying those layers by another raster.
For example, if we have a raster brick called 'r.brick' and we try to multiply its layers 2:4 by a raster, 'r.mult', with same row&column dimensions:
r.brick[[2:4]]returns layers 2:4, as expectedr.brick[[2:4]] * r.multsuccessfully multiplies those layers, as expected
but, if I try to assign the result back into the subset layers I get an error
r.brick[[2:4]] = r.brick[[2:4]] * r.mult
# Error in value[] <- val :
# incompatible types (from S4 to double) in subassignment type fix
The error message suggests that the assignment is trying to assign the raster values rather than the raster itself. But if I try the assignment with getValues, I get a different error:
r.brick[[2:4]] = getValues(r.brick[[2:4]] * r.mult)
# Error in .local(x, values, ...) : length(values) is not equal to ncell(x)
What is the correct way to do this?
Some reproducible data:
library(raster)
r.list = vector("list", 20)
set.seed(123)
for (i in 1:20) {
r.list[[i]] = raster(vals=runif(100), nrows=10, ncols=10, ext=extent(c(0,25,0,25)))
}
r.brick = brick(r.list)
r.mult = raster(vals=sample(2,100,T), nrows=10, ncols=10, ext=extent(c(0,25,0,25)))