| Type: | Package |
| Title: | Chic and Sleek Functions for Beautiful Statisticians |
| Version: | 0.1.3 |
| Description: | Because your linear models deserve better than console output. A sleek color palette and kable styling to make your regression results look sharper than they are. Includes support for Partial Least Squares (PLS) regression via both the SVD and NIPALS algorithms, along with a unified interface for model fitting and fabulous LaTeX and console output formatting. Regression diagnostics include the standard residual plots, marginal model plots, a table of unusual observations and variance inflation factors. LaTeX tables also preview as HTML when R Markdown chunks are run interactively. See the package website at https://finitesample.space/snazzier. |
| License: | MIT + file LICENSE |
| URL: | https://finitesample.space/snazzier, https://detectivefierce.github.io/snazzieR/, https://github.com/DetectiveFierce/snazzieR |
| BugReports: | https://github.com/DetectiveFierce/snazzieR/issues |
| Depends: | R (≥ 4.1.0) |
| Imports: | ggplot2 (≥ 3.5.0), graphics, grDevices, grid, htmltools, kableExtra, knitr, stats |
| Suggests: | rmarkdown, testthat (≥ 3.0.0), withr |
| VignetteBuilder: | knitr |
| Config/testthat/edition: | 3 |
| Encoding: | UTF-8 |
| Language: | en-US |
| LazyData: | true |
| Config/roxygen2/version: | 8.1.1 |
| NeedsCompilation: | no |
| Packaged: | 2026-11-16 19:41:44 UTC; shared-psychosis |
| Author: | Aidan J. Wagner [aut, cre] |
| Maintainer: | Aidan J. Wagner <JesusButForGayPeople@proton.me> |
| Repository: | CRAN |
| Date/Publication: | 2026-11-16 20:20:02 UTC |
Generate a Summary Table for ANOVA Results
Description
This function creates a summary table for ANOVA results, including degrees of freedom, sum of squares, mean squares, F-values, and p-values. The table can be output as either LaTeX (for PDF reports) or plain text (for console viewing).
Usage
ANOVA.summary.table(model, title = "ANOVA Summary", latex = TRUE, caption)
Arguments
model |
A model object for which ANOVA results are computed (e.g., output from 'lm()' or 'aov()'). |
title |
A character string used as the table's title (its LaTeX
caption). Defaults to |
latex |
Logical; if 'TRUE', returns a LaTeX-formatted table using 'kableExtra'. If 'FALSE', prints a plain-text version to the console. |
caption |
Deprecated alias for |
Value
If 'latex = TRUE', a LaTeX-formatted table object (of class
"snazzieR_table", which also previews when a chunk is run
interactively; see snazzieR_table). If 'latex = FALSE', prints the summary table and returns it (invisibly).
Examples
# Fit a linear model
model <- lm(mpg ~ wt + hp, data = mtcars)
# Generate a plain-text ANOVA summary table
ANOVA.summary.table(model, title = "ANOVA Summary", latex = FALSE)
Partial Least Squares Regression via NIPALS (Internal)
Description
This function is called internally by pls.regression and is not intended
to be used directly. Use pls.regression(..., calc.method = "NIPALS") instead.
Performs Partial Least Squares (PLS) regression using the NIPALS (Nonlinear Iterative Partial Least Squares) algorithm. This method estimates the latent components (scores, loadings, weights) by iteratively updating the X and Y score directions until convergence. It is suitable for cases where the number of predictors is large or predictors are highly collinear.
Usage
NIPALS.pls(x, y, n.components = NULL)
Arguments
x |
A numeric matrix or data frame of predictors (X). Should have dimensions n × p. |
y |
A numeric matrix or data frame of response variables (Y). Should have dimensions n × q. |
n.components |
Integer specifying the number of PLS components to extract. If NULL, it defaults to |
Details
The algorithm standardizes both x and y using z-score normalization. It then performs the following for each
of the n.components latent variables:
Initializes a random response score vector
u.Iteratively:
Updates the X weight vector
w = E^\top u, normalized.Computes the X score
t = E w, normalized.Updates the Y loading
q = F^\top t, normalized.Updates the response score
u = F q.Repeats until
tconverges below a tolerance threshold.
Computes scalar regression coefficient
b = t^\top u.Deflates residual matrices
EandFto remove current component contribution.
After component extraction, the final regression coefficient matrix B_{original} is computed and rescaled to the original
data units. Explained variance is also computed component-wise and cumulatively.
Value
A list with the following elements:
- model.type
Character string indicating the model type ("PLS Regression").
- T
Matrix of X scores (n × H).
- U
Matrix of Y scores (n × H).
- W
Matrix of X weights (p × H).
- C
Matrix of normalized Y weights (q × H).
- P_loadings
Matrix of X loadings (p × H).
- Q_loadings
Matrix of Y loadings (q × H).
- B_vector
Vector of regression scalars (length H), one for each component.
- coefficients
Matrix of regression coefficients in original data scale (p × q).
- intercept
Vector of intercepts (length q). Always zero here due to centering.
- X_explained
Percent of total X variance explained by each component.
- Y_explained
Percent of total Y variance explained by each component.
- X_cum_explained
Cumulative X variance explained.
- Y_cum_explained
Cumulative Y variance explained.
References
Wold, H., & Lyttkens, E. (1969). Nonlinear iterative partial least squares (NIPALS) estimation procedures. Bulletin of the International Statistical Institute, 43, 29–51.
Examples
## Not run:
X <- matrix(rnorm(100 * 10), 100, 10)
Y <- matrix(rnorm(100 * 2), 100, 2)
model <- pls.regression(X, Y, n.components = 3, calc.method = "NIPALS")
model$coefficients
## End(Not run)
Partial Least Squares Regression via SVD (Internal)
Description
This function is called internally by pls.regression and is not intended
to be used directly. Use pls.regression(..., calc.method = "SVD") instead.
Performs Partial Least Squares (PLS) regression using the Singular Value Decomposition (SVD)
of the cross-covariance matrix. This method estimates the latent components by identifying directions
in the predictor and response spaces that maximize their covariance, using the leading singular vectors
of the matrix R = X^\top Y.
Usage
SVD.pls(x, y, n.components = NULL)
Arguments
x |
A numeric matrix or data frame of predictors (X). Should have dimensions n × p. |
y |
A numeric matrix or data frame of response variables (Y). Should have dimensions n × q. |
n.components |
Integer specifying the number of PLS components to extract. If NULL, defaults to |
Details
The algorithm begins by z-scoring both x and y (centering and scaling to unit variance).
The initial residual matrices are set to the scaled values: E = X_scaled, F = Y_scaled.
For each component h = 1, ..., H:
Compute the cross-covariance matrix
R = E^\top F.Perform SVD on
R = U D V^\top.Extract the first singular vectors:
w = U[,1],q = V[,1].Compute scores:
t = E w(normalized),u = F q.Compute loadings:
p = E^\top t, regression scalarb = t^\top u.Deflate residuals:
E \gets E - t p^\top,F \gets F - b t q^\top.
After all components are extracted, a post-processing step removes components with zero regression
weight. The scaled regression coefficients are computed using the Moore–Penrose pseudoinverse of the
loading matrix P, and then rescaled to the original variable units.
Value
A list containing:
- model.type
Character string indicating the model type ("PLS Regression").
- T
Matrix of predictor scores (n × H).
- U
Matrix of response scores (n × H).
- W
Matrix of predictor weights (p × H).
- C
Matrix of normalized response weights (q × H).
- P_loadings
Matrix of predictor loadings (p × H).
- Q_loadings
Matrix of response loadings (q × H).
- B_vector
Vector of scalar regression weights (length H).
- coefficients
Matrix of final regression coefficients in the original scale (p × q).
- intercept
Vector of intercepts (length q). All zeros due to centering.
- X_explained
Percent of total X variance explained by each component.
- Y_explained
Percent of total Y variance explained by each component.
- X_cum_explained
Cumulative X variance explained.
- Y_cum_explained
Cumulative Y variance explained.
References
Abdi, H., & Williams, L. J. (2013). Partial least squares methods: Partial least squares correlation and partial least square regression. Methods in Molecular Biology (Clifton, N.J.), 930, 549–579. doi:10.1007/978-1-62703-059-5_23
de Jong, S. (1993). SIMPLS: An alternative approach to partial least squares regression. Chemometrics and Intelligent Laboratory Systems, 18(3), 251–263. doi:10.1016/0169-7439(93)85002-X
Examples
## Not run:
X <- matrix(rnorm(100 * 10), 100, 10)
Y <- matrix(rnorm(100 * 2), 100, 2)
model <- pls.regression(X, Y, n.components = 3, calc.method = "SVD")
model$coefficients
## End(Not run)
Variance Inflation Factor Table
Description
Computes variance inflation factors (VIFs) for the terms of a regression to diagnose multicollinearity, and returns them as a LaTeX table (for PDF reports) or plain text (for the console), like the other snazzieR summary tables. car is not required.
Usage
VIF.table(
model,
title = "Variance Inflation Factors",
latex = TRUE,
cols = "all",
moderate = 5,
severe = 10,
digits = 4
)
Arguments
model |
A fitted |
title |
Table title (its LaTeX caption). Defaults to
|
latex |
Logical; if |
cols |
Columns to show: |
moderate, severe |
VIF cutoffs for flagging moderate and severe multicollinearity. Default 5 and 10. |
digits |
Number of significant digits shown. Defaults to 4. |
Details
VIFs are computed from the correlation matrix of the estimated coefficients,
exactly as car::vif() does, so they are valid for weighted
lm fits and for glm fits. For a numeric predictor,
\mathrm{VIF}_j = 1/(1 - R^2_j), where R^2_j is from regressing
that predictor on all the others.
The available columns are:
- VIF
The variance inflation factor. Terms with more than one coefficient (factors,
poly(), splines) have no ordinary VIF, so their VIF is reported as(\textrm{adj. GVIF})^2, which is on the same scale and equals the ordinary VIF for one-df terms.- 1/VIF
The tolerance,
1 - R^2_j.- GVIF
The generalized VIF of Fox and Monette (1992); equal to the VIF for one-df terms.
- adj. GVIF
\mathrm{GVIF}^{1/(2\,\mathrm{Df})}, comparable across terms with different degrees of freedom. Each cell also shows the term's degrees of freedom, e.g.1.547 (df = 2).
The Term and Flag columns are always shown. Terms are flagged
moderate when the VIF exceeds moderate (default 5) and
severe when it exceeds severe (default 10). Rows are sorted
from the highest VIF to the lowest. Aliased (perfectly collinear)
coefficients are dropped and listed in the notes under the table.
Value
If latex = TRUE, a LaTeX table of class
"snazzieR_table" (see snazzieR_table for interactive
previews). If latex = FALSE, the table is printed and a data frame
of the shown columns, one row per term, is returned invisibly.
References
Fox, J. and Monette, G. (1992). Generalized collinearity diagnostics. Journal of the American Statistical Association, 87, 178–183.
See Also
unusual.points.table, model.summary.table
Examples
model <- lm(mpg ~ wt + hp + disp + qsec, data = mtcars)
VIF.table(model, latex = FALSE)
# Factors get generalized VIFs
VIF.table(lm(mpg ~ wt + hp + factor(cyl), data = mtcars), latex = FALSE)
# Only some columns
VIF.table(model, latex = FALSE, cols = c("VIF", "1/VIF"))
# LaTeX table for a PDF report
tbl <- VIF.table(model, title = "Collinearity Check")
Display a Color Reference Palette
Description
This function generates a plot displaying a predefined color palette with color codes for easy reference. The palette includes shades of Red, Orange, Yellow, Green, Blue, Purple, and Grey.
Usage
color.ref()
Details
Value
Called for its side effect of drawing the color palette; returns NULL invisibly.
Examples
color.ref()
SnazzieR Color Palette
Description
A collection of named hex colors grouped by hue and tone.
Each color is available as an exported object (e.g., Red, Dark.Red).
Usage
color.list
Format
Each color is a character string representing a hex code.
Details
| Name | Hex | Swatch | Name | Hex | Swatch | |
| Deep.Red | #590D21 | | Deep.Green | #304011 | |
|
| Dark.Red | #9F193D | | Dark.Green | #54711E | |
|
| Red | #C31E4A | | Green | #83B02F | |
|
| Light.Red | #E66084 | | Light.Green | #ABD45E | |
|
| Pale.Red | #F1A7BB | | Pale.Green | #C4E18E | |
|
| Deep.Orange | #6F4B0B | | Deep.Blue | #002429 | |
|
| Dark.Orange | #A77011 | | Dark.Blue | #004852 | |
|
| Orange | #E99F1F | | Blue | #008C9E | |
|
| Light.Orange | #F0BF6A | | Light.Blue | #1FE5FF | |
|
| Pale.Orange | #F4CF90 | | Pale.Blue | #85F1FF | |
|
| Deep.Yellow | #9D7F06 | | Deep.Purple | #271041 | |
|
| Dark.Yellow | #CEA708 | | Dark.Purple | #4E2183 | |
|
| Yellow | #E8D206 | | Purple | #743496 | |
|
| Light.Yellow | #FFE373 | | Light.Purple | #A06CDA | |
|
| Pale.Yellow | #FFF8DC | | Pale.Purple | #CAADEB | |
|
| Deep.Grey | #151315 | | ||||
| Dark.Grey | #403A3F | | ||||
| Grey | #6F646C | | ||||
| Light.Grey | #9E949B | | ||||
| Pale.Grey | #CFC9CD | |
See Also
Create K-Fold Cross Validation Splits
Description
Create K-Fold Cross Validation Splits
Usage
create_kfold_splits(data, k = 5, seed = NULL)
Arguments
data |
A data frame containing the dataset |
k |
Number of folds (default: 5) |
seed |
Random seed for reproducibility (optional) |
Value
A list containing fold assignments for each observation
Compute Cross-Validated Mean Squared Error
Description
Computes mean squared error via k-fold cross-validation for a fixed lambda value.
Usage
cv.mse(x, y, lambda, folds = 5, fold_indices = NULL)
Arguments
x |
A standardized design matrix (n × p) |
y |
A centered response vector (n × 1) |
lambda |
A non-negative regularization scalar |
folds |
Number of cross-validation folds (default: 5) |
Value
A numeric scalar representing the CV-MSE
Snazzy Regression Diagnostic Plots
Description
Draws the four standard diagnostic plots for a linear model (the same
panels as plot(model) for an lm fit) as a 2 x 2 grid of
ggplot2 plots styled with snazzieR.theme().
Usage
diagnostics.plots(model, id.n = 3, cook.levels = c(0.5, 1))
## S3 method for class 'snazzieR_plot_grid'
print(x, ...)
Arguments
model |
A fitted |
id.n |
Number of extreme points to label in each panel (default 3). |
cook.levels |
Cook's distance levels drawn as contours in the
leverage panel (default |
x |
A |
... |
Unused. |
Details
The panels reproduce plot.lm with its default
which = c(1, 2, 3, 5):
-
Residuals vs Fitted: residuals against fitted values with a
lowesssmooth (f = 2/3,iter = 3) and a reference line at zero. -
Q-Q Residuals: standardized residuals against theoretical normal quantiles (
ppoints) with the line through the first and third quartiles, as drawn byqqline. -
Scale-Location:
\sqrt{|\textrm{standardized residuals}|}against fitted values with a lowess smooth. -
Residuals vs Leverage: standardized residuals against leverage (hat values), with Cook's distance contours at
cook.levels.
As in plot.lm, the id.n most extreme observations in each
panel are labelled with their observation numbers (placed so that labels do
not overlap), observations with zero weight are
dropped, and observations with leverage one are omitted from the
standardized-residual panels.
Value
An object of class "snazzieR_plot_grid": a list whose
plots element holds the four ggplot objects (named
residuals.fitted, qq, scale.location and
residuals.leverage). Printing it draws the 2 x 2 grid; individual
panels can be printed or modified on their own.
See Also
Examples
model <- lm(mpg ~ wt + hp, data = mtcars)
diagnostics.plots(model)
# A single panel
diagnostics.plots(model)$plots$qq
Summarize Eigenvalues and Eigenvectors of a Covariance Matrix
Description
This function computes the eigenvalues and eigenvectors of a given covariance matrix, ensures sign consistency in the eigenvectors, and outputs either a LaTeX table or plaintext summary displaying the results.
Usage
eigen.summary(
cov.matrix,
title = "Eigenvectors of Covariance Matrix",
latex = TRUE,
caption
)
Arguments
cov.matrix |
A square numeric matrix representing the covariance matrix. |
title |
A character string used as the table's title (default: "Eigenvectors of Covariance Matrix"). |
latex |
A logical indicating whether to output LaTeX table (default: TRUE). If FALSE, prints as plain text. |
caption |
Deprecated alias for |
Value
A LaTeX formatted table of class "snazzieR_table" (if latex = TRUE; see
snazzieR_table for interactive previews) or plaintext console output (if latex = FALSE).
Examples
cov_matrix <- matrix(c(4, 2, 2, 3), nrow = 2)
eigen.summary(cov_matrix, title = "Eigenvalues and Eigenvectors", latex = FALSE)
Fit Ridge Regression with Closed-Form Solution
Description
Computes ridge regression coefficients and standard errors using the closed-form solution:
\hat{\beta} = (X^T X + \lambda I)^{-1} X^T y
Usage
fit.ridge(x, y, lambda)
Arguments
x |
A standardized design matrix (n × p) |
y |
A centered response vector (n × 1) |
lambda |
A non-negative regularization scalar |
Value
A list containing:
- coefficients
Ridge regression coefficients (length p)
- std_errors
Standard errors of the coefficients (length p)
Format PLS Model Output as LaTeX or Console Tables
Description
Formats and displays Partial Least Squares (PLS) model output from pls.regression()
as either LaTeX tables (for PDF rendering) or console-friendly output.
Usage
## S3 method for class 'pls'
format(x, ..., include.scores = TRUE, latex = FALSE)
Arguments
x |
A list returned by |
... |
Further arguments passed to or from methods (unused). |
include.scores |
Logical. Whether to include score matrices (T and U). Default is |
latex |
Logical. If |
Value
When latex = TRUE, returns a knitr::asis_output object (LaTeX code) of class
"snazzieR_table" (see snazzieR_table for interactive previews). When FALSE, prints formatted tables to console.
Perform K-Fold Cross Validation
Description
Perform K-Fold Cross Validation
Usage
kfold_cross_validation(
data,
formula,
model_function,
predict_function = predict,
metric_function = NULL,
k = 5,
seed = NULL,
...
)
Arguments
data |
A data frame containing the dataset |
formula |
A formula specifying the model (e.g., y ~ x1 + x2) |
model_function |
Function to fit the model (e.g., lm, glm) |
predict_function |
Function to make predictions (default: predict) |
metric_function |
Function to calculate performance metric |
k |
Number of folds (default: 5) |
seed |
Random seed for reproducibility (optional) |
... |
Additional arguments passed to model_function |
Value
A list containing fold results and summary statistics
Snazzy Marginal Model Plots
Description
Draws marginal model plots for a linear model, the same plots as
car::mmps(model), as a single faceted ggplot2 plot styled with
snazzieR.theme(). Only ggplot2 is required; car is
not needed.
Usage
marginal.model.plots(model, fitted = TRUE, ncol = NULL, title = NULL)
Arguments
model |
A fitted |
fitted |
Logical; include the panel against the fitted values
(default |
ncol |
Number of panel columns. Defaults to car's layout. |
title |
Plot title. Defaults to |
Details
For each eligible term in the model, and for the fitted values, the response is plotted against that variable together with two smooths:
- Data
(solid) a loess smooth of the response on the variable;
- Model
(dashed) a loess smooth of the model's fitted values on the variable.
If the model is adequate the two smooths should agree. The smooths match
those drawn by car: loess with
span = 2/3, degree = 1, family = "symmetric" and four
robustness iterations, evaluated at 50 equally spaced points.
As in car::mmps(), factors and interaction terms are skipped, and
matrix terms such as poly() or spline bases are replaced by their
fitted linear combination (predict(model, type = "terms")). The
panel layout follows car's defaults (e.g. 3 x 3 for 7 to 9 panels).
Value
A ggplot object. Its title is drawn as the legend title,
so the Data/Model key sits to the right of it.
See Also
Examples
model <- lm(mpg ~ wt + hp + qsec, data = mtcars)
marginal.model.plots(model)
# Label which model the plots belong to
marginal.model.plots(model, title = "Marginal Model Plots: Fuel Economy")
Generate a Model Equation from a Linear Model
Description
This function extracts and formats the equation from a linear model object. It includes an option to return the equation as a LaTeX-formatted string or print it to the console.
Usage
model.equation(model, latex = TRUE)
Arguments
model |
A linear model object (e.g., output from 'lm()'). |
latex |
A logical value indicating whether to return a LaTeX-formatted equation (default: TRUE). If FALSE, the equation is printed to the console. |
Value
If 'latex' is TRUE, the equation is returned as LaTeX code using 'knitr::asis_output()'. If FALSE, the equation is printed to the console.
Examples
# Fit a linear model
model <- lm(mpg ~ wt + hp, data = mtcars)
# Get LaTeX equation
model.equation(model)
# Print equation to console
model.equation(model, latex = FALSE)
Generate a Summary Table for a Linear Model
Description
This function creates a summary table for a linear model, including estimated coefficients, standard errors, p-values with significance codes, and model statistics such as MSE and R-squared. The table can be output as either LaTeX (for PDF reports) or plain text (for console viewing).
Usage
model.summary.table(model, title = "Model Summary", latex = TRUE, caption)
Arguments
model |
A linear model object (typically the result of 'lm()'). |
title |
A character string used as the table's title (its LaTeX
caption). Defaults to |
latex |
Logical; if 'TRUE' (default), returns a LaTeX-formatted table using 'kableExtra'. If 'FALSE', prints plain-text summary tables to the console. |
caption |
Deprecated alias for |
Value
If 'latex = TRUE', returns a LaTeX-formatted 'kableExtra' table object
(of class "snazzieR_table", which also previews nicely when a
chunk is run interactively; see snazzieR_table).
If 'latex = FALSE', prints formatted summary tables to the console and returns the underlying data frame.
Examples
# Fit a linear model
model <- lm(mpg ~ wt + hp, data = mtcars)
# Print a plain-text version to the console
model.summary.table(model, title = "Linear Model Summary", latex = FALSE)
Optimize Lambda Using Cross-Validation
Description
Searches the lambda range to minimize CV-MSE using Brent's method via 'optimize()'.
Usage
optimize.cv.lambda(x, y, lambda.range, folds)
Arguments
x |
A standardized design matrix (n × p) |
y |
A centered response vector (n × 1) |
lambda.range |
A numeric vector of length 2 specifying the search interval |
folds |
Number of cross-validation folds |
Value
A list containing:
- minimum
Optimal lambda value
- objective
Minimum CV-MSE achieved
- trace
Data frame with lambda and CV-MSE pairs
Partial Least Squares (PLS) Regression Interface
Description
Performs Partial Least Squares (PLS) regression using either the NIPALS or SVD algorithm for component extraction.
This is the main user-facing function for computing PLS models. Internally, it delegates to either NIPALS.pls() or SVD.pls().
Usage
pls.regression(x, y, n.components = NULL, calc.method = c("SVD", "NIPALS"))
Arguments
x |
A numeric matrix or data frame of predictor variables (X), with dimensions n × p. |
y |
A numeric matrix or data frame of response variables (Y), with dimensions n × q. |
n.components |
Integer specifying the number of latent components (H) to extract. If NULL, defaults to the rank of |
calc.method |
Character string indicating the algorithm to use. Must be either |
Details
This function provides a unified interface for Partial Least Squares regression. Based on the value of calc.method,
it computes latent variables using either:
-
"SVD"— A direct method using the singular value decomposition of the cross-covariance matrix (X^\top Y). -
"NIPALS"— An iterative method that alternately estimates predictor and response scores until convergence.
The outputs from both methods include scores, weights, loadings, regression coefficients, and explained variance.
Value
A list (from either SVD.pls() or NIPALS.pls()) containing:
- model.type
Character string ("PLS Regression").
- T, U
Score matrices for X and Y.
- W, C
Weight matrices for X and Y.
- P_loadings, Q_loadings
Loading matrices.
- B_vector
Component-wise regression weights.
- coefficients
Final regression coefficient matrix (rescaled).
- intercept
Intercept vector (typically zero due to centering).
- X_explained, Y_explained
Variance explained by each component.
- X_cum_explained, Y_cum_explained
Cumulative variance explained.
References
Abdi, H., & Williams, L. J. (2013). Partial least squares methods: Partial least squares correlation and partial least square regression. Methods in Molecular Biology (Clifton, N.J.), 930, 549–579. doi:10.1007/978-1-62703-059-5_23
de Jong, S. (1993). SIMPLS: An alternative approach to partial least squares regression. Chemometrics and Intelligent Laboratory Systems, 18(3), 251–263. doi:10.1016/0169-7439(93)85002-X
See Also
Examples
## Not run:
X <- matrix(rnorm(100 * 10), 100, 10)
Y <- matrix(rnorm(100 * 2), 100, 2)
# Using SVD (default)
model1 <- pls.regression(X, Y, n.components = 3)
# Using NIPALS
model2 <- pls.regression(X, Y, n.components = 3, calc.method = "NIPALS")
## End(Not run)
Format PLS Model Output as LaTeX Tables
Description
Formats and displays Partial Least Squares (PLS) model output from pls.regression()
as LaTeX tables for PDF rendering.
Usage
pls.summary(x, ..., include.scores = TRUE)
Arguments
x |
A list returned by |
... |
Further arguments passed to or from methods (unused). |
include.scores |
Logical. Whether to include score matrices (T and U). Default is |
Value
Returns a knitr::asis_output object (LaTeX code) for PDF rendering
It has class "snazzieR_table", so it also previews when a chunk is run interactively
(see snazzieR_table).
Examples
# Load example data
data(mtcars)
# Prepare data for PLS regression
X <- mtcars[, c("wt", "hp", "disp")]
Y <- mtcars[, "mpg", drop = FALSE]
# Fit PLS model with 2 components
pls.fit <- pls.regression(X, Y, n.components = 2)
# Print a LaTeX-formatted summary
pls.summary(pls.fit, include.scores = FALSE)
Predict Method for Ridge Model Objects
Description
Predicts response values for new data using a fitted ridge model.
Usage
## S3 method for class 'ridge.model'
predict(object, newdata = NULL, ...)
Arguments
object |
A 'ridge.model' object |
newdata |
A data frame or matrix containing new predictor values |
... |
Additional arguments (not used) |
Value
A numeric vector of predicted values
Print Method for Ridge Model Objects
Description
Prints a summary of the ridge model fit.
Usage
## S3 method for class 'ridge.model'
print(x, ...)
Arguments
x |
A 'ridge.model' object |
... |
Additional arguments (not used) |
Ridge Regression with Automatic Lambda Selection
Description
Performs ridge regression with automatic selection of the optimal regularization parameter 'lambda' by minimizing k-fold cross-validated mean squared error (CV-MSE) using Brent's method. Supports both formula and matrix interfaces.
Usage
ridge.regression(
formula = NULL,
data = NULL,
x = NULL,
y = NULL,
lambda.range = c(1e-04, 100),
folds = 5,
...
)
Arguments
formula |
A model formula like 'y ~ x1 + x2'. Mutually exclusive with 'x'/'y'. |
data |
A data frame containing all variables used in the formula. |
x |
A numeric matrix of predictor variables (n × p). Used when formula is not provided. |
y |
A numeric vector of response variables (n × 1). Used when formula is not provided. |
lambda.range |
A numeric vector of length 2 specifying the interval for lambda optimization. Default: 'c(1e-4, 100)'. |
folds |
An integer specifying the number of cross-validation folds. Default: '5'. |
... |
Additional arguments passed to internal methods. |
Details
This function implements ridge regression with automatic hyperparameter tuning. The algorithm:
Standardizes predictor variables (centers and scales)
Centers the response variable
Uses k-fold cross-validation to find the optimal lambda
Fits the final model with the optimal lambda
Returns a structured object for prediction and analysis
The ridge regression solution is computed using the closed-form formula:
\hat{\beta} = (X^T X + \lambda I)^{-1} X^T y
Value
A 'ridge.model' object containing:
- coefficients
Final ridge coefficients (no intercept)
- std_errors
Standard errors of the coefficients
- intercept
Intercept term (from y centering)
- optimal.lambda
Best lambda minimizing CV-MSE
- cv.ms
Minimum CV-MSE achieved
- cv.results
Data frame with lambda and CV-MSE pairs
- x.scale
Standardization info: mean and sd for each predictor
- y.center
Centering constant for y
- fitted.values
Final model predictions on training data
- residuals
Training residuals (y - fitted)
- call
Matched call (for debugging)
- method
Always "ridge"
- folds
Number of CV folds used
- formula
Stored if formula interface used
- terms
Stored if formula interface used
References
Hoerl, A. E., & Kennard, R. W. (1970). Ridge regression: Biased estimation for nonorthogonal problems. Technometrics, 12(1), 55-67.
See Also
Examples
## Not run:
# Formula interface
model1 <- ridge.regression(mpg ~ wt + hp + disp, data = mtcars)
# Matrix interface
X <- as.matrix(mtcars[, c("wt", "hp", "disp")])
y <- mtcars$mpg
model2 <- ridge.regression(x = X, y = y)
# Custom lambda range and folds
model3 <- ridge.regression(mpg ~ .,
data = mtcars,
lambda.range = c(0.1, 10), folds = 10
)
## End(Not run)
Format Ridge Model Output as LaTeX Tables
Description
Formats and displays ridge regression model output from ridge.regression()
as LaTeX tables for PDF rendering or plain text for console viewing.
Usage
ridge.summary(x, ..., include.cv.trace = TRUE, latex = TRUE)
Arguments
x |
A ridge model object returned by |
... |
Further arguments passed to or from methods (unused). |
include.cv.trace |
Logical. Whether to include cross-validation trace information. Default is |
latex |
Logical; if |
Value
If latex = TRUE, returns a knitr::asis_output object (LaTeX code) for PDF rendering
It has class "snazzieR_table", so it also previews when a chunk is run interactively
(see snazzieR_table).
If latex = FALSE, prints formatted summary tables to the console and returns the underlying data frames.
Examples
# Load example data
data(mtcars)
# Fit ridge regression model
ridge.fit <- ridge.regression(mpg ~ wt + hp + disp, data = mtcars)
# Print a LaTeX-formatted summary
ridge.summary(ridge.fit, include.cv.trace = FALSE)
# Print a plain-text summary
ridge.summary(ridge.fit, include.cv.trace = FALSE, latex = FALSE)
A Custom ggplot2 Theme for Publication-Ready Plots
Description
This theme provides a clean, polished look for ggplot2 plots, with a focus on readability and aesthetics. It includes a custom color palette and formatting for titles, axes, and legends.
Usage
snazzieR.theme()
Value
A ggplot2 theme object.
See Also
Examples
library(ggplot2)
set.seed(123)
chains.df <- data.frame(
Iteration = 1:500,
alpha.1 = cumsum(rnorm(500, mean = 0.01, sd = 0.2)) + rnorm(1, 5, 0.2),
alpha.2 = cumsum(rnorm(500, mean = 0.005, sd = 0.2)) + rnorm(1, 5, 0.2),
alpha.3 = cumsum(rnorm(500, mean = 0.000, sd = 0.2)) + rnorm(1, 5, 0.2),
alpha.4 = cumsum(rnorm(500, mean = -0.005, sd = 0.2)) + rnorm(1, 5, 0.2),
alpha.5 = cumsum(rnorm(500, mean = -0.01, sd = 0.2)) + rnorm(1, 5, 0.2)
)
chain.colors <- c("Chain 1" = Red, "Chain 2" = Orange, "Chain 3" = Yellow,
"Chain 4" = Green, "Chain 5" = Blue)
ggplot(chains.df, aes(x = Iteration)) +
geom_line(aes(y = alpha.1, color = "Chain 1"), linewidth = 1.2) +
geom_line(aes(y = alpha.2, color = "Chain 2"), linewidth = 1.2) +
geom_line(aes(y = alpha.3, color = "Chain 3"), linewidth = 1.2) +
geom_line(aes(y = alpha.4, color = "Chain 4"), linewidth = 1.2) +
geom_line(aes(y = alpha.5, color = "Chain 5"), linewidth = 1.2) +
labs(x = "Iteration", y = expression(alpha),
title = expression("Traceplot for " ~ alpha)) +
scale_color_manual(values = chain.colors, name = "Chains") +
snazzieR.theme()
Interactive Previews for snazzieR Tables
Description
The LaTeX tables returned by model.summary.table,
ANOVA.summary.table, eigen.summary,
pls.summary, ridge.summary and
format.pls carry the class "snazzieR_table".
This lets them show a readable preview when a chunk is run interactively
(for example with the play button in the RStudio or Positron editor),
while knitting produces exactly the same LaTeX as before.
Usage
## S3 method for class 'snazzieR_table'
print(x, ...)
## S3 method for class 'snazzieR_table'
knit_print(x, options = list(), ...)
Arguments
x |
A |
... |
Further arguments passed to the underlying print method. |
options |
Chunk options, passed on by knitr. |
Details
When a document is being knitted, printing is handed straight to the
underlying knitr/kableExtra method, so compiled output does
not change. Outside of knitting, the preview style is controlled by the
option snazzieR.preview:
"auto"(default) An HTML preview in RStudio or Positron, a plain-text preview in other interactive sessions, and the raw LaTeX in non-interactive sessions.
"html"Always render an HTML preview.
"text"Always print a plain-text preview.
"latex"Always print the raw LaTeX source.
Value
x, invisibly.
Examples
model <- lm(mpg ~ wt + hp, data = mtcars)
tbl <- model.summary.table(model, title = "Fuel Economy")
# Force a plain-text preview
old <- options(snazzieR.preview = "text")
print(tbl)
options(old)
Table of Unusual Observations in a Regression
Description
Identifies the observations of a fitted regression that should be investigated – high-leverage points, outliers, influential points and bad leverage points – and returns them in a table, as LaTeX (for PDF reports) or plain text (for the console), like the other snazzieR summary tables.
Usage
unusual.points.table(
model,
title = "Unusual Observations",
latex = TRUE,
id = NULL,
data = NULL,
leverage.cutoff = NULL,
residual.cutoff = 2,
cook.cutoff = NULL,
flag = c("leverage", "outlier", "influential"),
n.max = NULL,
digits = 4
)
Arguments
model |
A fitted |
title |
Table title (its LaTeX caption). Defaults to
|
latex |
Logical; if |
id |
Optional labels to identify observations: either the name of a
column in |
data |
The data frame the model was fitted to. Only needed when
|
leverage.cutoff |
Leverage threshold. Defaults to |
residual.cutoff |
Threshold for |
cook.cutoff |
Cook's distance threshold. Defaults to |
flag |
Which criteria make an observation unusual: any of
|
n.max |
Maximum number of observations to list (default |
digits |
Number of significant digits shown. Defaults to 4. |
Details
Diagnostics are computed with hatvalues,
rstandard and cooks.distance, so the function works for any
lm fit (including weighted fits, factors, transformed variables and
missing values) and for glm fits (using deviance residuals).
Observations with zero weight are excluded, as in plot.lm.
An observation is listed if it meets at least one of these criteria (defaults follow Sheather, A Modern Approach to Regression with R):
- High leverage
h_{ii} > 2(p+1)/n, twice the average leverage, wherep+1is the number of estimated coefficients.- Outlier
|r_i| > 2, wherer_iis the standardized residual. (For large data sets a cutoff of 4 may be more appropriate.)- Influential
Cook's distance
D_i > 4/(n-2).- Bad leverage
both high leverage and an outlier.
For each flagged point the table reports its observed and fitted response, leverage, standardized residual, Cook's distance and flags. A legend under the table explains the flags and compares the number of outliers with the number expected by chance.
Value
If latex = TRUE, a LaTeX table of class
"snazzieR_table" (see snazzieR_table for interactive
previews). If latex = FALSE, the table is printed and a data frame
with one row per flagged observation (sorted by Cook's distance) is
returned invisibly. Its "cutoffs" attribute holds the thresholds
used.
See Also
diagnostics.plots, model.summary.table
Examples
model <- lm(mpg ~ wt + hp, data = mtcars)
# Plain-text table, labelling cars by name
unusual.points.table(model, latex = FALSE, id = rownames(mtcars))
# Only the 3 most influential, ignoring points flagged by Cook's D alone
unusual.points.table(model, latex = FALSE, id = rownames(mtcars),
flag = c("leverage", "outlier"), n.max = 3)
# LaTeX table for a PDF report
tbl <- unusual.points.table(model, title = "Cars to Investigate")