我已经使用包运行了一个简单的 PCA
FactoMineR
。
PCA 运行良好,我得到 15 个维度(我有 15 个变量)
当我尝试获取每个变量对每个主成分的贡献时,我只得到 5 个维度的结果,而不是所有 15 个维度的结果。
我的代码:
library(FactoMineR)
library(factoextra)
set.seed(123)
PCA_data <- matrix(rnorm(675), ncol = 15)
PCA_scaled <- scale(PCA_data)
pca_result <- PCA(PCA_scaled, graph = TRUE)
eigenvalues <- get_eigenvalue(pca_result)
variance_explained <- get_pca_var(pca_result)$prop_var
contributions <- pca_result$var$contrib
contributions
get_pca_var(pca_result)$contribSDT_scaled <- scale(PCA_data)
fviz_eig(pca_result, choice = "eigenvalue", addlabels = TRUE)
# Biplot
fviz_pca_biplot(pca_result, repel = TRUE, col.var = "contrib",
gradient.cols = c("#00AFBB", "#E7B800", "#FC4E07"))
# Create a data frame for plotting
plot_data <- data.frame(
Principal_Component = rep(1:ncol(contributions), each = nrow(var_contributions)),
Variable = rep(rownames(contributions), ncol(contributions)),
Contribution = as.vector(contributions)
)
# Create a stacked bar plot
ggplot(plot_data, aes(x = Principal_Component, y = Contribution, fill = Variable)) +
geom_bar(stat = "identity") +
labs(title = "Variable Contributions to Principal Components",
x = "Principal Component",
y = "Contribution") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
scale_fill_viridis_d()
#I also tried:
summary(pca_result, nbelements=Inf)
这些都没有给我所有 15 个维度或每个变量的贡献。
tl;dr 要保留所有组件,请在运行 PCA 时指定
ncp=15
...
来自
?PCA
:
PCA(X,scale.unit = TRUE,ncp = 5,ind.sup = NULL, Quanti.sup = NULL,quali.sup = NULL,row.w = NULL, col.w = NULL,图 = TRUE,轴 = c(1,2))
(强调)。
...
ncp: number of dimensions kept in the results (by default 5)