中每周拆分时间序列

中每周拆分时间序列

本文介绍了在 R 中每周拆分时间序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想每周在 R 中拆分 xts/zoo 时间序列.时区设置为亚洲/加尔各答"

I want to split xts/zoo time-series in R on weekly basis. The timezone is set to "Asia/Kolkata"

Sys.setenv(TZ="Asia/Kolkata")
library(xts)
seqs<- seq(as.POSIXct("2016-01-01"),as.POSIXct("2016-01-30"), by = "30 mins")
ob<- xts(data.frame(value=1:(length(seqs))),seqs)
weekdata <- split(ob,f="weeks",k=1)

这个split的问题是每周数据偏移了5:30小时,如下图

The problem with this split is that each week data is offset by 5:30 hours as shown below

> head(weekdata[[2]],2)
                    value
2016-01-04 05:30:00   156
2016-01-04 06:00:00   157
> head(weekdata[[3]],2)
                    value
2016-01-11 05:30:00   492
2016-01-11 06:00:00   493

我知道这是由于时区(亚洲/加尔各答为 5:30 小时).我也相信这可以通过使用 endpoints 函数来调整,但我发现它很难修复.谁能提供一些指点?

I know it is due to timezone (5:30 hours for Asia/Kolkata). I also believe that this can be tuned by using endpoints function, but I find it diffcult to fix. Can anyone provide some pointers?

推荐答案

所以,如果我理解正确的话,你想要的输出是一个 xts 列表,其中每个元素都有一个星期的数据.你可以这样做:

So if I understand correctly your desired output is a list of xts where every element has data for one week.You can do that with this:

Sys.setenv(TZ="Asia/Kolkata")
library(xts)
library(lubridate)
seqs = seq(as.POSIXct("2016-01-01"),as.POSIXct("2016-01-30"), by = "30 mins")
weeks <- week(seqs)
df <- data.frame(seqs, weeks)
ob <- xts(data.frame(value=1:(length(seqs))), seqs)
weekdata = lapply(unique(weeks), function(i){
   ob[weeks == i]
})

这篇关于在 R 中每周拆分时间序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 06:27