我正在尝试建立一个R函数,通过基础R或其他各种包(即format(DATE,"%j")
)确定类似于“年度日”(DOY)功能的“水年”。水年可以从10月1日或5月1日开始,因此标准的DOY功能不起作用。
在这个post和这个webpage类似于“水年”评估的评估被执行。主要的垮台是如果你有连续的日期,顺序日指数将关闭,而不是真正的“水年”。有没有办法在不使用日期索引的情况下执行此操作?
以下是非常低效的第一步。有没有办法优化这个或以不同的方式做到不创建基于日的索引?
hydro.day=function(date,WY){
require(lubridate)
if(WY=="Fed"){jul.str=274};#"Federal" Water Year(WY) starts Oct 1
if(WY=="FL"){jul.str=121};#"State" Water Year(WY) starts May 1
doy.reg=data.frame(jul.day=c(seq(jul.str,365,1),
seq(1,jul.str-1,1)),hydro.day=seq(1,365,1))
doy.leap=data.frame(jul.day=c(seq(jul.str+1,366,1),
seq(1,jul.str,1)),hydro.day=seq(1,366,1))
hydro.day=data.frame()
for(i in 1:length(date)){
jul.day=as.numeric(format(date[i],"%j"))
leap=leap_year(date[i])
if(leap==F){tmp=merge(jul.day,doy.reg,by.x="x",by.y="jul.day")}
else{tmp=merge(jul.day,doy.leap,by.x="x",by.y="jul.day")}
hydro.day=rbind(hydro.day,tmp)
}
return(hydro.day$hydro.day)
}
任何帮助,将不胜感激。
这应该这样做:
library(lubridate)
hydro.day.new = function(x, start.month = 10L){
start.yr = year(x) - (month(x) < start.month)
start.date = make_date(start.yr, start.month, 1L)
as.integer(x - start.date + 1L)
}
测试出来:
set.seed(123)
x = as.Date(as.POSIXct(sample(5000,10)*60*60*24, origin = "2000-01-01", tz = "GMT"))
hydro.day.new(x)
# [1] 70 16 311 123 43 321 174 166 289 180
hydro.day(x, "Fed")
# [1] 70 16 311 123 43 321 174 166 289 180