Rstudio中使用factoextra包PCA函数如何获取个体点坐标及对应ID
factoextra包PCA分析后匹配个体坐标与原ID的实现方法
- 执行PCA前先单独备份ID列,不要直接在原数据集上删除ID,仅提取数值列作为PCA的输入:
# 加载依赖包 library(factoextra) library(FactoMineR) # 如果你用FactoMineR的PCA函数才需要加载,用基础prcomp可省略 # 假设原始数据框为raw_df,ID列列名为sample_id # 单独存储样本ID向量 sample_ids <- raw_df$sample_id # 生成仅含数值变量的PCA输入矩阵,移除ID列 pca_input <- raw_df[, !colnames(raw_df) %in% "sample_id"] # 运行PCA分析,二选一即可 # 方法1:用FactoMineR的PCA函数(factoextra原生适配) pca_res <- PCA(pca_input, scale.unit = TRUE, graph = FALSE) # 方法2:用基础包prcomp函数 pca_res <- prcomp(pca_input, scale. = TRUE)
- 调用factoextra内置的
get_pca_ind()函数提取个体主坐标,再和预存的ID合并即可得到对应关系:
# 提取所有个体的全部主成分坐标 ind_all_coords <- get_pca_ind(pca_res)$coord # 绑定ID与前两轴坐标,生成结果表 pca_id_result <- data.frame( sample_id = sample_ids, PC1 = ind_all_coords[, 1], PC2 = ind_all_coords[, 2] )
上述方法对
FactoMineR::PCA()和stats::prcomp()的输出结果都兼容,如果需要获取更多主坐标轴的坐标,只需要调整ind_all_coords的列索引即可。
内容的提问来源于stack exchange,提问作者Nicolas
相关产品推荐
相关产品推荐

