我有一个栅格路径列表(rplist
= 912个栅格(19yeras)的912个栅格路径((12months)(4weeks))如下:
[1] "C:/Users/Eric/Downloads/Results/RMI_2000_02_18.tif"
[2] "C:/Users/Eric/Downloads/Results/RMI_2000_02_26.tif"
[3] "C:/Users/Eric/Downloads/Results/RMI_2000_03_05.tif"
[4] "C:/Users/Eric/Downloads/Results/RMI_2000_03_13.tif"
[5] "C:/Users/Eric/Downloads/Results/RMI_2000_03_21.tif"
[...] "......"
[912] "C:/Users/Eric/Downloads/Results/RMI_2019_03_21.tif"
我需要每年逐月读取栅格组(例如,属于RMI_2000_02的栅格),然后提取每个覆盖像元的最小值作为单独的栅格(忽略NA值,如果有的话)。
################### SETTING UP WORKING DIRECTORY ############################
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
# list rasters in workin directory
rplist <- list.files(getwd(),full.names = TRUE)
从这里开始,我不知道如何处理rs(如上所述),但是应该:
1. read rasters using rplist
2. group them by month for each year
3. extract the min raster
答案 0 :(得分:2)
一种方法如下:
# list rasters in workin directory
rplist <- list.files(getwd(),full.names = TRUE)
r_name <- list.files(getwd(),full.names = FALSE)
# 1. read rasters using rplist
mrlist <- lapply(rplist, raster)
names(mrlist) <- r_name
# 2. stack rasters of the same month
tstList <- list()
tstStack <- stack()
i <- 1
for (y in 2000:2019){
for (m in 1:12){
# paste0(y,"_",sprintf("%02d", m)) returnes YEAR_MONTH
tstStack <- stack(mrlist[grep(paste0(y,"_",sprintf("%02d", m)), names(mrlist))] )
tstList[[i]] <- tstStack
i <- i+1
}
}
#3. extract the min raster(s)
min.rlist <- list()
for (i in 1:length(tstList)) {
min.rlist[[i]] <- min(tstList[[i]])
print(i) # to track the process
}
答案 1 :(得分:2)
要获得一个好的答案,您应该提供一些示例数据(不是外部文件,请使用R附带的数据,或使用代码创建一些数据)。您可以做的是创建一个RasterStack s
和一个向量v
,将需要组合的图层分组,然后执行
x <- stackApply(s, v, fun=min, na.rm=TRUE)
现在有示例数据
library(raster)
# RasterStack with 12 layers
s <- stack(system.file("external/rlogo.grd", package="raster"))
s <- stack(s, s*2, s*3, s*4)
# make one layer with only NAs
values(s[[2]]) <- NA
# 12 corresponding dates
d <- paste0("RMI_2000", rep(sprintf("_%02d", 1:3), each=4), "_0", 1:4)
d
# [1] "RMI_2000_01_01" "RMI_2000_01_02" "RMI_2000_01_03" "RMI_2000_01_04" "RMI_2000_02_01" "RMI_2000_02_02" "RMI_2000_02_03" "RMI_2000_02_04" "RMI_2000_03_01" "RMI_2000_03_02" "RMI_2000_03_03" "RMI_2000_03_04"
# transform date into an index (stripping of the label and the week number)
i <- substr(d, 4, 11)
i
#[1] "2000_01" "2000_01" "2000_01" "2000_01" "2000_02" "2000_02" "2000_02" "2000_02" "2000_03" "2000_03" "2000_03" "2000_03"
ss <- stackApply(s, i, min, na.rm=TRUE)
ss
#class : RasterBrick
#dimensions : 77, 101, 7777, 3 (nrow, ncol, ncell, nlayers)
#resolution : 1, 1 (x, y)
#extent : 0, 101, 0, 77 (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=merc +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
#data source : in memory
#names : index_2000_01, index_2000_02, index_2000_03
#min values : 0, 0, 0
#max values : 255, 510, 765