Let's first create the dataset:
d1 <- data.frame(Date = seq.Date(as.Date("2009-04-07"), as.Date("2015-04-06"), by = "day"), stock = 60004)
d2 <- data.frame(Date = seq.Date(as.Date("2009-04-07"), as.Date("2015-04-06"), by = "day"), stock = 60005)
d3 <- data.frame(Date = seq.Date(as.Date("2009-04-07"), as.Date("2015-04-06"), by = "day"), stock = 60006)
d4 <- data.frame(Date = seq.Date(as.Date("2009-04-07"), as.Date("2015-04-06"), by = "day"), stock = 60007)
dat <- rbind(d1, d2, d3, d4)
dat$D <- rnorm(dim(dat)[1])
dat$stock <- as.factor(dat$stock)
datzoo$rollmean <- ave(dats$D, datzoo$stock, FUN = function(x) rollmean(x, k = 365, fill = 0, align = "right"))
For ave
to work optimally, you should convert stock
into a factor, and set the ave
function where k
is the window size (365 for rolling mean by day); fill
is what to fill NA
values with; and align
is to let the function know which side (left is the same as top and right is the same as bottom of dataset) to calculate your rolling mean from.