使用 R 将每日数据转换为每周/每月数据 [英] Convert daily to weekly/monthly data with R

查看:203
本文介绍了使用 R 将每日数据转换为每周/每月数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有各种产品的每日价格系列;我想转换为包含每周或每月数据的新数据框.

I have daily prices series over a wide range of products; I want to convert to a new dataframe with weekly or monthly data.

我第一次使用 xts 是为了应用 to.weekly 函数……它只适用于 OHLC 格式.我确信可能存在类似于 to.weekly 的函数,但对于格式不是 OHLC 的数据帧.

I first used xts in order to apply the to.weekly function...which works only for OHLC format. I am sure there may exist a function similar to to.weekly but for dataframe where the format is not OHLC.

已经有与此相关的不同帖子如下:rollapply() 是否允许从调用函数?将每日数据平均为每周数据

There a different posts already related to this as the following: Does rollapply() allow an array of results from call to function? or Averaging daily data into weekly data

我最终会使用:

长度(胸罩)

1 2416

测试<-bra[seq(1,2416,7),]

test<-bra[seq(1,2416,7),]

是否有更有效的方法?谢谢.

Would there be a more efficient approach? Thanks.

推荐答案

让我们用这个数据试试:

Let's try with this data:

library(zoo)
tt <- seq(Sys.Date(), by='day', length=365)
vals <- data.frame(A=runif(365), B=rnorm(365), C=1:365)
z <- zoo(vals, tt)

现在我定义了一个函数来提取年份和星期几(如果不需要区分年份,请删除 %Y):

Now I define a function which extracts the year and the number of the week (drop %Y if you don't need to distinguish between years):

week <- function(x)format(x, '%Y.%W')

您可以使用此函数将 zoo 对象与均值进行聚合(例如):

You can use this function to aggregate the zoo object with mean (for example):

aggregate(z, by=week, FUN=mean)

产生这个结果:

                A           B  C
2013.18 0.3455357  0.34129269  3
2013.19 0.4506297  0.57665133  9
2013.20 0.3950585  0.46197173 16
2013.21 0.5990886 -0.02689994 23
2013.22 0.5115043  0.18726564 30
2013.23 0.5327597  0.16250339 37

这篇关于使用 R 将每日数据转换为每周/每月数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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