如何从PCA中提取载荷-在保留变量载荷/变量名称的同时

时间:2019-03-06 13:38:14

标签: r

我执行了一次成功的PCA,现在我希望提取负载。

我运行了PCA

    #Run PCA and plot results
pca <- prcomp(dataset_numeric[c(1:8, 10:11, 13:18),c(1:ncol(data_tsc))], center = TRUE, scale. = TRUE)
summary(pca)

尝试提取载荷

loading_PC <- pca$rotation[,2] %>% sort(decreasing = TRUE)

哪个退回了这个

enter image description here

此后,我尝试使用以下代码将其组织到一个数据框中:

loading_PC <- pca$rotation[,2]  %>% sort(decreasing = TRUE) %>% as.data.frame(row.names = TRUE)

哪个回来了

enter image description here

如您所见,所有基因名称(变量,加载名称)都丢失了,所以我想知道是否有任何方法可以保留它们。预先谢谢你。

更改 我按要求添加了用于Loading_PC的dput:

    c(A1CF = -0.146219143927011, AACS = -0.231151131955, AATK = -0.485220551393282, 
ABCA1 = -0.222934271967757, ABCA5 = 0.282376223269048, ABCA7 = 0.0779960358397119, 
ABCB9 = -0.389273153643306, ABCC4 = -0.611693335877105, ABCC5 = 0.129182251850867, 
ABCD2 = 0.108813374460373)

1 个答案:

答案 0 :(得分:0)

缺少名称是因为您将原子向量传递给sort(),而作为回报,它为您提供了原子向量。按顺序重新排列孔矩阵/ df,然后使用drop = FALSE重新设置子集:

> rm(list = ls())
> 
> data(iris)
> 
> iris.pca <- prcomp(iris[colnames(iris) != "Species"], center = TRUE, scale. = TRUE)
> iris.weights <- data.frame(iris.pca$rotation)
> 
> # Names are lost
> NoNames <- sort(iris.weights[, 2], decreasing = TRUE)
> NoNames
[1] -0.02449161 -0.06694199 -0.37741762 -0.92329566
> 
> # Names are preserve
> WithNames <- iris.weights[order(iris.weights[, 2], decreasing = TRUE),][, 2, drop = FALSE]
> WithNames
                     PC2
Petal.Length -0.02449161
Petal.Width  -0.06694199
Sepal.Length -0.37741762
Sepal.Width  -0.92329566
> 

这是最后一个dput():

> # With dput
> 
> df <- data.frame(c(A1CF = -0.146219143927011, AACS = -0.231151131955, AATK = -0.485220551393282,
+         ABCA1 = -0.222934271967757, ABCA5 = 0.282376223269048, ABCA7 = 0.0779960358397119,
+         ABCB9 = -0.389273153643306, ABCC4 = -0.611693335877105, ABCC5 = 0.129182251850867,
+         ABCD2 = 0.108813374460373))
> 
> colnames(df) <- "weights"
> 
> sort(df$weights, decreasing = TRUE)
 [1]  0.28237622  0.12918225  0.10881337  0.07799604 -0.14621914 -0.22293427 -0.23115113
 [8] -0.38927315 -0.48522055 -0.61169334
> 
> df[order(df$weights, decreasing = TRUE),,drop = FALSE]
          weights
ABCA5  0.28237622
ABCC5  0.12918225
ABCD2  0.10881337
ABCA7  0.07799604
A1CF  -0.14621914
ABCA1 -0.22293427
AACS  -0.23115113
ABCB9 -0.38927315
AATK  -0.48522055
ABCC4 -0.61169334
> 

希望有帮助。