从一年到下一年过滤 xts 对象

问题描述 投票:0回答:1

如果我有一个 10 年的每日 xts 时间序列,从 1985 年 1 月 1 日开始,到 1994 年 12 月 31 日结束,我如何计算从 11 月 1 日开始到 3 月 31 日结束的区间值的总和明年,整个系列?

dates <- seq(from = as.Date("1985-01-01"), to = as.Date("1994-12-31"), by = 1)
data <- rnorm(length(dates))
my.ts <- xts(x=data, order.by=dates)

my.ts2 <- sum( my.ts['year1-11-01/year2-03-31'] )  where year2 = year1+1
r time-series xts
1个回答
0
投票

此数据按连续组进行汇总,分别于 11 月 1 日和 3 月 31 日分开。 结果的第一行是不完整的“in”组,然后是“out”组,然后是“in”,依此类推。

library(xts)

set.seed(1)
dates <- seq(from = as.Date("1985-01-01"), to = as.Date("1994-12-31"), by = 1)
data <- round(rnorm(length(dates)), 2)
my.ts <- xts(x=data, order.by=dates)

d <- as.POSIXlt(index(my.ts))
nov1 <- d$mon == 10 & d$mday == 1
mar31 <- d$mon == 2 & d$mday == 31
id <- cumsum(nov1+mar31)

cbind(
  range=aggregate(index(my.ts), list(id), function(x) as.character(range(x))),
  sum=aggregate(my.ts, id, sum)
)
#    range.Group.1  range.x.1  range.x.2    sum
# 0              0 1985-01-01 1985-03-30   9.50
# 1              1 1985-03-31 1985-10-31   2.03
# 2              2 1985-11-01 1986-03-30  -4.31
# 3              3 1986-03-31 1986-10-31 -13.89
# 4              4 1986-11-01 1987-03-30 -11.03
# 5              5 1987-03-31 1987-10-31  -1.88
# 6              6 1987-11-01 1988-03-30  -7.92
# 7              7 1988-03-31 1988-10-31   6.59
# 8              8 1988-11-01 1989-03-30   9.60
# 9              9 1989-03-31 1989-10-31  -9.92
# 10            10 1989-11-01 1990-03-30  -4.51
# 11            11 1990-03-31 1990-10-31 -10.80
# 12            12 1990-11-01 1991-03-30  -6.07
# 13            13 1991-03-31 1991-10-31  23.11
# 14            14 1991-11-01 1992-03-30 -18.69
# 15            15 1992-03-31 1992-10-31  12.52
# 16            16 1992-11-01 1993-03-30  19.60
# 17            17 1993-03-31 1993-10-31  23.78
# 18            18 1993-11-01 1994-03-30  15.74
# 19            19 1994-03-31 1994-10-31   0.91
# 20            20 1994-11-01 1994-12-31  -5.76
© www.soinside.com 2019 - 2024. All rights reserved.