---
title: "Getting started with nestedmodels"
description: "An introduction to the nestedmodels package"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Getting started with nestedmodels}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

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

This vignette provides an introduction to the nestedmodels package and the most basic use case. For this and all other vignettes, it is assumed that you have a familiarity with the '[tidymodels](https://www.tidymodels.org/)' framework (e.g. by reading [Tidy Modelling with R](https://www.tmwr.org/)). This vignette does not aim to teach good statistical practices, and instead demonstrates how to use the package as simply as possible.

# What is nestedmodels?
nestedmodels is an extension to the '[tidymodels](https://www.tidymodels.org/)' framework. It allows models and workflows to be used on [nested data](https://tidyr.tidyverse.org/articles/nest.html). It provides an alternative to [modeltime's approach to nested modelling](https://business-science.github.io/modeltime/articles/nested-forecasting.html) or the '[multilevelmod](https://multilevelmod.tidymodels.org/)' package, allowing any model or workflow to be used on nested data very easily.

# Why do I need nestedmodels?
The best example where you may need to use the nestedmodels package is when working with panel data. When you have a set of time series, each describing a different object (the historic prices for a set of stocks, for example), you may want to model each time series separately, especially considering the fact that many time series modelling tools do not work well with non-date predictors (and furthermore, many models do not accept non-numeric predictors, although there are often better ways to deal with this problem; see `recipes::step_dummy()`). In this scenario, nested modelling is often the best solution.

# How does nestedmodels work?
The implementation of nestedmodels is very simple. Fitting a nested model fits the model to each nested value (for time series about a set of stocks, a model would be fitted to each stock). The correct model will then be selected and used when making predictions.

# A quick example
In this vignette, we're going to explore the most basic example of a nested model. You're going to need the following packages:

```{r setup, message = FALSE}
library(nestedmodels)
library(tidyr)
library(parsnip)
library(recipes)
library(workflows)
library(rsample)
library(glmnet)
```

We're going to use the example data included in the nestedmodels package. The data is very simple, and only serves as an example of data that can be nested, rather than representing anything concrete.

```{r data}
data("example_nested_data")
data <- example_nested_data
data
```

The data can be nested in the following way:

```{r nested-data}
nested_data <- nest(data, data = -id)
nested_data
```
Lets split this data up into a training and testing set using the `nested_resamples()` function. This ensures that the training and testing set all contain data with every 'id' value.

```{r}
split <- nested_resamples(nested_data, rsample::initial_split())
data_tr <- rsample::training(split)
data_tst <- rsample::testing(split)
```

Now let's define our model:

```{r create-model}
model <- linear_reg(penalty = 0.1) %>%
  set_engine("glmnet")
```

Since we're fitting this model to nested data, we need some way to make the model 'nested'. This is very simple with the `nested()` function.

```{r nested-model}
nested_model <- model %>%
  nested()
nested_model
```

We can then fit this model in the usual way. Note that the data must be nested, and formula cannot include the id column.

```{r fit-model}
nested_tr <- tidyr::nest(data_tr, data = -id)
model_fit <- fit(nested_model, z ~ x + y + a + b, nested_tr)
model_fit
```

Predicting can also be done in the usual way (the data to predict on can be both nested and non-nested). Since this is just a demonstration, we use the same data that the model was fitted on.

```{r predict-model, R.options = list(warnPartialMatchArgs = FALSE)}
predict(model_fit, data_tst)
```

This method is fine, but having to nest the data ourselves is a pain. We can solve this by using a workflow.

We first define the recipe, and we define a step which is used to nest the data. This time, the formula can include the 'id' column, since the recipe needs to act on it.

```{r recipe}
recipe <- recipe(data_tr, z ~ x + y + a + b + id) %>%
  step_nest(id)
```

This is a little easier than nesting the data manually. Note that the recipe does not actually nest the data, but instead removes the specified columns and adds a new column, '.nest_id', which specifies which nest each row belongs to.

```{r bake}
recipe %>%
  prep() %>%
  bake(NULL)
```

Now we create the workflow, combining the recipe and the model.

```{r workflow}
wf <- workflow() %>%
  add_model(nested_model) %>%
  add_recipe(recipe)
```

A workflow can be fitted in the same way as a model, but note that since we used `step_nest()` the data does not have to be nested.

```{r workflow-fit}
wf_fit <- fit(wf, data_tr)
```

This fit object can then be used to make predictions.

```{r workflow-predict, R.options = list(warnPartialMatchArgs = FALSE)}
predict(wf_fit, data_tst)
```

Other common parsnip functions can also be used on fitted nested models:

```{r tidy, R.options = list(warnPartialMatchArgs = FALSE)}
augment(wf_fit, data_tst)
tidy(wf_fit)
```

This is all you really need to know to use the nestedmodels package. These models and workflows can be compared, fitted and tuned in much the same way as normal models and workflows - you can even combine them with normal models using the workflowsets and stacks packages.

# Conclusion
In this short vignette, a simple example of a nested model and workflow were created and used on dummy data, to demonstrate how nestedmodels is used.
