You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R的PCA分析中保留TREATMENTS列而非转为序列号?

Fixing TREATMENTS Label Display in PCA Plots with FactoMineR

Hey there! Let's sort out why your TREATMENTS labels are showing up as serial numbers instead of their original names in the PCA individual plot. There are two key issues in your code causing this—let's break them down and fix them step by step.

What's Going Wrong?

  1. Wrong Order of Operations: You tried converting mm.active$TREATMENTS to a factor before you even created the mm.active subset. That line of code didn't actually do anything because mm.active didn't exist yet!
  2. Not Specifying Qualitative Variables: The PCA() function treats all columns as quantitative variables by default—even factors get converted to their underlying serial numbers for analysis. You need to tell it which column is your categorical grouping variable so it preserves the labels.

Corrected Code

Here's the adjusted version of your code that will keep your TREATMENTS labels intact:

library(readr)
library(FactoMineR)
library(factoextra) # Optional, but great for nicer plots

# Load your data
mm <- read_csv("masters.csv")

# First create your active dataset subset
mm.active <- mm[1:36, 2:12]

# Convert TREATMENTS to a factor (now that mm.active exists!)
mm.active$TREATMENTS <- as.factor(mm.active$TREATMENTS)

# Run PCA, and specify TREATMENTS as a qualitative supplementary variable
# We use `which(colnames(mm.active) == "TREATMENTS")` to find its column index automatically
res.pca <- PCA(mm.active, 
               graph = FALSE, 
               quali.sup = which(colnames(mm.active) == "TREATMENTS"))

# Now plot individuals—you'll see the original TREATMENTS labels!
plot(res.pca, choix = "ind")

Extra Tip: Nicer Plots with factoextra

If you want more control over the plot (like coloring points by treatment group), use the factoextra package:

# Plot individuals colored by TREATMENTS
fviz_pca_ind(res.pca,
             geom.ind = "point", # Use points for individuals
             col.ind = mm.active$TREATMENTS, # Color by treatment group
             legend.title = "Treatments",
             repel = TRUE) # Prevent label overlap

Key Explanations

  • Fixing the Factor Conversion: By creating mm.active first, then converting its TREATMENTS column to a factor, you ensure the change actually applies to your working dataset.
  • quali.sup Parameter: This tells PCA() that the TREATMENTS column is a qualitative (categorical) variable that shouldn't be used to calculate the principal components—instead, it's kept as metadata to label/group your individuals in plots.

内容的提问来源于stack exchange,提问作者Samuel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:15:05