按 R 中指定的不规则间隔拆分 xts 对象 [英] Split xts object by specified irregular intervals in R

查看:42
本文介绍了按 R 中指定的不规则间隔拆分 xts 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将每日 xts 对象拆分为 4 个独立的周,对应于该月的以下几天:1 日至 7 日、8 日至 14 日、15 日至 21 日和月末 22 日,其中最后一周通常会更长(但没关系!).

I want to split a daily xts object into 4 separate weeks which correspond to the following days in the month: 1st-7th, 8th-14th, 15th-21st, and 22nd to the end of the month, where the last week will generally be longer (but that's okay!).

以下是根据日期序列创建的 2004 年 1 月 xts 对象的一些示例代码:

Here's some example code of an xts object for January 2004 created from a sequence of dates:

week <- seq(from=as.Date("2004-01-01"), to=as.Date("2004-01-31"), by = "day")
x2 <- sample(1:50, 31) # generating 31 random numbers 
January_series <- xts(x2, order.by=week) # create January daily series 

问题是 1 月 1 日不是星期日,所以 split.xts 不一定符合我的要求.

The issue is that January 1st doesn't occur on a Sunday so split.xts doesn't necessarily do what I want.

我最初认为我可以创建与上述那些日子相对应的四个间隔,但我不知道这是否是正确的方法.

I initially thought that I could create four intervals corresponding to those days noted above however I don't know whether that is the right approach.

有没有办法按您创建的间隔拆分 xts 对象?

Is there any way of splitting an xts object by intervals which you've created?

推荐答案

您可以使用 .indexmday 来获取 xts 对象中每个观察值的月份日期.然后使用 cut 定义要分割的间隔.

You can use .indexmday to get the day of the month for each observation in your xts object. Then use cut to define the intervals you want to split by.

intervals <- cut(.indexmday(January_series), c(0,7,14,21,31), paste0("W",1:4))
splitlist <- split(January_series, intervals)

这篇关于按 R 中指定的不规则间隔拆分 xts 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆