r - 使用 XTS 根据不同月份将数据聚合到每年
问题描述
我正在使用时间序列数据集,并希望聚合不基于日历年的年度数据。因此,假设我想从 10 月到 9 月聚合为apply.yearly
. 我有一个从 12 月到 3 月工作的版本,但由于闰年它失败了。我正在使用endpoints
insidezoo
来完成这项工作。我想修改这个函数来支持闰年。
功能:
apply.wateryear <- function(x, FUN, wateryearmon = 10, on = 'days', ...) {
wateryearmon <- as.numeric(wateryearmon)
yearlyendpoints <- endpoints(x, 'years')
# Adjusting Water Year
FirstYear <- format(index(x[1]), '%Y')
FirstDayWY <- as.numeric(format(as.Date(paste(FirstYear, wateryearmon, '01', sep = '-')), '%j'))
LastDay <- as.numeric(format(as.Date(paste(FirstYear, '12', '31', sep = '-')), '%j'))
# Loosely supporting daily and monthly
if(on == 'days' | on == 'day') {
WYAdjust <- LastDay - FirstDayWY + 1
} else if (on == 'months' | on == 'month') {
WYAdjust <- 12 - wateryearmon + 1
} else stop('Unknown periods string (on)')
# Shifting yearly to Month
yearlyendpoints <- yearlyendpoints - WYAdjust
# If first value is negative, replace with a zero
if(yearlyendpoints[1] < 0) yearlyendpoints[1] <- 0
# Last Value should be last of the data
if(as.numeric(format(as.Date(index(x[tail(yearlyendpoints, n = 1)])), '%j')) - FirstDayWY < 0) yearlyendpoints <- c(yearlyendpoints[-length(yearlyendpoints)], length(x))
return(period.apply(x, yearlyendpoints, FUN, ...))
}
一个快速的示例使用是:
sampleData <- xts::xts(runif(2000), order.by = seq(from = as.Date('2020-10-01'), by = 'days', length.out = 2000))
apply.wateryear(sampleData, sum, 10)
但是,我还想扩展它以支持 2 月,这样apply.wateryear(sampleData, sum, 2)
就不会减少一天。
谢谢!
解决方案
推荐阅读
- bash - 在ubuntu上建立了大胆,无法启动它
- kubernetes - Kubernetes CPU 节流,CPU 使用率远低于请求/限制
- android - 使用 Google 进行 Firebase 身份验证
- python - 在没有 CoLab 的情况下在 Jupyter 中实现相当于 Google CoLab @param 标记
- python - 我应该包括什么来制作 boost.python 扩展?
- maven - 未找到 Maven 配置文件
- qt - 如何删除相邻选定行之间的空白?
- java - 在 FIPS 模式下禁用 HTTPS 证书验证
- rest - 缩写“REPRESENTATIONAL STATE TRANSFER”中“STATE TRANSFER”的几个误区
- aframe - 错误,相机锁定在移动轴上