I'm working with a raster stack of 300 SGS, sims
, and a raster layer, trend
. I'm trying to sum trend
to each of the raster layers in the stack. My end goal is to have a new raster stack of my simulations with the trend map so that I can then preform other operations.
what i was looking for would be something like:
sims1 <- sims + trend
so that each layer would be somewhat like this:
>names(sims1)
[1] "sim1+trend" "sim2+trend" "sim3+trend" "sim4+trend"...
list_sims <- list() # list to save sums
for (i in 1:nlayers(sims)) {
list_sims[[i]] <- sims[[i]] + trend
}
sims1 <- stack(list_sims)
Operations in R are typically vectorized with recycling of the short variables. Thus you can do
1:3 + 10
#[1] 11 12 13
The same applies to raster data.
Example data:
library(raster)
sims <- stack(system.file("external/rlogo.grd", package="raster"))
trend <- raster(sims)
values(trend) <- 1:ncell(trend)
Solution:
x <- sims + trend
names(x) <- paste0(names(sims), ".trend")
x
#class : RasterBrick
#dimensions : 77, 101, 7777, 3 (nrow, ncol, ncell, nlayers)
#resolution : 1, 1 (x, y)
#extent : 0, 101, 0, 77 (xmin, xmax, ymin, ymax)
#crs : +proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs
#source : memory
#names : red.trend, green.trend, blue.trend
#min values : 256, 256, 256
#max values : 8032, 8032, 8032
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.