【发布时间】:2021-06-08 21:28:58
【问题描述】:
我想为列表中的每一年数据(长达 30 年)定位每日温度低于 0 度的第一个和最后一个日期,并返回事件发生的儒略日(Day Of Year)对于网格中的每个单元格。
这是我的示例数据集: 我的列表中有 30 年的每日最低温度数据:
#First create the example dataset of dimensions: Days,Lat,Lon
tmin=array(-2:35, c(10958,11,10))
#create the list
Variable <- list(varName="tmin")
Data = tmin
xyCoords <- list(x = seq(-4.37,1.37,length.out=10), y = seq(45.37,52.37,length.out=11))
Dates <- list(start = seq(as.Date("1976-01-01"), as.Date("2005-12-31"), by="days"), end=seq(as.Date("1976-01-01"), as.Date("2005-12-31"), by="days"))
All <- list(Variable = Variable,Data=Data, xyCoords=xyCoords,Dates=Dates)
#Make sure the dates are characters (as in the original dataset I'm, working with)
All$Dates$start=as.character(All$Dates$start)
All$Dates$end=as.character(All$Dates$end)
我希望按年份对数据进行子集化(例如,第 1 年的数据将是 1:365x11x10)以评估该年每一天的 11X10 网格中的每个单元格是否小于零。发生这种情况的第一个实例是“第一次霜冻的日期”,我想保存发生这种情况的日期。最终,我会在第一个发生日期得到大小为 30x11x10 的数据,第一年看起来像这样(当温度第一次降至零以下时,DOY 的 11 x 10 矩阵):
我还想为最后一次低于零的温度创建另一个 30x11x10 日期输出。
首先,我创造了我的儒略时代/DOY:
#Convert the dates into julian days
require(lubridate)
tmp<-as.Date(All$Dates$start)
doy <- yday(tmp)
并提取年份:
yr <- year(tmp)
unique.yrs<-unique(yr)
我在这之后的想法是循环匹配所有 unique.yrs[i] 实例的日期。
for (i in 1:length(yr)){
#Find the indices for the data by identifying the year
yridx<-which(yr ==unique.yrs[i], arr.ind = TRUE)
#Get the year of data using the year indices
yr.data<-All$Data[yridx,,]
#Identify where temperatures<0 occurred
frost<-which(yr.data <0, arr.ind = TRUE)
}
我不知道从这里去哪里。我想如果我能得到每年网格中每个单元格的所有霜冻发生情况,那么也许我可以使用head 来获取第一个实例并使用tail 来获取最后一个实例?所以也许我应该在一个循环中再次设置子集?
我意识到我在这里没有提供完整的代码集,但对 R 来说相对较新,我需要知道我是否以错误的方式处理这一切。我提议的前进路线是否过于复杂?有没有更好的办法?
############################################## ################################################# ################################################# ####### #这是我想出的……它并不优雅,但我认为它有效:
firstoccur=array(numeric(),c(30,11,10))
lastoccur=array(numeric(),c(30,11,10))
yrcntr<-0
for (j in unique.yrs) {
indcntr<-0
yrcntr<-yrcntr+1
ind=which(yr==j)
for (i in ind) {
indcntr<-indcntr+1
for (ii in 1:11){
for (jj in 1:10){
if (Data[i,ii,jj]<0 && is.na(firstoccur[yrcntr,ii,jj])){
firstoccur[yrcntr,ii,jj]<-doy[ind[indcntr]]
}
}
}
}
}
【问题讨论】: