## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 7,
  fig.height = 4.5
)

## ----data---------------------------------------------------------------------
measurement_names <- c(
  "Sepal.Length",
  "Sepal.Width",
  "Petal.Length",
  "Petal.Width"
)

iris_data <- datasets::iris
complete_rows <- stats::complete.cases(iris_data[, measurement_names])

x <- as.matrix(iris_data[complete_rows, measurement_names])
dim(x)

## ----fit----------------------------------------------------------------------
set.seed(2026)

iris_sig <- sigPCA::sigPCA(
  x,
  method = "both",
  num_permutations = 999
)

iris_sig$mp$mp_bounds
iris_sig$combined

## ----results-table------------------------------------------------------------
eigenvalues <- iris_sig$mp$eigenvalues

component_results <- data.frame(
  component = paste0("PC", seq_along(eigenvalues)),
  eigenvalue = round(eigenvalues, 3),
  variance_percent = round(100 * eigenvalues / sum(eigenvalues), 1),
  beyond_mp_upper = seq_along(eigenvalues) %in%
    iris_sig$mp$significant_components,
  permutation_p = iris_sig$perm$pvalues
)

knitr::kable(component_results)

## ----spectrum, fig.cap="Observed eigenvalues and the Marchenko--Pastur bounds. Components above the upper bound are highlighted."----
sigPCA::plot_sigPCA(
  iris_sig$mp$eigenvalues,
  iris_sig$mp$mp_bounds
)

## ----spectrum-histogram, fig.cap="Histogram and density of the observed eigenvalues with the Marchenko--Pastur bounds."----
sigPCA::plot_sigPCA_histogram(
  iris_sig,
  bins = 4
)

## ----scores, fig.cap="PCA scores for the iris observations. Species labels were not used by sigPCA."----
iris_pca <- stats::prcomp(x, center = TRUE, scale. = TRUE)
variance_explained <- 100 * iris_pca$sdev^2 / sum(iris_pca$sdev^2)

score_data <- data.frame(
  PC1 = iris_pca$x[, 1],
  PC2 = iris_pca$x[, 2],
  species = iris_data$Species[complete_rows]
)

ggplot2::ggplot(score_data) +
  ggplot2::aes(x = PC1, y = PC2, colour = species) +
  ggplot2::geom_point(alpha = 0.75, size = 2) +
  ggplot2::labs(
    x = sprintf("PC1 (%.1f%% of variance)", variance_explained[1]),
    y = sprintf("PC2 (%.1f%% of variance)", variance_explained[2]),
    colour = "Species"
  ) +
  ggplot2::theme_minimal()

## ----loadings-----------------------------------------------------------------
round(iris_pca$rotation[, 1, drop = FALSE], 3)

