首页 > 解决方案 > 使用 XTS 根据不同月份将数据聚合到每年

问题描述

我正在使用时间序列数据集,并希望聚合不基于日历年的年度数据。因此,假设我想从 10 月到 9 月聚合为apply.yearly. 我有一个从 12 月到 3 月工作的版本,但由于闰年它失败了。我正在使用endpointsinsidezoo来完成这项工作。我想修改这个函数来支持闰年。

功能:

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)就不会减少一天。

谢谢!

标签: rtime-seriesxts

解决方案


推荐阅读