本文介绍了将每日系列转换为每周将所有星期的指数更改为星期五,无论真实日期如何的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to convert a daily series into a weekly one ending on Fridays. There are missing values for each series and therefore merge function leave some NAs. I have tried with na.locf and to.weekly but didn't work for me. I'm creating a weekly date object containg all fridays in that period and, because some weeks end on wednesdays or thursdays for some series, I can't match those indexes.

理想情况下,我想覆盖不以星期五结束的那些周中最后一个值的日期.

Ideally I would like to overwrite the date of the last value in those weeks not ending on fridays.

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)

推荐答案

感谢 @G.Grothendieck 动物园包小插图中的函数 nextfri 成功了!

Thanks to @G. Grothendieck the function nextfriin the zoo package vignette did the trick!

# 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)

这篇关于将每日系列转换为每周将所有星期的指数更改为星期五,无论真实日期如何的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 08:29