Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
755 views
in Technique[技术] by (71.8m points)

xts - Convert daily to weekly/monthly data with 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.

enter image description here

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 eventually used:

length(bra)

[1] 2416

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

Would there be a more efficient approach? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...