从R中的PCA中提取百分比

时间:2018-11-04 21:32:43

标签: r pca

我想提取PC百分比并将其用于轴标签

输入:

>colnames(df_out)
  [1] "PC1"   "PC2"   "PC3"   "PC4" 
>percentage
            PC1   PC2  PC3  PC4  
    PC1   52.89  0.00 0.00 0.00 
    PC2    0.00 31.69 0.00 0.00 
    PC3    0.00  0.00 6.49 0.00 
    PC4    0.00  0.00 0.00 3.82 

所需的输出:

  [1] "PC1 (52.89%)"   "PC2 (31.69%)"   "PC3 (6.49%)"   
  [4] "PC4 (3.82%)" 

代码

percentage <- paste(colnames(df_out), "(", paste(as.character(percentage), "%", ")", sep=""))

上面的代码只给我提供了第一台PC的百分比,但是我也希望PC2。

1 个答案:

答案 0 :(得分:0)

一种选择是提取diag

v1 <- diag(as.matrix(percentage))
paste0(names(v1), " (", v1, "%)")
#[1] "PC1 (52.89%)" "PC2 (31.69%)" "PC3 (6.49%)"  "PC4 (3.82%)" 

数据

percentage <- structure(list(PC1 = c(52.89, 0, 0, 0), PC2 = c(0, 31.69, 0, 
 0), PC3 = c(0, 0, 6.49, 0), PC4 = c(0, 0, 0, 3.82)), 
 class = "data.frame", row.names = c("PC1", "PC2", "PC3", "PC4"))