首页 > 解决方案 > 有没有办法防止 R 在 PCA 分析中将我的变量更改为序列号?

问题描述

我正在使用 R 中的 FactoMineR 和 factoextra 包运行 PCA 分析。分析后,R 不断将我的第一列将行名更改为序列号。我想知道如何在不将其更改为序列号的情况下保留该列。

我是 R 新手,所以我不知道该怎么做。

library(readr)
library(FactoMineR)
mm <- read_csv("masters.csv")
mm.active$TREATMENTS <- as.factor(mm.active$TREATMENTS) #this the column 
#that is being changed to serial number
mm.active <- mm[1:36, 2:12] #to specify the active components
head(mm.active[ , 1:6])
res.pca <- PCA(mm.active, graph = FALSE)
print(res.pca)
plot(res.pca, choix = "var") #this displays the PCA plot of the variables
plot(res.pca, choix = "ind") #this is supposed to show that of the 
# "TREATMENTS" column showing each treatments but it shows serial numbers 
#instead     

我希望看到图中显示的每种治疗方法,但 R 显示的是序列号。

标签: rpca

解决方案


欢迎来到 SO!我没有你的数据,所以这里有一个著名mtcars数据集的例子:

library(FactoMineR)
res.pca <- PCA(mtcars, graph = FALSE)
plot(res.pca, choix = "ind") 

在此处输入图像描述

它正在打印汽车的名称,因为它们是行名。因此,您必须TREATMENTS从数据中删除 ,并将它们添加为行名(反之亦然,就像我的代码一样,因为我已经想象您现在在数据集中拥有该列):

rownames(mm.active) <- mm.active$TREATMENTS
mm.active[ , -which(names(mm.active) %in% c("TREATMENTS"))]

然后运行 ​​PCA。


推荐阅读