Getting data frame from loadings of factor analysis (fa function in psych)
Asked Answered
M

2

5

I have a data frame such as follows:

x <- c(1, 2, 1, 2)
y <- c(1, 2, 3, 4)
z <- c(4, 3, 2, 1)
df <- data.frame(x, y, z)

I am running a factor analysis with the fa funciton from the psych package:

fit <- fa(df, nfactors = 2)
fit$loadings

This results in the following output:

Loadings:
  MR1    MR2   
x  0.448       
y  0.999       
z -0.999       

                 MR1   MR2
SS loadings    2.195 0.000
Proportion Var 0.732 0.000
Cumulative Var 0.732 0.732

I would like to save the table with MR1 and MR2 as a data frame. Does anyone know how could this be done? Thank you.

Manifestative answered 10/11, 2018 at 13:23 Comment(0)
H
6

I believe the short answer should simply be:

as.data.frame(unclass(fit$loadings))

Giving:

         MR1         MR2
x  0.4502976  0.10314193
y  0.9984784 -0.02325767
z -0.9984784  0.02325767
Huskey answered 7/7, 2022 at 6:18 Comment(0)
S
3
x <- c(1, 2, 1, 2)
y <- c(1, 2, 3, 4)
z <- c(4, 3, 2, 1)
df <- data.frame(x, y, z)

fit <- psych::fa(df, nfactors = 2)

x <- fit$loadings

via stats:::print.loadings:

Lambda <- unclass(x)
p <- nrow(Lambda)
factors <- ncol(Lambda)

vx <- colSums(x^2)
varex <- rbind(`SS loadings` = vx)

if (is.null(attr(x, "covariance"))) {
  varex <- rbind(varex, `Proportion Var` = vx/p)
  if (factors > 1) 
    varex <- rbind(varex, `Cumulative Var` = cumsum(vx/p))
}

tibble::rownames_to_column(as.data.frame(varex), "x")
##                x       MR1          MR2
## 1    SS loadings 2.1954555 3.000000e-30
## 2 Proportion Var 0.7318185 1.000000e-30
## 3 Cumulative Var 0.7318185 7.318185e-01

And, for the first table:

cutoff <- 0.1 # (the default for the `print.loadings()` function)
Lambda <- unclass(x)
p <- nrow(Lambda)
fx <- setNames(Lambda, NULL)
fx[abs(Lambda) < cutoff] <- NA_real_
fx <- as.data.frame(fx)
rownames(fx) <- NULL
fx
##          MR1 MR2
## 1  0.4476761  NA
## 2  0.9987596  NA
## 3 -0.9987596  NA
Sledge answered 10/11, 2018 at 13:41 Comment(2)
This works well. I'm sorry I wasn't specific enough: I would like to turn the first table into a data frame (the one with MR1, MR2, x, y, z). Could this be done in a way that doesn't require to list out all the variables from the the original df data frame (x, y, z)?Manifestative
updated to account for needing the first table and using NA vs the blanks for the other column.Sledge

© 2022 - 2024 — McMap. All rights reserved.