Skip to content

Instantly share code, notes, and snippets.

@DavisVaughan
Last active April 18, 2020 02:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavisVaughan/83aef2194ef98cabc0725f0b751fec91 to your computer and use it in GitHub Desktop.
Save DavisVaughan/83aef2194ef98cabc0725f0b751fec91 to your computer and use it in GitHub Desktop.
suppressPackageStartupMessages(library(tibbletime))
suppressPackageStartupMessages(library(tidyverse))
data(FB)
# Create the column names
col_names <- map_chr(2:10, ~paste0("adjusted_", .x))
# Creating the rolling functions and assign them names
rollers <- map(2:10, ~rollify(mean, window = .x)) %>%
set_names(nm = col_names)
# Use invoke map, it takes a list of functions and calls each one with the
# supplied args
FB_with_multiroll <- bind_cols(FB, invoke_map(rollers, x = FB$adjusted))
FB_with_multiroll %>% select(starts_with("adjusted"))
#> # A tibble: 1,008 x 10
#> adjusted adjusted_2 adjusted_3 adjusted_4 adjusted_5 adjusted_6
#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 28.00 NA NA NA NA NA
#> 2 27.77 27.885 NA NA NA NA
#> 3 28.76 28.265 28.17667 NA NA NA
#> 4 29.42 29.090 28.65000 28.4875 NA NA
#> 5 29.06 29.240 29.08000 28.7525 28.602 NA
#> 6 30.59 29.825 29.69000 29.4575 29.120 28.93333
#> 7 31.30 30.945 30.31667 30.0925 29.826 29.48333
#> 8 31.72 31.510 31.20333 30.6675 30.418 30.14167
#> 9 30.95 31.335 31.32333 31.1400 30.724 30.50667
#> 10 30.10 30.525 30.92333 31.0175 30.932 30.62000
#> # ... with 998 more rows, and 4 more variables: adjusted_7 <dbl>,
#> # adjusted_8 <dbl>, adjusted_9 <dbl>, adjusted_10 <dbl>
@salvelinusbob
Copy link

This worked great for me but now I'd like to do this on multiple groups of FB$adjusted. For instance, if there were multiple stock symbols in this example across the same date range, I'd like to have the same multiple rolling means calculated for each group.

I tried the equivalent of:
FB_with_multiroll <- FB%>%
group_by(symbol) %>%
bind_cols(FB, invoke_map(rollers, x = FB$adjusted))

But that didn't work.

Thanks

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