That's an interesting and quite advanced request! Moving from "sum of squares" (which underlies standard PCA and variance maximization) to "modulus" often implies a shift towards using the L1 norm (sum of absolute values) instead of the L2 norm (sum of squares).
This is the core idea behind Sparse PCA or variations of Robust PCA. Standard PCA inherently maximizes variance, which is based on the L2 norm. Replacing this fundamental objective requires a different algorithmic approach, not just a parameter tweak to prcomp or psych::principal.
There isn't a single standard function that directly swaps the L2 objective for an L1 objective within PCA calculations in base R or common packages like psych. However, the sparsepca package is designed precisely for this purpose.
Here's how you can adapt the function to use Sparse PCA (which uses L1 norm concepts for sparsity control) and explain the differences:
Understanding the Shift:
- Standard PCA (Sum of Squares/L2 Norm): Aims to find orthogonal components that explain the maximum variance. Variance is calculated using squared deviations (∑(xi−xˉ)2).
- Sparse PCA (Modulus/L1 Norm): Aims to find components that maximize variance while also enforcing sparsity in the loadings. Sparsity means that many of the loadings (coefficients connecting original variables to the components) are zero or close to zero. This often makes the components easier to interpret as they rely on fewer original variables. The control parameter (
alpha in the sparsepca package) influences how sparse the loadings become.
Modified Function using sparsepca:
This function will use the sparsepca package. You'll need to install it first:
install.packages("sparsepca")
install.packages("rgl") (if you haven't already for 3D plotting)
# Load necessary packages
# install.packages("sparsepca")
# install.packages("rgl")
require(sparsepca)
require(rgl)
#' Performs Sparse PCA (L1 norm optimization for sparsity) and Visualization
#'
#' This function implements Sparse PCA, which seeks principal components that
#' explain variance but also have sparse loadings (many loadings are zero).
#' It uses the L1 norm concept indirectly via sparsity control parameters.
#' This is fundamentally different from standard PCA's objective of maximizing variance
#' based solely on the L2 norm (sum of squares).
#'
#' @param rawdata A data frame or matrix containing the raw data.
#' @param dim Dimension for plotting ('2D' or '3D'). Defaults to '2D'.
#' @param normalize_data Logical. If TRUE (default), PCA is performed on the
#' correlation matrix (variables are scaled to unit variance).
#' If FALSE, PCA is performed on the covariance matrix
#' (variables are NOT scaled).
#' @param n_components The number of sparse principal components to extract.
#' Defaults to 2. Must be less than the number of variables.
#' @param alpha Controls the sparsity level. Higher alpha leads to sparser loadings.
#' A value between 0 and 1 is typical. Default is 0.5. Adjust based on desired sparsity.
#' @param rotation_method Rotation method for the resulting components (e.g., "varimax", "promax", "none").
#' Defaults to "none" to get the raw sparse components.
#'
#' @return The results object from the sparsepca function.
#' @export
#'
#' @examples
#' # Example usage with iris dataset
#' # data(iris)
#' # iris_data <- iris[, 1:4]
#' # rownames(iris_data) <- paste(iris$Species, 1:nrow(iris), sep="_") # Optional: add meaningful row names
#'
#' # Sparse PCA (on correlation matrix) - 2D plot
#' # pca_plot_sparse(iris_data, dim = "2D", n_components = 2, alpha = 0.5)
#'
#' # Sparse PCA (on correlation matrix) - 3D plot
#' # pca_plot_sparse(iris_data, dim = "3D", n_components = 3, alpha = 0.4)
#'
#' # Sparse PCA (on covariance matrix)
#' # pca_plot_sparse(iris_data, dim = "2D", normalize_data = FALSE, n_components = 2, alpha = 0.5)
#'
pca_plot_sparse <- function(rawdata, dim = "2D", normalize_data = TRUE, n_components = NULL, alpha = NULL, rotation_method = "none") {
# --- Input Validation and Setup ---
original_rownames <- rownames(rawdata)
data_matrix <- as.matrix(rawdata)
# Select only numeric columns
data_numeric <- data_matrix[, sapply(data_matrix, is.numeric), drop = FALSE]
if (ncol(data_numeric) == 0) {
stop("No numeric columns found in the data.")
}
if (nrow(data_numeric) < 2) {
stop("Need at least 2 rows (observations) for PCA.")
}
# Check for constant columns, which cause issues with PCA/SPCA
constant_cols <- which(apply(data_numeric, 2, function(x) length(unique(x))) == 1)
if (length(constant_cols) > 0) {
warning(paste("Columns with constant values detected and removed for PCA:",
paste(colnames(data_numeric)[constant_cols], collapse=", ")))
data_numeric <- data_numeric[, -constant_cols, drop = FALSE]
if (ncol(data_numeric) == 0) {
stop("All columns were constant.")
}
}
# Assign original row names back if they exist
if (!is.null(original_rownames)) {
rownames(data_numeric) <- original_rownames
}
# --- Parameter Setup for sparsepca ---
num_vars <- ncol(data_numeric)
# Set default number of components if not provided
if (is.null(n_components)) {
n_components <- min(2, num_vars - 1) # Default to 2 or max possible if fewer variables
if (n_components < 1) n_components <- 1
message("Default n_components = ", n_components, " used.")
} else if (n_components >= num_vars) {
stop(paste("n_components must be less than the number of variables (", num_vars, ")"))
}
# Set default alpha (sparsity level) if not provided
# alpha controls the L1 penalty strength. Higher alpha -> more sparsity.
if (is.null(alpha)) {
alpha <- 0.5 # A common starting point for moderate sparsity
message("Default alpha value (0.5) used for sparsity control. Adjust 'alpha' parameter for more control.")
}
# Determine matrix type string for messages
matrix_type <- ifelse(normalize_data, "correlation", "covariance")
# --- Sparse PCA Calculation ---
pca_results <- tryCatch({
# The sparsepca function handles centering and scaling internally.
# 'center = TRUE' is standard.
# 'scale = TRUE' corresponds to using the correlation matrix (normalize_data = TRUE).
# 'alpha' is the key parameter for L1 regularization / sparsity control.
spca_out <- sparsepca(
data_numeric,
k = n_components, # Number of components
center = TRUE, # Center the data
scale = normalize_data, # Scale the data (use correlation matrix if TRUE)
alpha = alpha, # Sparsity control parameter
rotation = rotation_method # Optional rotation after extraction
)
spca_out # Return the result object
}, error = function(e) {
stop("Error during Sparse PCA calculation: ", e$message,
"\nConsider adjusting 'n_components' or 'alpha', or check data properties (e.g., multicollinearity).")
}
)
# --- Visualization ---
# The output structure of sparsepca is different from prcomp/psych::principal
# Key elements: loadings, scores, eigenvalues (related to variance explained)
# Check if results are valid for plotting
if (!("loadings" %in% names(pca_results)) || ncol(pca_results$loadings) == 0) {
stop("Sparse PCA calculation did not produce valid loadings.")
}
if (!("scores" %in% names(pca_results)) || ncol(pca_results$scores) == 0) {
stop("Sparse PCA calculation did not produce valid scores.")
}
# Ensure row names are correctly assigned to scores
if (!is.null(original_rownames)) {
rownames(pca_results$scores) <- original_rownames
}
# Number of components actually found (can sometimes differ if k is too high)
num_components_found <- ncol(pca_results$scores)
# Define plot dimension based on user request, but cap at available components
num_plot_dims <- if(dim == "2D") 2 else 3
if (num_plot_dims > num_components_found) {
warning(paste0("Requested ", dim, " plot, but only ", num_components_found,
" components were extracted. Plotting available components."))
num_plot_dims <- num_components_found
}
pca_method_str <- paste0("Sparse PCA (", matrix_type, ", alpha=", alpha, ")")
if (dim == "2D") {
if (num_plot_dims < 2) {
stop("Cannot create a 2D plot with fewer than 2 components.")
}
scores_2d <- pca_results$scores[, 1:2, drop = FALSE]
loadings_2d <- pca_results$loadings[, 1:2, drop = FALSE]
# Plotting scores
plot(scores_2d[, 1], scores_2d[, 2],
xlab = paste0("SPC1"), # Sparse Principal Component 1
ylab = paste0("SPC2"), # Sparse Principal Component 2
main = paste(pca_method_str, "- 2D Plot"),
col = "blue", pch = 16, cex=1.2) # Make points slightly larger
# Add observation labels
text(scores_2d[, 1], scores_2d[, 2],
labels = rownames(scores_2d), pos = 3, cex = 0.7, col="darkblue")
# Add loading vectors
# Scaling the loadings for visualization is crucial as they represent variable contributions.
# A common heuristic is to scale them relative to the range of the scores.
max_score_abs <- max(abs(as.matrix(scores_2d)))
# Adjust the multiplier (0.7) to control how far the vectors extend relative to the scores.
scale_factor <- max_score_abs * 0.7
loadings_scaled_2d <- loadings_2d * scale_factor
for (i in 1:ncol(loadings_2d)) {
# Draw the loading vector line
arrows(0, 0,
loadings_scaled_2d[i, 1], loadings_scaled_2d[i, 2],
col = "red", lwd = 2, length = 0.1)
# Add the variable label
text(loadings_scaled_2d[i, 1] * 1.1, # Position label slightly beyond the vector tip
loadings_scaled_2d[i, 2] * 1.1,
labels = rownames(loadings_2d)[i], col = "red", cex = 0.8, pos = 4)
}
# Calculate and display correlation between the *sparse* component scores
if (num_plot_dims >= 2) {
comp_corr <- cor(scores_2d)[1,2]
title(sub = paste("Correlation between SPC1 and SPC2 scores:", round(comp_comp, 3)))
}
} else if (dim == "3D") {
if (num_plot_dims < 3) {
stop("Cannot create a 3D plot with fewer than 3 components.")
}
scores_3d <- pca_results$scores[, 1:3, drop = FALSE]
loadings_3d <- pca_results$loadings[, 1:3, drop = FALSE]
# Create the 3D scatter plot of scores
plot3d(scores_3d[, 1], scores_3d[, 2], scores_3d[, 3],
col = "blue", size = 5, # size controls point size
xlab = paste0("SPC1"),
ylab = paste0("SPC2"),
zlab = paste0("SPC3"),
main = paste(pca_method_str, "- 3D Plot"))
# Add observation labels
text3d(scores_3d[, 1], scores_3d[, 2], scores_3d[, 3],
texts = rownames(scores_3d),
col = "darkblue", cex = 0.8, adj = c(0.5, 0.5)) # Center text
# Add loading vectors
# Scale loadings for visualization
max_score_abs <- max(abs(as.matrix(scores_3d)))
scale_factor <- max_score_abs * 0.7 # Adjust multiplier as needed
loadings_scaled_3d <- loadings_3d * scale_factor
for (i in 1:ncol(loadings_3d)) {
# Draw line from origin to the scaled loading point
lines3d(x = c(0, loadings_scaled_3d[i, 1]),
y = c(0, loadings_scaled_3d[i, 2]),
z = c(0, loadings_scaled_3d[i, 3]),
col = "red", lwd = 2)
# Add label for the variable corresponding to the loading
text3d(x = loadings_scaled_3d[i, 1] * 1.1,
y = loadings_scaled_3d[i, 2] * 1.1,
z = loadings_scaled_3d[i, 3] * 1.1,
texts = rownames(loadings_3d)[i],
col = "red", cex = 0.8)
}
# Add reference axes and box
axes3d()
box3d()
} else {
stop("Invalid dimension specified. Please choose '2D' or '3D'.")
}
# Return the results object from sparsepca
return(pca_results)
}
Key Changes and Explanations:
- New Package
sparsepca: The core functionality is now handled by the sparsepca package, which implements algorithms designed to find sparse principal components.
alpha Parameter: This is the primary parameter for controlling sparsity. A higher alpha forces more loadings to be zero. You will need to experiment with alpha to find a level that provides meaningful sparsity for your data. A default of 0.5 is provided.
n_components: Similar to before, this specifies how many components you want.
rotation_method: You can choose to apply standard rotations (like 'varimax') after the sparse components are found, or leave it as 'none' for the raw sparse components.
sparsepca() Function: This function is called instead of prcomp or psych::principal. It takes the data, number of components (k), and the sparsity parameter (alpha). It handles centering and scaling internally based on its center and scale arguments.
- Plotting Adaptation:
- The plotting code has been adjusted to work with the output structure of
sparsepca (which includes loadings and scores matrices).
- Labels are changed to "SPC1", "SPC2", etc., to denote Sparse Principal Components.
- Scaling of Loadings: For visualization, the loading vectors are scaled heuristically (based on the maximum absolute score value) to make them visually comparable to the scores on the plot. You might need to fine-tune the
scale_factor multiplier (0.7 in the code) depending on your data and desired visual outcome.
- Fundamental Difference: It's crucial to remember that this is not a simple modification of standard PCA. It's a different method with a different mathematical objective. The resulting components might not be strictly orthogonal in the same way as standard PCA, and their interpretation differs due to the sparsity.