R:时间序列每月最大按组调整

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

我有一个这样的df(头):

        date  Value
1: 2016-12-31 169361280
2: 2017-01-01 169383153
3: 2017-01-02 169494585
4: 2017-01-03 167106852
5: 2017-01-04 166750164
6: 2017-01-05 164086438

我想计算一个比率,因此我需要每个时期的最大值。最大值通常是一个月的最后一天,但有时可能是几天后(28,29,30,31,01,02)。

为了正确计算,我想将我的参考日期(当月的最后一天)分配给这一组天的最大值,以确保该比率反映了它的用途。

这可能是一个可重复的例子:

Start<-as.Date("2016-12-31")
End<-Sys.Date()
window<-data.table(seq(Start,End,by='1 day'))
dt<-cbind(window,rep(rnorm(nrow(window))))
colnames(dt)<-c("date","value")

# Create a Dateseq

DateSeq <- function(st, en, freq) {
st <- as.Date(as.yearmon(st)) 
en <- as.Date(as.yearmon(en)) 
as.Date(as.yearmon(seq(st, en, by = paste(as.character(12/freq), 
"months"))), frac = 1)
}

# df to be fulfilled with the group max.

Value.Max.Month<-data.frame(DateSeq(Start,End,12))

colnames(Value.Max.Month)<-c("date")

         date
1  2016-12-31
2  2017-01-31
3  2017-02-28
4  2017-03-31
5  2017-04-30
6  2017-05-31
7  2017-06-30
8  2017-07-31
9  2017-08-31
10 2017-09-30
11 2017-10-31
12 2017-11-30
13 2017-12-31
14 2018-01-31
15 2018-02-28
16 2018-03-31
r time-series max
1个回答
0
投票

你可以使用data.table

library(lubridate)
library(zoo)
Start  <- as.Date("2016-12-31")
End    <- Sys.Date()
window <- data.table(seq(Start,End,by='1 day'))
dt     <- cbind(window,rep(rnorm(nrow(window))))

colnames(dt) <- c("date","value")
dt <- data.table(dt)

dt[,period := as.Date(as.yearmon(date)) %m+% months(1) - 1,][, maximum:=max(value), by=period][, unique(maximum), by=period]

在第一个表达式中,我们创建了一个名为period的新列。然后我们按这个新列进行分组,并在value中查找最大值。在最后一个表达式中,我们只输出这些唯一的行。

请注意,为了获得每个时期的最后一天,我们使用lubridate添加一个月,然后减去1天。输出是:

       period         V1
 1: 2016-12-31 -0.7832116
 2: 2017-01-31  2.1988660
 3: 2017-02-28  1.6644812
 4: 2017-03-31  1.2464980
 5: 2017-04-30  2.8268820
 6: 2017-05-31  1.7963104
 7: 2017-06-30  1.3612476
 8: 2017-07-31  1.7325457
 9: 2017-08-31  2.7503439
10: 2017-09-30  2.4369036
11: 2017-10-31  2.4544802
12: 2017-11-30  3.1477730
13: 2017-12-31  2.8461506
14: 2018-01-31  1.8862944
15: 2018-02-28  1.8946470
16: 2018-03-31  0.7864341
© www.soinside.com 2019 - 2024. All rights reserved.