xts 按周拆分函数将一周的第一天指定为星期日而不是默认的星期一 [英] xts split by week function specify first day of week as Sunday instead of default of Monday

查看:41
本文介绍了xts 按周拆分函数将一周的第一天指定为星期日而不是默认的星期一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过weekssplit 函数应用于xts 对象,将行分组为每周块.组中的默认天数是 MondaySunday.如果我希望小组中的日子从SundaySaturday 怎么办?

Applying the split function to a xts object by weeks groups rows into weekly chunks. The default days in the group are Monday to Sunday. What do I do if I want the days in the group to be from Sunday to Saturday?

library(xts)
idx <- as.Date("2018-3-1") + 0:14
v <- 1:15
x <- xts(v, idx)
group <- split(x, f = 'weeks')
group

Output:
[[1]]
           [,1]
2018-03-01    1  # Thursday
2018-03-02    2  # Friday
2018-03-03    3  # Saturday
2018-03-04    4  # Sunday

[[2]]
           [,1]
2018-03-05    5  # Monday
2018-03-06    6  # Tuesday
2018-03-07    7  # Wednesday
2018-03-08    8  # Thursday
2018-03-09    9  # Friday
2018-03-10   10  # Saturday
2018-03-11   11  # Sunday

[[3]]
           [,1]
2018-03-12   12  # Monday
2018-03-13   13  # Tuesday
2018-03-14   14  # Wednesday
2018-03-15   15  # Thursday

Desired Output:
[[1]]
           [,1]
2018-03-01    1  # Thursday
2018-03-02    2  # Friday
2018-03-03    3  # Saturday

[[2]]
           [,1]
2018-03-04    4  # Sunday
2018-03-05    5  # Monday
2018-03-06    6  # Tuesday
2018-03-07    7  # Wednesday
2018-03-08    8  # Thursday
2018-03-09    9  # Friday
2018-03-10   10  # Saturday

[[3]]
           [,1]
2018-03-11   11  # Sunday
2018-03-12   12  # Monday
2018-03-13   13  # Tuesday
2018-03-14   14  # Wednesday
2018-03-15   15  # Thursday

推荐答案

考虑为工作日开始创建具有 %U 格式的 Week Number 的外部等长向量在星期天.参见 ?strftime.

Consider creating an external, equal-length vector of Week Number with %U format for weekdays starting on Sunday. See ?strftime.

%U

以星期日为第一个十进制数 (00–53) 的一年中的第几周一周的第 1 天(通常将一年的第一个星期日作为第 1 周的第 1 天).美国公约.

Week of the year as decimal number (00–53) using Sunday as the first day 1 of the week (and typically with the first Sunday of the year as day 1 of week 1). The US convention.

week_num <- format(idx, "%U")
group <- unname(split(x, f = week_num))
group

[[1]]

2018-03-01 1
2018-03-02 2
2018-03-03 3

[[2]]

2018-03-04  4
2018-03-05  5
2018-03-06  6
2018-03-07  7
2018-03-08  8
2018-03-09  9
2018-03-10 10

[[3]]

2018-03-11 11
2018-03-12 12
2018-03-13 13
2018-03-14 14
2018-03-15 15

这篇关于xts 按周拆分函数将一周的第一天指定为星期日而不是默认的星期一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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