使用 prcomp 时列标签作为变量名

Column label as variable name when using prcomp

我有一个带有列标签的数据框*。例如,当使用 prcomp 时,如何使用或显示那些 labels 列而不是 names 列? (下面的函数 get_label 来自包 sjlabelled。)

> get_label(spss.wvs) %>% head(2)
           wvs_e069_01                wvs_e069_02 
"Confidence: churches" "Confidence: armed forces" 

我(通过prcomp)得到的是:

> pca.wvs$rotation %>% head(2)
                PC1        PC2
wvs_e069_01 -0.08513771 0.45688379 
wvs_e069_02 -0.23062304 0.05508813 

我想要的是:

> pca.wvs$rotation %>% head(2)
                PC1        PC2
"Confidence: churches" -0.08513771 0.45688379 
"Confidence: armed forces" -0.23062304 0.05508813 

* 数据集是通过包 haven (dropbox link to .sav) 以下列方式导入的:

library(haven)
haven.imp <- read_spss("qog_std.sav")
library(dplyr)
spss.wvs <- haven.imp %>% dplyr:: select(starts_with("wvs_e069_0"), starts_with("wvs_e069_1"), grep("wvs_e069_20", names(haven.imp)))

(我敢肯定有更有效的方法来获得 "everything between wvs_e0690_00 and wvs_e0690_20",但至少这可以解决问题。尽管如此,我们还是很感激您的指点。如您所知,我是 [=22= 的初学者].)

str(spss.wvs[1]) 的输出是:

Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   193 obs. of  1 variable:
 $ wvs_e069_01: num  NA NA NA 3.17 NA ...
  ..- attr(*, "label")= chr "Confidence: churches"
  ..- attr(*, "format.spss")= chr "F8.2"

啊!我能做到:

> library(sjlabelled)
> rownames(spss.wvs$rotation) <- get_label(wvs)

这给了我

> spss.wvs$rotation %>% head(2)
                                 PC1        PC2
Confidence: churches     -0.08513771 0.45688379
Confidence: armed forces -0.23062304 0.05508813