gpt4 book ai didi

r - xts 按周拆分函数将一周的第一天指定为星期日而不是默认的星期一

转载 作者:行者123 更新时间:2023-12-04 12:05:45 27 4
gpt4 key购买 nike

申请 split函数到 xts对象来自 weeks将行分组为每周块。组中的默认天数是 MondaySunday .想要群里的天数来自Sunday怎么办?至 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

最佳答案

我经常在周日而不是周一按周拆分,因为我处理外汇数据(市场在纽约东部时间周日下午开盘)。这是一个有效的解决方案,split_FXweeks ,使用“xts方式”分割时间序列数据。当您长时间处理高密度刻度数据时,这种方法非常快。

此技巧的功劳归功于以下链接中的技巧 1:http://darrendev.blogspot.com.au/2012/08/small-rxts-code-snippets-and-tips.html

添加了与其他建议方法相比的基准作为基准。

idx <- as.Date("2018-3-1") + 0:14
v <- 1:15
x <- xts(v, idx)


split_FXweeks <- function(x) {
ep <- .Call("endpoints", .index(x) + 4L * 86400L, 604800L,
1, TRUE, PACKAGE = "xts")
sp <- (ep + 1)[-length(ep)]
ep <- ep[-1]
lapply(1:length(ep), function(X) x[sp[X]:ep[X]])
}


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

library(microbenchmark)
microbenchmark(
y <- split_FXweeks(x),
z <- split1(idx, x))
# Unit: microseconds
# expr min lq mean median uq max neval
# y <- split_FXweeks(x) 52.521 60.167 72.90766 75.2390 80.6495 162.077 100
# z <- split1(idx, x) 325.681 351.658 383.13293 364.2215 384.9765 881.486 100
# > y
# [[1]]
# [,1]
# 2018-03-01 1
# 2018-03-02 2
# 2018-03-03 3
#
# [[2]]
# [,1]
# 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]]
# [,1]
# 2018-03-11 11
# 2018-03-12 12
# 2018-03-13 13
# 2018-03-14 14
# 2018-03-15 15

关于r - xts 按周拆分函数将一周的第一天指定为星期日而不是默认的星期一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49603445/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com