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

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

Ellipsoids are a generalization of ellipses to higher dimensions. Herein, confidence ellipsoids refers as a three-dimensional graphical representations, plotted in the space defined by three variables in a trivariate dataset.

```{r message=FALSE, warning=FALSE}
library(magrittr)
library(dplyr)
```

```{r message=FALSE, warning=FALSE}
library(ConfidenceEllipse)
```

```{r}
data(glass, package = "ConfidenceEllipse")
```

# Coordinate points

The `confidence_ellipsoid` function accepts `x`, `y` and `z` input variables and computes the coordinate points of the ellipsoid at the specified confidence level `conf_level`.

```{r message=FALSE, warning=FALSE}
ellipsoid <- glass %>%
  confidence_ellipsoid(x = SiO2, y = Na2O, z = Fe2O3, conf_level = 0.95)
```

```{r}
ellipsoid %>% glimpse()
```

```{r message=FALSE, warning=FALSE}
rgl::setupKnitr(autoprint = TRUE)
rgl::plot3d(
  x = ellipsoid$x,
  y = ellipsoid$y,
  z = ellipsoid$z,
  xlab = "SiO2 (wt.%)",
  ylab = "Na2O (wt.%)",
  zlab = "Fe2O3 (wt.%)",
  type = "l",
  radius = .05,
  col = "darkgrey"
)
rgl::points3d(
  x = glass$SiO2,
  y = glass$Na2O,
  z = glass$Fe2O3,
  col = "darkred",
  size = 5
)
rgl::view3d(zoom = .8)
```

# Grouping

For grouping trivariate data, the `.group_by` argument can be used if the data contains an unique grouping variable (`.group_by = NULL` by default). When a grouping variable is provided, the function will compute the ellipsoid separately for each level of the factor. It's important to note that the grouping variable should be appropriately coded as a factor before passing it to the `.group_by` argument.

```{r message=FALSE, warning=FALSE}
ellipsoid_grp <- glass %>%
  confidence_ellipsoid(x = SiO2, y = Na2O, z = Fe2O3, .group_by = glassType, conf_level = 0.95)
```

```{r}
ellipsoid_grp %>% glimpse()
```

```{r message=FALSE, warning=FALSE}
rgl::setupKnitr(autoprint = TRUE)
rgl::plot3d(
  x = ellipsoid_grp$x,
  y = ellipsoid_grp$y,
  z = ellipsoid_grp$z,
  xlab = "SiO2 (wt.%)",
  ylab = "Na2O (wt.%)",
  zlab = "Fe2O3 (wt.%)",
  type = "s",
  radius = .03,
  col = as.numeric(ellipsoid_grp$glassType)
)
rgl::points3d(
  x = glass$SiO2,
  y = glass$Na2O,
  z = glass$Fe2O3,
  col = as.numeric(glass$glassType),
  size = 5
)
rgl::view3d(zoom = .8)
```


















