Raster Stack nlayers in R

I am working with daily observations of climate data organized in .nc files. I read them using the bitmap package stack command. Each file (corresponding to a year) is a RasterStack with the following characteristics:

class       : RasterStack 
dimensions  : 360, 720, 259200, 365  (nrow, ncol, ncell, nlayers)
resolution  : 0.5, 0.5  (x, y)
extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax) 

      

each layer is a raster of day values.
I would like to sum the layers in order to calculate monthly values. I believe the solution is to use calc or stackApply {raster}, but I couldn't find a way to sum from layer x to layer y or a way to subset RasterStack before summing.

I've prepared a sample file with only 12 layers (to reduce the size).

I don't know exactly how to suggest the code, sorry, but it should be something like:

library(raster)
setwd("myfolder")
data<-stack(mydata.nc)

datasum<- stackApply(data, ??? ,fun=sum)

      

thank

+3


source to share


1 answer


You can use stackApply

for this. Using your example data, it looks like the name of each raster layer is date. You can use this to build the indexes you need to pass to stackApply

.

Index list should have 31 1 for January days, etc.

You can do:



    #get the date from the names of the layers and extract the month
    indices <- format(as.Date(names(data), format = "X%Y.%m.%d"), format = "%m")
    indices <- as.numeric(indices)

    #sum the layers
    datasum<- stackApply(data, indices, fun = sum)

      

The result will be a 12-layer raster stack.

To get a subset of the raster layers off the stack, you can do data[[c(1,2]]

+4


source







All Articles