gis - Cumulative sum of multiple rasters in R -
i have 200 rasters air temperatures each day stored in directory , cumulative sum of temperatures each day, e.g. day1 = day1; day2 = day1 + day2; day3 = day1 + day2 + day3, etc. tried in raster package, cumsum function calculates cumulative sum of cells in each raster , not cumulative sum of individual rasters (at to the lowest degree seems me results). tried this:
library(raster) setwd("c:/air_temperatures/at") # set working directory at.files <- list.files(pattern="at") # list files name @ all.at <- unique(at.files) # unique files (i in 1:200) { at.i <- all.at[i] # create at.raster.i<-raster(at.i) # create rasters files at.sum.i <- cumsum(at.raster.i) # ???calculate cumulative sum??? writeraster(at.sum.i, paste(at.i, "_cumsum.tif", sep = ""), datatype='flt4s', overwrite=true) # write new files , paste new name } this loop worked when tried illustration add together constant each raster , on, have no thought how calculate cumulative sum.
the reduce function might help here. function successively combines objects based on specified function. since there + method raster* objects, can utilize function , obtain cumulative sum of raster values.
first, create 200 raster objects in list:
theats <- lapply(all.at, raster) then, utilize reduce function accumulate argument set true
res <- reduce("+", theats, accumulate = true) then write results files:
lapply(seq_along(res), function(x) { writeraster(res[[x]], # apparently, using .tif files threw error # paste(all.at[x], "_cumsum.tif", sep = ""), # alternatively, omit file extension write default type (usually .grd) paste(all.at[x], "_cumsum", sep = ""), datatype = 'flt4s', overwrite = true) }) the rasters create here stored in memory, if original files large, may run problems.
r gis raster
No comments:
Post a Comment