我有一个由12层组成的栅格砖,每层代表给定月份的平均温度(第1层= 1月,第2层= 2月等)。我想要做的就是计算一些简单的统计数据,例如平均值和标准偏差。这是一个问题:我只想计算与小麦作物季节持续时间相对应的月份的这些统计数据,并删除所有其他单元格值(即将它们更改为NA)。我有一个小麦种植日期rasterLayer和一个小麦收获日期rasterLayer(这两个光栅层的细胞值再次代表小麦种植和收获的一年中的月份)。
我已经通过以下代码成功实现了这一目标,但只有当小麦种植的时间早于收获时(即作物不跨越两年,例如 - 种植于2015年11月(11日)并收获2016年4月(4))。
种植RasterLayer https://www.dropbox.com/s/d5i8kdfxl2hzulc/WPlantingCropped.gri?dl=0
Harvest RasterLayer https://www.dropbox.com/s/idqys2djbgjv4yr/WHarvestCropped.gri?dl=0
最低温度RasterBrick https://www.dropbox.com/s/7pf5oe5rjcaqdqt/TminCropped.gri?dl=0
Harvest<-raster("WHarvestCropped")
Planting<-raster("WPlantingCropped")
TminCropped<-raster("TminCropped)
#Split dataset into two: Separate those cells in which wheat is planted earlier than
#its harvest date from those in which wheat is planted later than its harvest date
Separate<-overlay(Planting,Harvest, fun=function (x,y) {return(x-y)},filename="Separate")
Earlier<-function(x){
ifelse(x<0,1,
ifelse(x>=0,NA,NA))}
EarlierPH<-calc(Separate,Earlier, filename="EarlierPH")
#Make Planting dataset consisting of only those cells in which wheat is planted earlier than harvest
EarlierPlant<-overlay(EarlierPH,Planting,fun=function (x,y) {return(x*y)},
filename="EarlierPlant",overwrite=T,na.rm=T)
#Make Harvest dataset consisting of only those cells in which wheat is planted later than harvest
EarlierHarvest<-overlay(EarlierPH,Harvest, fun=function (x,y){return(x*y)},
filename="EarlierHarvest",overwrite=T,na.rm=T)
#Expand planting and harvest rasterLayers into RasterBricks
Expand <- function(p) {
x <- matrix(0, nrow=length(p), ncol=12)
x[cbind(1:nrow(x), p)] <- 1
x <- t(apply(x, 1, cumsum))
x[x==0] <- 0
x
}
EarlyPlantingBrick<-calc(EarlierPlant,Expand,filename="EarlyPlantingBrick",overwrite=T)
EarlyHarvestBrick <- calc(EarlierHarvest, Expand, filename="EarlyHarvestBrick",overwrite=T)
EarlyPHJoin<-overlay(EarlyPlantingBrick,EarlyHarvestBrick,
fun=function(x,y){return(x+y)}, filename="EarlyPHJoin",overwrite=T)
#Final cropping calendar template
i <- function(f) {
x<-f
x[x==2]<-0
return(x)
}
EarlyBrickTemplate<-calc(EarlyPHJoin, i, filename="EarlyBrickTemplate",overwrite=T)
#Final Cropping Calendar for cells in which wheat was planted earlier than harvest
EarlyBrick <-overlay(EarlyBrickTemplate,TminCropped,
fun=function(x,y){return(x*y)}, filename="EarlyBrick”,overwrite=T)
同样,上述代码适用于小麦播种日期早于收获日期(即小麦在一年内种植和收获)的细胞,但不适用于小麦播种日期早于其收获的月份日期(例如,2015年11月种植,2016年4月收获)。我怎么能这样做?