Convert daily to weekly/monthly data with R

匿名 (未验证) 提交于 2019-12-03 02:00:02

问题:

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

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.

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

I am eventually using:

length(bra)

1 2416

test

Would there be a more efficient approach? Thanks.

回答1:

Let's try with this data:

library(zoo) tt 

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 

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

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

which produces this result:

                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 


回答2:

I'm fairly new to R but stumbled on this when I had a similar problem. I needed to convert xts data that isn't OHLC. to.monthly states that it can handle univariate series but it also says in the details that it only supports returning OHLC. I think it might work by just setting OHLC=FALSE. Alternatively, the source of to.period uses the following function which worked for me even to convert several series (all with same time index)

data.monthly 

Short and clean and even copies the column names.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!