r - 使用指定日期和月份的每日值保存 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 文件在这里。
解决方案
为什么要这么做?似乎是一个坏主意,但你应该能够这样做:
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])
}
推荐阅读
- c - C:管道:如何正确使用管道传递动态 int 数组
- python - 尝试将我的文件推送到 heroku 时出现错误“git push heroku master ERROR”
- reactjs - 提交发布请求并在邮递员中工作时,仅在 reactjs 中出现 CORS 策略错误
- php - htaccess 重定向文件夹以防止直接访问
- python - 用管道填充某些列缺失值后,无法从数据框中删除
- vb.net - vb.net框架不使用webBrowser工具自动登录网站
- c# - 加密文件的密钥长度
- pybind11 - 带有需要与静态库链接的 C++ 的 pybind11
- python - 不允许对 tf.Tensor 进行迭代:此函数中禁用了 AutoGraph
- javascript - 如何创建一个以 div id 作为 case 参数的 switch/case 语句?