Search code examples
rpsych

How do I format psych factor analysis output to tables?


Has something changed with the psych package? There used to be a function fa2latex that let you produce latex code for factor analysis results, but I do not see it here (https://cran.r-project.org/web/packages/psych/psych.pdf) . df2latex is there, but not fa2latex.

This is along the lines of what I need, but I am certain there are much better ways to accomplish this.

library(psych)
library(flextable)
#Make PCA model
data("Thurstone")
Thurstone
pca1<-principal(Thurstone, nfactors=2, rotate="varimax")
#Make function to save the object as word or html
psychSave<-function(x, cut=0.3, row.names=T, format="html", path){
  #Get the number of items in the pca
  n_items<-dim(x$loadings)[1]
  #Now sort 
  x_sorted<-fa.sort(x$loadings[1:n_items,])
  #Convert to data frame
  x_sorted<-data.frame(x_sorted)
  #Implement the cut option, converting all else to NA
  x_sorted<-apply(x_sorted, 2, function(z) {
    ifelse(abs(z)< cut, NA, z)
  })
  x_sorted<-data.frame(x_sorted)
  #Add Row Names in Variable Name
  x_sorted$Name<-rownames(x_sorted)
#Convert to flextable
  x_sorted<-flextable(x_sorted)
if(format=="html") {
  save_as_html(x_sorted, path=path)
}
else {
  save_as_docx(x_sorted, path=path)
}
}
#Save out. 
psychSave(pca1, format="html", path="~/Desktop/test.html")

I would like to add functionality here like have the item names printed in the table (first in the order of the columns) and add some of the summary statistics (e.g. communality). I'll get to it, I guess, but there must be a way that someone has implemented some of this.


Solution

  • To be more explicit, the tth package will convert the latex output from fa2latx to an html document.

    Thus

    . library(tth)
    library(psych)
    f3 <- fa(Thurstone,3)
    f3.lat <- fa2latex(f3)
    f3.htm <- tth(f3.lat)
    print(as.data.frame(f3.htm),row.names=FALSE)