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

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

```{r setup}
library(tidydlnm)
library(tibble)
library(dplyr)
library(dlnm)
```

Suppose we have the following data, where lags 0 through 9 are the values of some exposure experienced 0 to 9 days before the outcome `y`.

```{r, echo = F}
set.seed(212)
d <- tibble::tibble(lag0 = rnorm(n=100, mean=0.3, sd=1))

d <- d %>%
    dplyr::mutate(lag1 = rnorm(n=100, mean=lag0, sd=1),
           lag2 = rnorm(n=100, mean=lag1, sd=1),
           lag3 = rnorm(n=100, mean=lag2, sd=1),
           lag4 = rnorm(n=100, mean=lag3, sd=1),
           lag5 = rnorm(n=100, mean=lag4, sd=1),
           lag6 = rnorm(n=100, mean=lag5, sd=1),
           lag7 = rnorm(n=100, mean=lag6, sd=1),
           lag8 = rnorm(n=100, mean=lag7, sd=1),
           lag9 = rnorm(n=100, mean=lag8, sd=1))

d <- d %>%
    dplyr::mutate(y = rnorm(100, mean = 53.5 + 2*(lag3+lag4), sd=10))

d
```

First, use the `dlnm` package to fit a distributed lag model. We create the crossbasis, fit the model, and create the crosspred object. (For more info, see [https://github.com/gasparrini/dlnm](https://github.com/gasparrini/dlnm)). 

```{r, message = F}
Q <- dplyr::select(d, lag0:lag9)

cb <- dlnm::crossbasis(Q, lag=9,
                   argvar=list("lin"),
                   arglag=list(fun="ns"))
mod <- lm(y ~ cb, data=d)
cpred <- dlnm::crosspred(cb, mod, at=1, cumul = TRUE)
```

Then use `tidydlnm` to obtain more tidyverse-friendly output and plots. 

## Effect estimates at each lag

```{r}
lag_fits <- tidy_lag_fits(cpred)
tidy_lag_plot(lag_fits)
```

## Estimated effect over all lags

```{r}
tidy_overall_fit(cpred)
```

## Cumulative effect estimates at each lag

```{r}
cumul_fits <- tidy_cumul_fits(cpred)
```

Add optional shading to plot of estimates at each lag with the `shading` argument.
```{r}
tidy_lag_plot(lag_fits, shading = T)
```

Note that the same plotting function can be used to plot the cumulative estimates. Also, since this is a ggplot object, the plot can be customized as any other ggplot. 

```{r}
library(ggplot2)

tidy_lag_plot(cumul_fits) +
  ylab("Estimate") +
  theme_minimal()
```

For a summary of specific windows of association identified by the model, use `tidy_window_summary()`.
```{r}
tidy_window_summary(lag_fits)
```

