I would like to replace NA values with previous two months' average. For example, region A in Dec 2014 has missing v1
for males. How do I replace the NA with the average of region A's previous two values of Dec-Male v1
?
| v1|region |gender | year|month |
|---------:|:------|:------|----:|:-----|
| NA|A |Male | 2014|Dec |
| 12.055853|A |Female | 2014|Dec |
| 10.516935|B |Male | 2014|Dec |
| 2.251625|B |Female | 2014|Dec |
| 11.230126|C |Male | 2014|Dec |
| NA|C |Female | 2014|Dec |
#----------------
# Data Example
#----------------
toy_data <- tibble(
var_missing = rnorm(mean = 10, sd = 3, n = 360),
region = rep(c("A", "B", "C"), each = 2, times = 60),
gender = rep(c("Male","Female"), times = 180),
year = rep(2010:2014, each = 72),
month = rep(1:12, each = 6, times = 5)) %>%
mutate(month = month(month, label = TRUE))
# replace with NA
toy_data[355, 1] <- NA
toy_data[360, 1] <- NA