Performs PCA after automatically detecting and fixing problematic columns
(e.g., zero variance, NA-only, partial NAs) in a deterministic way.
Ensures that the output dimensions match those from a clean dataset.
safe_pca(X, nc = min(dim(X)), center = TRUE, scale = TRUE)
Arguments
- X
A numeric matrix or data frame.
- nc
Number of components to return.
- center
Logical, whether to center columns.
- scale
Logical, whether to scale columns to unit variance.
Value
A list with the same structure as prcomp
,
with rotation, sdev, x, etc.
Examples
set.seed(123)
mat <- matrix(rnorm(50), nrow = 10)
mat[, 3] <- 1 # zero variance col
mat[, 5] <- NA # all NA col
# result <- safe_pca(mat, nc = 3)
# result$rotation