将每日系列转换为每周将索引更改为所有周的星期五,而不管真实日期(convert a daily series into weekly changing the index to fridays in

编程入门 行业动态 更新时间:2024-10-28 08:21:05
将每日系列转换为每周将索引更改为所有周的星期五,而不管真实日期(convert a daily series into weekly changing the index to fridays in all weeks regardless of the true date)

我正在尝试将每日系列转换为星期五结束的每周系列。 每个系列都有缺失值,因此merge功能会留下一些NA。 我试过na.locf和to.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)

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做了伎俩!

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

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)

更多推荐

本文发布于:2023-08-05 03:26:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1428656.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   索引   星期   日期   真实

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!