# Confidence Ellipsoid

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.

    library(magrittr)
    library(dplyr)

    library(ConfidenceEllipse)

    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`.

    ellipsoid <- glass %>%
      confidence_ellipsoid(x = SiO2, y = Na2O, z = Fe2O3, conf_level = 0.95)

    ellipsoid %>% glimpse()
    #> Rows: 2,500
    #> Columns: 3
    #> $ x <dbl> 66.54472, 66.54472, 66.54472, 66.54472, 66.54472, 66.54472, 66.54472…
    #> $ y <dbl> 12.55263, 12.55263, 12.55263, 12.55263, 12.55263, 12.55263, 12.55263…
    #> $ z <dbl> 0.6815153, 0.6815153, 0.6815153, 0.6815153, 0.6815153, 0.6815153, 0.…

    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.

    ellipsoid_grp <- glass %>%
      confidence_ellipsoid(x = SiO2, y = Na2O, z = Fe2O3, .group_by = glassType, conf_level = 0.95)

    ellipsoid_grp %>% glimpse()
    #> Rows: 10,000
    #> Columns: 4
    #> $ x         <dbl> 67.32486, 67.32486, 67.32486, 67.32486, 67.32486, 67.32486, …
    #> $ y         <dbl> 14.51964, 14.51964, 14.51964, 14.51964, 14.51964, 14.51964, …
    #> $ z         <dbl> 0.5971494, 0.5971494, 0.5971494, 0.5971494, 0.5971494, 0.597…
    #> $ glassType <fct> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, …

    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)