Here is a brief description of my data: The first column is date by month, the second column is binary variable (0 or 1), the third column is stock return, so each month's stock return point to 1 or 0. I want to calculate the 12-month rolling mean return separately based on the second column (0 or 1). There will be different number of 0s and 1s in the 12-month rolling base. There should be 2 outcome (mean_rolling_0, and mean_rolling_1).
Asked
Active
Viewed 105 times
0
-
1It would be really helpful if you provided a reproducible example of your data, what you've tried, what isn't working, and what you expected outcome is. Otherwise, your question is likely to be downvoted to oblivion. – tblznbits Sep 27 '18 at 19:25
1 Answers
1
Use rollmean()
from the zoo package, and apply this per group with group_by()
in dplyr.
Here's an example. I'm guessing at your data structure, but it will also work for similar structures.
library(tidyverse)
library(zoo)
# sample data
d = tibble(a = 1:100,
b = sample(c(0,1), 100, replace = T),
c = a/10 + rnorm(100))
# compute rolling mean
d2 = d %>%
group_by(b) %>%
mutate(roll = rollmean(c, 12, na.pad=TRUE, align="right"))
# plot to see the effect
ggplot(data = d2) + geom_line(aes(x = a, y = c, colour = factor(b))) +
geom_line(aes(x = a, y = roll, colour = factor(b)), linetype = 'dashed')

Mike S
- 312
- 1
- 8