首页 > 解决方案 > 使用指定日期和月份的每日值保存 rasterLayers

问题描述

我有一个 1986 年每日积雪深度值的 tiff。这个 tiff 有 365rasterLayers个代表一年中的每一天。我需要提取每个rasterLayer并按月和日保存。例如:

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

最后一个文件是 snow_19861231.tif

我能够保存一月份的值,但我不明白如何在所有月份中循环。我创建了一个包含每个月所有天数的表格,并累积了每月的值,希望它能帮助我完成几个月的循环。

   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)
}

tiff 文件在这里

标签: rloopsraster

解决方案


为什么要这么做?似乎是一个坏主意,但你应该能够这样做:

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])
}

推荐阅读