Skip to content

Instantly share code, notes, and snippets.

@brshallo
Last active October 13, 2021 23:51
Show Gist options
  • Select an option

  • Save brshallo/f88aa80a1be181ecc176ad3b2ac2edcd to your computer and use it in GitHub Desktop.

Select an option

Save brshallo/f88aa80a1be181ecc176ad3b2ac2edcd to your computer and use it in GitHub Desktop.
More flexible version than slide_multiple() shown here: https://gist.github.com/brshallo/e193b743f86ae62b5134707ec016fdf5
library(tidyverse)
library(slider)

slide_dbl_multiple <- function(.x, .f, ..., .before = 0L, .after = 0L, .step = 1L, .complete = FALSE, suffix = "") {
  x <- .x
  f <- .f
  f_name <- deparse(substitute(.f))
  
  map2(
    .before,
    .after,
    ~ slider::slide_dbl(
      x,
      f,
      ...,
      .before = .x,
      .after = .y,
      .step = .step,
      .complete = .complete
    )
  ) %>%
    set_names(
      paste0(f_name, "_before", .before, "after", str_replace(.after, "-", "n"), suffix) %>% 
        str_replace("aftern1", "")
    ) %>%
    as_tibble()
  
}

tibble(x = 1:30) %>%
  mutate(slide_dbl_multiple(x,
                            .f = mean,
                            .before = seq(3, 7, by = 2),
                            .after = -1,
                            .complete = TRUE)
         )
#> # A tibble: 30 x 4
#>        x mean_before3 mean_before5 mean_before7
#>    <int>        <dbl>        <dbl>        <dbl>
#>  1     1           NA           NA           NA
#>  2     2           NA           NA           NA
#>  3     3           NA           NA           NA
#>  4     4            2           NA           NA
#>  5     5            3           NA           NA
#>  6     6            4            3           NA
#>  7     7            5            4           NA
#>  8     8            6            5            4
#>  9     9            7            6            5
#> 10    10            8            7            6
#> # ... with 20 more rows

Created on 2021-10-13 by the reprex package (v2.0.0)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment