Search code examples
rraster

Create many subsets of raster stacks from larger raster stack


Having a difficult time conceptualization this one. I currently have a netcdf file that contains monthly climate averages from 1979-2016. I would like to make separate yearly raster stacks from this larger one (i.e., go from 1 raster stack to 38). I cannot for the life of me figure this out. Any suggestions would be great! The data can be found here: http://nimbus.cos.uidaho.edu/abatz/DATA/vpd19792016.nc

What I have started so far is as follows:

  library(raster)
  library(lubridate)
  library(rgdal)
  library(tidyverse)
  library(tools)

  file = "../data/raw/climate/aet_19792016.nc" 
  file_split <- file %>%
    basename %>%
    strsplit(split = "_") %>%
    unlist
  var <- file_split[1]
  year <- substr(file_split[2], start = 1, stop = 4)
  endyear <- substr(file_split[2], start = 5, stop = 8)

  start_date <- as.Date(paste(year, "01", "01", sep = "-"))
  end_date <- as.Date(paste(ifelse(year == endyear, year, endyear), "12", "31", sep = "-"))
  date_seq <- seq(start_date, end_date, by = "1 month")
  month_seq <- month(date_seq)

  nc <- nc_open(file)
  nc_att <- attributes(nc$var)$names
  ncvar <- ncvar_get(nc, nc_att)
  tvar <- aperm(ncvar, c(3,2,1))
  proj <- "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0 "

  raster <- brick(tvar, crs= proj)
  extent(raster) <- c(-124.793, -67.043, 25.04186, 49.41686)
  names(raster) <- paste(var, year(date_seq),
                                     unique(month(date_seq, label = TRUE)),
                                     sep = "_")
  unstack(raster)

Thanks in advance for any suggestions!


Solution

  • First you have to properly name the raster stack based on Years and months:

    library(ncdf4)
    library(raster)
    
    nc <- nc_open(file)
    nc_att <- attributes(nc$var)$names
    ncvar <- ncvar_get(nc, nc_att)
    tvar <- aperm(ncvar, c(3,2,1))
    proj <- "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0 "
    r <- brick(tvar, crs= proj)
    extent(r) <- c(-124.793, -67.043, 25.04186, 49.41686)
    # name raster brick based on year and month
    dates <- format(seq(as.Date(paste(1979,'/1/1',sep='')), as.Date(paste(2016,'/12/31', sep="")), by='month'), '%Y%m')
    names(r) <- dates
    r_sub <- subset(r,  grep("X1982", names(r))) # subset based on year