目前我正在做一项河流流量数据分析。我有1935年到现在的每日出院记录。我想提取每个水文年的年最大流量(从01/11开始到明年31/10)。然而,我发现hydroTSM包只能处理自然年份。我试着使用“动物园”软件包,但我发现它很难计算,因为每年都有不同的日子。有人有什么想法吗?谢谢。
数据看上去如下:
01-11-1935 663
02-11-1935 596
03-11-1935 450
04-11-1935 381
05-11-1935 354
06-11-1935 312我的代码:
mydata<-read.table("discharge")
colnames(mydata) <- c("date","discharge")
library(zoo)
z<-zooreg(mydata[,2],start=as.Date("1935-11-1"))
mydta$date <- as.POSIXct(dat$date)
q.month<-daily2monthly(z,FUN=max,na.rm = TRUE,date.fmt = "%Y-%m-%d",out.fmt="numeric")
q.month.plain=coredata(q.month)
z.month<-zooreg(q.month.plain,start=1,frequency=12)发布于 2014-02-27 16:37:59
将日期存储在类Date的向量中,只需使用cut()和tapply(),如下所示:
## Example data
df <- data.frame(date = seq(as.Date("1935-01-01"), length = 100, by = "week"),
flow = (runif(n = 100, min = 0, max = 1000)))
## Use vector of November 1st dates to cut data into hydro-years
breaks <- seq(as.Date("1934-11-01"), length=4, by="year")
df$hydroYear <- cut(df$date, breaks, labels=1935:1937)
## Find the maximum flow in each hydro-year
with(df, tapply(flow, hydroYear, max))
# 1935 1936 1937
# 984.7327 951.0440 727.4210
## Note: whenever using `cut()`, I take care to double-check that
## I've got the cuts exactly right
cut(as.Date(c("1935-10-31", "1935-11-01")), breaks, labels=1935:1937)
# [1] 1935 1936
# Levels: 1935 1936 1937发布于 2014-02-27 19:27:27
这是一条可以做到这一点的单线。
首先将日期转换为"yearmon"类。该类将一年的月份表示为整数部分,而月份表示为小数部分(Jan = 0,Feb = 1/12等)。加上2/12,将11月移至1月,然后截断,只给出年数。聚集在这些之上。尽管我们使用的测试数据是在水电年开始时开始的,但即使数据不是在水电年开始时就开始使用,这个解决方案仍然有效。
# test data
library(zoo)
z <- zooreg(1:1000, as.Date("2000-11-01")) # test input
aggregate(z, as.integer(as.yearmon(time(z)) + 2/12), max)这意味着:
2001 2002 2003
365 730 1000 发布于 2014-02-27 16:27:27
尝试xts包,它与zoo一起工作
require(zoo)
require(xts)
dates = seq(Sys.Date(), by = 'day', length = 365 * 3)
y = cumsum(rnorm(365 * 3))
serie = zoo(y, dates)
# if you need to specify `start` and `end`
# serie = window(serie, start = "2015-06-01")
# xts function
apply.yearly(serie, FUN = max)https://stackoverflow.com/questions/22073881
复制相似问题