Guest User

Untitled

a guest
Feb 17th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. ```{r setup}
  2. library(tidyverse)
  3. library(RcppRoll)
  4. ```
  5.  
  6.  
  7. ```{r function}
  8.  
  9. splatter <- function(var, fun, n = 10, ...) {
  10.  
  11. args <- quos(...)
  12. var <- enquo(var)
  13. fun <- enquo(fun)
  14.  
  15.  
  16. if(length(n) == 1) {
  17. i <- seq_len(n)
  18. } else {
  19. i <- n
  20. }
  21.  
  22. map( i, ~quo(UQ(fun)(!!var, !!.x, !!!args)) ) %>%
  23. set_names(sprintf("%s_%s_%s", quo_text(var), quo_text(fun), i))
  24.  
  25. }
  26.  
  27. ```
  28.  
  29.  
  30. ```{r output}
  31.  
  32. library(gapminder)
  33.  
  34. rolls <- splatter(lifeExp, roll_mean, c(2, 3, 5), fill = NA)
  35.  
  36.  
  37. gapminder %>% group_by(country) %>% mutate(!!!rolls) %>%
  38. select(country, year, matches("roll_mean"))
  39.  
  40. # A tibble: 1,704 x 5
  41. # Groups: country [142]
  42. country year lifeExp_roll_mean_2 lifeExp_roll_mean_3 lifeExp_roll_mean_5
  43. <fct> <int> <dbl> <dbl> <dbl>
  44. 1 Afghanistan 1952 29.6 NA NA
  45. 2 Afghanistan 1957 31.2 30.4 NA
  46. 3 Afghanistan 1962 33.0 32.1 32.2
  47. 4 Afghanistan 1967 35.1 34.0 34.2
  48. 5 Afghanistan 1972 37.3 36.2 36.1
  49. 6 Afghanistan 1977 39.1 38.1 37.8
  50. 7 Afghanistan 1982 40.3 39.7 39.4
  51. 8 Afghanistan 1987 41.2 40.8 40.5
  52. 9 Afghanistan 1992 41.7 41.4 41.2
  53. 10 Afghanistan 1997 41.9 41.9 42.0
  54. # ... with 1,694 more rows
  55.  
  56. ```
Add Comment
Please, Sign In to add comment