I want to compute a weighted moving average across multiple columns, using the same weights for each column. The weighted moving average shall be computed per group (in contrast to using `dplyr::across` with functions with more than one argument).
In the example below, the grouping should make the weighted moving average "reset" every year, yielding missing values for the first two observations of each year.
How do I make this work?
library(tidyverse)
weighted.filter <- function(x, wt, filter, ...) {
filter <- filter / sum(filter)
stats::filter(x * wt, filter, ...) / stats::filter(wt, filter, ...)
}
economics %>%
group_by(year = lubridate::year(date)) %>%
arrange(date) %>%
mutate(across(
c(pce, psavert, uempmed),
list("moving_average_weighted" = weighted.filter),
wt = pop, filter = rep(1, 3), sides = 1
))
#> Error: Problem with `mutate()` input `..1`.
#> x Input `..1` can't be recycled to size 12.
#> ℹ Input `..1` is `(function (.cols = everything(), .fns = NULL, ..., .names = NULL) ...`.
#> ℹ Input `..1` must be size 12 or 1, not 6.
#> ℹ The error occurred in group 2: year = 1968.
Created on 2021-03-31 by the reprex package (v1.0.0)