Search code examples
rlabelspssprcomp

Column label as variable name when using prcomp


I have a data frame* with column labels. How can I use, or show, those column labels instead of column names when, for instance, using prcomp? (The function get_label below, is from the package sjlabelled.)

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

What I get (through prcomp) is:

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

What I want is:

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

* The dataset is imported from (dropbox link to .sav) through package haven in the following fashion:

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)))

(I'm sure there are more effective ways of getting "everything between wvs_e0690_00 and wvs_e0690_20", but at least this does the trick. Pointers are appreciated though. As you can tell, I am a beginner at .)

Output of str(spss.wvs[1]) is:

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"

Solution

  • Ah! I can do:

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

    Which gives me

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