【问题标题】:convert a daily series into weekly changing the index to fridays in all weeks regardless of the true date将每日系列转换为每周将索引更改为所有星期中的星期五,无论真实日期如何
【发布时间】:2013-10-11 16:55:13
【问题描述】:

我正在尝试将每日系列转换为周五结束的每周系列。每个系列都有缺失值,因此merge 函数会留下一些 NA。我试过na.locfto.weekly 但对我不起作用。我正在创建一个包含该期间所有星期五的每周日期对象,并且由于某些系列的某些星期在星期三或星期四结束,因此我无法匹配这些索引。

理想情况下,我想覆盖那些星期内最后一个值的日期,而不是在星期五结束。

library(quantmod)
library(xts)

TickerL <- c("ABE.MC", "FNC.MI", "ENI.MI")

getSymbols(TickerL,from = "2000-01-01")

pr <- list(ABE.MC[,4], FNC.MI[,4], ENI.MI[,4])

w.dates <- seq(from=min(index(ABE.MC)),to=max(index(ABE.MC)), by='days') 
w.dates <- w.dates[.indexwday(as.xts(w.dates))==5] 
if (max(index(ABE.MC)) > max(w.dates)) w.dates <- c(w.dates,seq(last(w.dates),by='weeks',length.out=2)[2])

pr2 <- lapply(pr, function(x) do.call(rbind, lapply(split(x, "weeks"), last)))

pr3 <- do.call(merge, pr2)

【问题讨论】:

  • 查看 zoo 包快速参考小插图中的一行 nextfri 函数。
  • @G。非常感谢格洛腾迪克!

标签: r time-series xts


【解决方案1】:

感谢@G。 Grothendieck 函数 nextfri 在 zoo 包 vignette 中成功了!

# given a Date, x, return the Date of the next Friday
nextfri <- function(x) 7 * ceiling(as.numeric(x - 1)/7) + as.Date(1)

pr2 <- lapply(pr, function(x) x <- do.call(rbind, lapply(split(x, "weeks"), last))
                    index(x) <- nextfri(index(x))
                    x
)

pr3 <- do.call(merge, pr2)

【讨论】:

    猜你喜欢
    • 2017-06-05
    • 2017-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多