---
title: "MARS models via the `earth` package"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{MARS models via the `earth` package}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

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

| Function                                                      |Works|
|---------------------------------------------------------------|-----|
|`tidypredict_fit()`, `tidypredict_sql()`, `parse_model()`      |  ✔  |
|`tidypredict_to_column()`                                      |  ✔  |
|`tidypredict_test()`                                           |  ✔  |
|`tidypredict_interval()`, `tidypredict_sql_interval()`         |  ✗  |
|`parsnip`                                                      |  ✔  |


## `tidypredict_` functions

```{r}
library(earth)
data("etitanic", package = "earth")

model <- earth(age ~ sibsp + parch, data = etitanic, degree = 3)
```

- Create the R formula
    ```{r}
    tidypredict_fit(model)
    ```

- SQL output example
    ```{r}
    tidypredict_sql(model, dbplyr::simulate_odbc())
    ```

- Add the prediction to the original table
    ```{r}
    library(dplyr)
    
    etitanic %>%
      tidypredict_to_column(model) %>%
      glimpse()
    ```

- Confirm that `tidypredict` results match to the model's `predict()` results
    ```{r}
    tidypredict_test(model, etitanic)
    ```

## GLM models

`tidypredict` supports the `glm` argument as well:
```{r}
model <- earth(survived ~ .,
               data = etitanic,
               glm = list(family = binomial), degree = 2)

tidypredict_fit(model)
```

The spec sets the `is_glm` entry to 1, as well as the `family` and `link` entries. 
```{r}
str(parse_model(model), 2)
```

## parsnip

`parsnip` fitted models are also supported by `tidypredict`:
```{r}
library(parsnip)

p_model <- mars(mode = "regression", prod_degree = 3) %>%
  set_engine("earth") %>%
  fit(age ~ sibsp + parch, data = etitanic)

tidypredict_fit(p_model)
```

## Parse model spec

Here is an example of the model spec:
```{r}
pm <- parse_model(model)
str(pm, 2)
```

```{r}
str(pm$terms[1:2])
```

