-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Closed
Description
From a StackOverflow post.
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 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.
Why does version 1 work, but version 2 does not?
library(tidyverse)
weighted.filter <- function(x, wt, filter, ...) {
filter <- filter / sum(filter)
stats::filter(x * wt, filter, ...) / stats::filter(wt, filter, ...)
}
# Version 1
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))
))
#> # A tibble: 574 x 10
#> # Groups: year [49]
#> date pce pop psavert uempmed unemploy year pce_moving_average_we…
#> <date> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 1967-07-01 507. 198712 12.6 4.5 2944 1967 NA
#> 2 1967-08-01 510. 198911 12.6 4.7 2945 1967 NA
#> 3 1967-09-01 516. 199113 11.9 4.6 2958 1967 511.
#> 4 1967-10-01 512. 199311 12.9 4.9 3143 1967 513.
#> 5 1967-11-01 517. 199498 12.8 4.7 3066 1967 515.
#> 6 1967-12-01 525. 199657 11.8 4.8 3018 1967 518.
#> 7 1968-01-01 531. 199808 11.7 5.1 2878 1968 NA
#> 8 1968-02-01 534. 199920 12.3 4.5 3001 1968 NA
#> 9 1968-03-01 544. 200056 11.7 4.1 2877 1968 536.
#> 10 1968-04-01 544 200208 12.3 4.6 2709 1968 541.
#> # … with 564 more rows, and 2 more variables:
#> # psavert_moving_average_weighted <dbl>,
#> # uempmed_moving_average_weighted <dbl>
# Version 2
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)
Metadata
Metadata
Assignees
Labels
No labels