7

I am trying to convert an object of type "loadings" to a dataframe in R. However, my attempts to coerce it via as_tibble() or as.data.frame() have not worked. Here is the code:

iris_pca <- prcomp(iris[1:4], center = TRUE, scale. = TRUE)
iris_pca$rotation[,1:2] %>% 
  varimax() %>% 
  .$loadings

This prints out:

Loadings:
             PC1    PC2   
Sepal.Length  0.596 -0.243
Sepal.Width         -0.961
Petal.Length  0.570  0.114
Petal.Width   0.565       

                PC1  PC2
SS loadings    1.00 1.00
Proportion Var 0.25 0.25
Cumulative Var 0.25 0.50

How can I get this data into a dataframe?

Hank Lin
  • 5,959
  • 2
  • 10
  • 17

1 Answers1

7

From the "loadings" object extract the values as numeric. Coerce them into a matrix. Needed dimensions and names you will find within str(l).

data.frame(matrix(as.numeric(l), attributes(l)$dim, dimnames=attributes(l)$dimnames))
#                      PC1         PC2
# Sepal.Length  0.59593180 -0.24252635
# Sepal.Width  -0.04181096 -0.96087188
# Petal.Length  0.56955777  0.11438157
# Petal.Width   0.56455387  0.06944826

Data

iris_pca <- prcomp(iris[1:4], center=TRUE, scale.=TRUE)
l <- varimax(iris_pca$rotation[, 1:2])$loadings
jay.sf
  • 60,139
  • 8
  • 53
  • 110