Search code examples
rdatetime-seriessubsetraster

R Raster stack subset by date


I am trying to subset a monthly raster time-series according to a specific time period, in this case I want just the rasters from October of the year 'n' to Feb of the year 'n+1' (means Oct,Nov,Dec,Jan,Feb). Then I will analyse these subsets : eg: in the case below I should get 3 subsets (Oct00 to Feb01, Oct01 to Feb02, Oct02 to Feb03) that need to be compared.

I am running the code below but it does not work. I get also the months that do not be considered in my analysis (May to Sep)

library(raster)
library(lubridate)

# create stack
r <- raster(ncol=10, nrow=10)
r <- stack(lapply(1:48, function(i) setValues(r, runif(100, -0, 1000))))

# add time dimension and names
date <- seq(as.Date('2000-01-01'),as.Date('2003-12-01'), 'months')
r <- setZ(r, date)
names(r)<-date
r

# time subsetting
sub <- subset(r, which(getZ(r) >= '2000-10-01' & (getZ(r) <= '2003-02-01')))
sub

can you help please? thanks i


Solution

  • Your current code subsets all rasters from 2000-10-01 to 2003-02-01. Depending on your needs you could subset each Oct to Feb time-series individually:

    sub1 <- subset(r, which(getZ(r) >= '2000-10-01' & (getZ(r) <= '2001-02-01')))
    sub2 <- subset(r, which(getZ(r) >= '2001-10-01' & (getZ(r) <= '2002-02-01')))
    sub3 <- subset(r, which(getZ(r) >= '2002-10-01' & (getZ(r) <= '2003-02-01')))
    

    Or subset Oct to Feb for all years:

    require(stringr)
    ##subset all months that fall between Oct to Feb
    sub <- subset(r, which(substr(getZ(r),6,7)%in%c(10,11,12,01,02)))