如何在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?
- Wrong Order of Operations: You tried converting
mm.active$TREATMENTSto a factor before you even created themm.activesubset. That line of code didn't actually do anything becausemm.activedidn't exist yet! - 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.activefirst, then converting its TREATMENTS column to a factor, you ensure the change actually applies to your working dataset. quali.supParameter: This tellsPCA()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
相关产品推荐
相关产品推荐

