---
title: "Runner examples"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Runner examples}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

The most fundamental function in `runner` package is `runner`. With `runner::runner`
one can apply any R function on running windows. This tutorial presents set of 
examples explaining how to tackle some tasks. Some of the examples are referenced 
to original topic on [stack-overflow](https://stackoverflow.com).

![](images/using_runner.png)

### Number of unique elements in 7 days window

```{r echo=TRUE, message=FALSE, warning=FALSE}
library(runner)
x <- sample(letters, 20, replace = TRUE)
date <- as.Date(cumsum(sample(1:5, 20, replace = TRUE)), origin = Sys.Date()) # unequaly spaced time series

runner(x, k = 7, idx = date, f = function(x) length(unique(x)))
```

### weekly trimmed mean

```{r echo=TRUE, message=FALSE, warning=FALSE}
x <- cumsum(rnorm(20))
date <- as.Date(cumsum(sample(1:5, 20, replace = TRUE)), origin = Sys.Date()) # unequaly spaced time series

runner(x, k = 7, idx = date, f = function(x) mean(x, trim = 0.05))
```

### 2 weeks regression

```{r echo=TRUE, message=FALSE, warning=FALSE}
x <- cumsum(rnorm(20))
y <- 3 * x + rnorm(20)
date <- as.Date(cumsum(sample(1:3, 20, replace = TRUE)), origin = Sys.Date()) # unequaly spaced time series
data <- data.frame(date, y, x)

running_regression <- function(idx) {
  predict(lm(y ~ x, data = data))[max(idx)]
}

data$pred <- runner(seq_along(x), k = 14, idx = date, f = running_regression)

plot(data$date, data$y, type = "l", col = "red")
lines(data$date, data$pred, col = "blue")
```


### Rolling sums for groups with uneven time gaps

[SO discussion](https://stackoverflow.com/a/58167952/3495076)

```{r echo=TRUE, message=FALSE, warning=FALSE}
library(dplyr)
set.seed(3737)
df <- data.frame(
  user_id = c(rep(27, 7), rep(11, 7)),
  date = as.Date(rep(c('2016-01-01', '2016-01-03', '2016-01-05', '2016-01-07', '2016-01-10', '2016-01-14', '2016-01-16'), 2)),
  value = round(rnorm(14, 15, 5), 1))

df %>%
  group_by(user_id) %>%
  mutate(
    v_minus7  = sum_run(value, 7, idx = date),
    v_minus14 = sum_run(value, 14, idx = date))
```
