Search code examples
rloopsraster

Save rasterLayers with daily values specifying day and month


I have a tiff with daily snow depth values in 1986. This tiff has 365 rasterLayers representing each day of the year. I need to extract each rasterLayer and save it by month and day. For example:

    snow_19860101.tif
    snow_19860102.tif
    snow_19860103.tif
    snow_19860104.tif
    …
    snow_19860201.tif
    snow_19860202.tif
    snow_19860203.tif
    snow_19860204.tif
    …

The last file would be snow_19861231.tif

I was able to save the January values but I don’t understand how I can make a loop through all months. I created a table with all days in each month and accumulated monthly values hoping that it would help me doing the loop through months.

   Year Month DaysInMonth DaysInMonthAcc
1  1986     1          31             31
2  1986     2          28             59
3  1986     3          31             90
4  1986     4          30            120
5  1986     5          31            151
6  1986     6          30            181
7  1986     7          31            212
8  1986     8          31            243
9  1986     9          30            273
10 1986    10          31            304
11 1986    11          30            334
12 1986    12          31            365

#load raster and unstack
snowraster <- stack("Y:/Downloads/10km_daily_snow_1961_2018_geotiff/snow_1986.tif")
unstacked <- unstack(snowraster)

#helper table with months and accumulated days per month 
daysInMonth1986 <- as.numeric(diff(seq(as.Date("1986-01-01"), as.Date("1987-01-01"), by = "month")))
yearTable <- data.frame("Year" = "1986", "Month" = seq(1,12), "DaysInMonth" = daysInMonth1986, "DaysInMonthAcc" = cumsum(daysInMonth1986))

#get the number of days in first month
DaysInMonthAcc <- yearTable[1:12,"DaysInMonthAcc"]
daysinmonth <- seq(1, DaysInMonthAcc[1])

#write the first month
for (i in daysinmonth){
  snow1986 <- unstacked[[i]]
  snow1986filename <- paste0("Y:/Downloads/test/", "snow_198601",sprintf("%02d", i),".tif")
  #print(snow1986filename)
  writeRaster(snow1986, snow1986filename)
}

The tiff file is here.


Solution

  • Why would you do that? Seems like a bad idea, but you should be able to do it like this:

    inpath <- "Y:/Downloads/10km_daily_snow_1961_2018_geotiff/"
    outpath <- "Y:/Downloads/test/"
    
    year <- 1986
    dates <- seq(as.Date(paste0(year, "-01-01")), as.Date(paste0(year, "-12-31")), 1)
    dates <- gsub("-", "", as.character(dates))
    fnames <- file.path(outpath, paste0("snow_", dates, ".tif"))
    
    snow <- brick(file.path(inpath, paste0("snow_", year, ".tif")))
    
    #check: length(fnames) == nlayers(snow)
    
    for (i in 1:length(fnames)) {
        writeRaster(snow[[i]], filename=fnames[i])
    }