Search code examples
ras.daterollapply

R: Rollapply, preserve Date column


I have a dataset that includes a date column and the other columns are daily index returns. I would like to receive the rolling standard deviation for all indices but preserve the date in order to plot the results. Data looks as follows:

head(mydata)

        Date      GL1 GL2       US CN       JP       DE       UK
1 1990-01-03  0.02460  NA -0.25889 NA       NA  3.00128  1.20872
2 1990-01-04  0.33681  NA -0.86503 NA       NA -1.82327 -0.49234
3 1990-01-05 -0.81943  NA -0.98041 NA -1.13817 -0.86874 -0.29003
4 1990-01-06       NA  NA       NA NA       NA       NA       NA
5 1990-01-07       NA  NA       NA NA       NA       NA       NA

When using rollapply function the date however disappears and returns NAs

require(zoo)

Rolling = as.data.frame(rollapply(mydata,30,sd,na.rm=TRUE,align="right"))

head(Rolling)
 Date       GL1 GL2       US CN        JP       DE        UK
1   NA 0.5527451  NA 1.033204 NA 0.9021960 1.486567 0.8421562
2   NA 0.5675608  NA 1.057156 NA 0.9318496 1.467637 0.7954081
3   NA 0.5681388  NA 1.077253 NA 0.9318496 1.438117 0.8123918
4   NA 0.5663124  NA 1.095049 NA 0.9264034 1.454327 0.8331727
5   NA 0.5623544  NA 1.075118 NA 0.9017324 1.443547 0.8123613
6   NA 0.5523878  NA 1.052310 NA 0.8797660 1.411220 0.8197624

I kept the date in the as.Date format but can not figure out how to continue showing the corresponding dates in the Date column.


Solution

  • The real problem here is using data frames to represent time series. If you use a time series representation then the entire problem goes away.

    mydata_z <- read.zoo(mydata)
    r <- rollapplyr(mydata_z, 30, sd, na.rm = TRUE, fill = NA)
    

    Now you can use plot.zoo, xyplot.zoo or autoplot.zoo to graph r using classic graphics, lattice graphics or ggplot2 graphics respectively or if you need a data frame then fortify.zoo(r).