--- title: "Exploratory Factor Analysis" author: "Shane T. Mueller shanem@mtu.edu" date: "`r Sys.Date()`" output: rmdformats::readthedown: gallery: yes highlight: kate self_contained: no html_document: df_print: paged pdf_document: default word_document: reference_docx: ../template.docx always_allow_html: yes --- ```{r knitr_init, echo=FALSE, cache=FALSE} library(knitr) library(rmdformats) ## Global options options(max.print="75") opts_chunk$set(echo=TRUE, cache=TRUE, prompt=FALSE, tidy=TRUE, comment=NA, message=FALSE, warning=FALSE) opts_knit$set(width=75) ``` ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` # Exploratory Factor analysis ### Some resources: * http://pareonline.net/getvn.asp?v=18&n=4 * http://pareonline.net/pdf/v10n7.pdf * http://en.wikiversity.org/wiki/Exploratory_factor_analysis ### Libraries used: * ```psych``` * ```GPArotation``` * ```factoextra``` PCA and SVD are considered simple forms of exploratory factor analysis. The term 'factor analysis' is a bit confusing and you will find a variety of definitions out there--some people assert that PCA is not factor analysis, and others might use PCA but call it factor analysis. PCA involves a complete redescription of the covariance or correlation matrix along a set of independent dimensions, until it completely redescribes the data, and then you pick off the most important components and ignore the rest. EFA is typically attempting to do the same thing, but trying to maximize the variance accounted for by a fixed number of 'latent' factors, so that we have the model + error. Furthermore, most of the time factor analysis lets us pick orthogonal dimensions based on criteria other than maximum variance, and permits factors that are not orthogonal, allowing for latent factors that are somewhat related. Making an analogy to MDS, classic MDS used eigen decomposition and then peels off just the top dimensions. But sammon and non-metric scaling try to force the higher dimensions into fewer. Now, instead of fitting all the noise, we can minimize or optimize some notion of fitting the correlation matrix, and treat everything else as noise. When an algorithm has this goal, it is typically called 'factor analysis'. As such, it is important when you report an analysis to give specific details of how the analysis was performed, including the software routine and arguments used. # A simple example In the section on PCA, we examined human abilities and came up with a solution in which one component was an overall ability across all skills, one was visual vs. verbal, and a third was picture vs. maze: ```{r,fig.width=8,fig.height=6} library(GPArotation) data(ability.cov) e2 <- eigen(cov2cor(ability.cov$cov)) f1plot(e2$values) evec <- e2$vectors rownames(evec)<- rownames(ability.cov$cov) round(evec,3) barplot(t(evec[,1:3]),beside=T) ``` We can use the factanal function to do something similar, giving it the covariance matrix. We now specify exactly how many factors we want: ```{r} f3 <- factanal(covmat=ability.cov,factors=3) print(f3) barplot(t(loadings(f3)),beside=T) ``` Now, the first three factors turn out a bit differently. factor1 is the specific `general` skill, reading and vocab--a basic verbal ability. Factor 2 is picture+books; the visual skills that don't involve maze, plus some general. The third loads highly on blocks, maze, and general. These tend to focus on single common positively-correlated factors rather than the divisive components we happened to get with PCA. If you think about it, a mixture of these three factors can produce basically the same patterns as the first three factors of the PCA, but in a different way. Note that the PCA dimensions do not change as we increase the number of dimensions--we do this once and pick off the first few dimensions we care about. FA gives us the best model with a limited number of factors (usually from a maximum likelihood perspective), and it calculates a statistical test asking whether the model is sufficient, at least if it can compute this For f3, it cannot be calculated, and it says the DF of the model is 0 and the fit is 0. For 1- and 2-factor models, it tells us that 1-factor fails but 2-factor does not, suggesting a 2-factor solution is sufficient. ```{r} f1 <- factanal(covmat=ability.cov,factors=1) f2 <- factanal(covmat=ability.cov,factors=2) f1 f2 ``` Each variable is given a 'uniqueness' score, which is the error variance of that term--the unique variance not accounted for by the model. This can help identify whether there are measures that should be removed, because they are simply multiple measures of the same thing. Also, the factors show sum-of-squares (variance), proportion and cumulative, to give a basic effect size for each factor. Because the factors try to maximize variance, we see less of a fall-off in explained variance across factors, and the method balances variance more equally across factors. However, as we increase the number of factors, you can see the total additional variance accounted for per dimension tends to gets smaller. In this case, f1 accounted for 41%, f2 accounted for 50%, and f3 accounted for 67%. Now that we see some of the similarities and differences, let's examine the different arguments to factor analysis. ## Input data factanal can use a formula with data, or a covariance matrix. When given data, it will form the covariance matrix. When given a formula, you specify nothing to the left of the ~, but any variable you care about to the right. If no formula is given, it will use all the variables. In both cases, it derives a correlation matrix. Notice that each of the following produces exactly the same results: ```{r} A <- rnorm(100) B <- rnorm(100) C <- A + rnorm(100)*5 D <- B + rnorm(100)*5 E <- A - B + rnorm(100)*4 F <- C + D + rnorm(100)*5 data <- data.frame(A,B,C,D,E,F) factanal(data,factors=3) factanal(~A+B+C+D+E+F,data=data,factors=3) factanal(covmat=cov(data),factors=3) factanal(covmat=cor(data),factors=3) ``` The psych library offers the fa() function which has much more detailed output and other options. This function has a lot of capabilities, but if we specify the varimax rotation, we get _nearly_ the same results: ```{r} library(psych) psych::fa((data),nfactors=3,rotate="varimax") ``` Because these all end up calculating correlations, this means that missing data (with NA values) can be troublesome. You can specify an na.action, including imputing a prediction about the missing values or ignoring them. Alternately, you can handle this when you make the covariance or correlation matrix. ```{r} fa(data,nfactors=3) ##try missing data: data$A[30] <- NA #factanal(data,factors=3) ## this does not work # factanal(data,factors=3,na.action=na.omit) ## also does not work factanal(~A+B+C+D+E+F,data=data,factors=3, na.action=na.omit) fa(data,nfactors=3) ``` ## Optimization method. Factor analysis can be thought of as a model of the correlation matrix of the responses that uses a fixed number of predictors to describe the data. How this works is that the factor analysis method essentially tries to do PCA using an iterative approximation, with the restriction that you are forced to use a fixed number of factors. After starting at some solution, it iteratively refines this to best describe the data better and maximize goodnees of fit of the model or minimize error in order to best describe the covariance data. However, it is not always exactly clear what 'best describe the data' means. Some traditional methods are 'minres', maximum likelihood, and principal axes, but other methods are available for special cases, depending on the software. In general, choice of optimization method probably depends more on requirements such as size, missing values, availability in the software you are using, etc.--the results might not differ much, one probably won't be universally better for all data sets, and results will be more impacted by other things such as the rotation. The literature suggests that the particular optimization methods differ across software packages, are not well documented, and typically produce similar results. Most sources appear to recommend using ML as a default if the matrix is well-behaved, and if it is not (i.e., the model does not converge) to try another method. The ML (maximum likelihood) factor analysis attempts to find a solution that is most likely to have produced the correlation matrix. Some methods will warn about 'Heywood cases' which could signal that another optimization method could be tried. The factanal function in R uses ML and has a number of options for controlling the estimation; the fa function in in the psych offers more alternatives to ML, but its ML implementation has fewer options. We will also use the psych::fa function because of better output, but you might try an alternate implementation if you run into trouble. ## Rotations Once a solution has been produced, we will have a small fixed number of components/factors that hopefully do a good job a redescribing the complete correlation matrix. But we have a potential problem of non-identifiability. These base factors will be orthogonal just as in PCA, which means that any point (i.e, a response pattern across questions) can be described as a combination of factors. But there are rotations of these axes that produce equally good fits. Thus, once the analysis is done, one usually chooses one of a number of rotations for looking at the data. Some common ones are available within the GPArotation library in R, and can be applied either as a function of fa, or afterward. It might seem non-intuitive that the rotation is not a part of the optimizization. But unlike PCA which has a very well-defined way of assigning dimensions (each dimension maximizes variance in that direction, subject to being orthogonal to all others), factor analysis finds its solution to minimize residual variance/maximize goodness-of-fit. Consequently, it is more like MDS, in that a particular dimension that it picks may not be the best dimension to look at. A specific rotation may help, and often leads to more interpretable factors, because they are designed to hang together better and account for distinct variance. These rotations are available within several packages, including GPArotation, which is used by psych::fa. * varimax (variance maximizing rotation). This maximizes the variance of the factors. Because variance involves squared deviation, it is best to try to put all the variance of any question into a single factor, rather than spreading it out. So overall, factors should favor all-or-none membership of items. Thus it tries to align factors with measures that vary. This is the most popular orthogonal rotation method used frequently by default, and aims to find a simple model where questions are related to unique factors. Within psych::fa, it is no longer the default; as that package uses a non-orthogonal rotation. * quartimax. This maximizes the variance in each item (rather than each factor). Again, this aims for a simple model. To maximize the variance of each item, it should also be placed in a single factor, so it is described as minimizing the number of factors an item appears in. * equamax uses a weighted sum of varimax and quartimax. * varimin a does the opposite of what varimax does. * A list of available orthogonal rotations includes: "none", "varimax", "quartimax", "bentlerT", "equamax", "varimin", "geominT" and "bifactor" The above are all 'orthogonal' rotations--they require the factors to be independent. But it may be better if we allow the factors to be somewhat correlated if they are able to simplify the model more. These are not exactly rotations, because they are also essentially warping the dimensions of the space. They are more properly called 'oblique transformations'. The oblique transformations are harder to easily describe. They use differing criteria to try to create simple and interpretable models. For oblique transformations, the factors will be correlated with one another. However, the correlation cannot be too large, because then it would be better to combine those factors into a single factor. Some options include the following. These are not well documented, and so it is usually preferable to use one that is well understood than to use one you cannot justify, but sometimes an exotic rotation will show a view of your data you did not see anywhere else. * oblimin (default of the fa function). * promax: an oblique transformation that has been described as having similar goals to varimax. * simplimax * bentlerQ * geominQ * quartimin * biQuartmin * cluster # Example: Big Five data set Let's try reading in the big-five data set and performing a factor analysis with various different rotations. We will use the big five data, and both fa and factanal will take the entire data set directly, and not require you to compute a correlation matrix first. ## Read in the big-five data set: ```{r} data <- read.csv("bigfive.csv") dat.vals <- data[,-1]##remove subject code qtype <- c("E","A","C","N","O", "E","A","C","N","O", "E","A","C","N","O", "E","A","C","N","O", "E","A","C","N","O", "E","A","C","N","O", "E","A","C","N","O", "E","A","C","N","O", "O","A","C","O") valence <- c(1,-1,1,1,1, -1,1,-1,-1,1, 1,-1,1,1,1, 1,1,-1,1,1, -1,1,-1,-1,1, 1,-1,1,1,1, -1,1,1,-1,-1, 1,-1,1,1,1, -1,1,-1,1) add <- c(6,0,0)[valence+2] tmp <- dat.vals tmp[is.na(tmp)] <- 3.5 reversed <-t(t(tmp)*valence + add) ##reverse code questions: bytype <- reversed[,order(qtype)] key <- sort(qtype) colnames(bytype) <- paste(key,1:44,sep="") ``` #Factor analysis functions First, let's confirm that the different fa methods can produce similar results: ```{r} ##factanal is built-in to R #f1a <- factanal(bytype,factors=3) library(psych) f1b <- fa(bytype,nfactors=3,rotate="varimax") f1a f1b image(loadings(f1b)) ``` Notice that the two methods produce identical results, but they display different information and show the factors differently. Let's focus on the output of fa, which was done using the minres method; we could have also selected ml, wls, gls, or pa. * It first shows a matrix that includes the three factors (MR2, MR3, and MR1), along with several other statistics. You can get this by doing loadings(model). This will display only the 'important' values--the values close to 0 will not be shown for easier examination. * h2 is the communality score--sum of the squared factor loadings for each question. Somewhat like an $R^2$ value for each item. * u2 is the uniqueness score, 1-h2. * com is complexity, an information score that is generally related to uniqueness. Next, a number of statistics related to the model are shown. It then provides a chi-squared test of whether the model is sufficiently complex (or needs more factors), and other diagnostics of whether the model is acceptable. Because we guess there might be five, we will try five, using the ml optimization method # Optimization method let's look at different optimization methods, using the fm argument ```{r} f2 <- psych::fa(bytype,nfactors=5,fm="ml",rotate="quartimax") f2 f2b <- psych::fa(bytype, nfactors=5,fm="gls",rotate="quartimax") f2b ##causes trouble because of missing data: pca <- princomp(bytype) ``` If you look at the loadings, values, etc. the factor analysis solutions are numerically different but tend to be fairly similar. We can look at them specifically, especially in comparison to the PCA solution: ```{r,fig.width=6,fig.height=8} par(mfrow=c(3,1)) matplot(loadings(f2),type="s",lty=1,main="Factor analyis ML optimization") matplot(loadings(f2b),type="s",lty=1,main="Factor analysis GLS optimization") matplot(loadings(pca)[,1:5],main="5 dimensions of PCA",type="s",lty=1) ``` That does not look bad. If you compare to the factor loadings from the PCA, these are much cleaner--the PCA is almost uninterpretable in comparison. Notice that the two optimization methods produce results that are essentially the same. It looks like each factor takes a turn and maps roughly onto a different set of personality questions. This structure comes from the quartimax rotation, not the optimization method. But maybe other rotations would provide a stronger factor structure. Although we applied rotations within the fa, we can also do it afterward: ```{r} library(GPArotation) ##needed for rotations like oblimin matplot(varimax(loadings(f2))$loadings,type="s",lty=1,main="varimax rotation",ylab="Factor loading") ##fairly similar: matplot(promax(loadings(f2))$loadings,type="s",lty=1,main="promax rotation",ylab="Factor loading") #matplot(oblimin(loadings(f2))$loadings,type="s",lty=1,main="oblimin rotation",ylab="Factor loading") matplot(simplimax(loadings(f2))$loadings,type="s",lty=1,main="simplimax rotation",ylab="Factor loading") matplot(oblimin(loadings(f2))$loadings,type="s",lty=1,main="oblimin rotation",ylab="Factor loading") matplot(varimin(loadings(f2))$loadings,type="s",lty=1,main="varimin rotation",ylab="Factor loading") matplot(varimax(loadings(pca)[,1:5])$loadings,type="s",lty=1,main="varimax rotation on PCA",ylab="Factor loading") ``` # Oblique rotations If you use an oblique rotation, that means your factors are allowed to be correlated. Here is the full output of an oblique rotation (the oblimin): ```{r} oblimin(loadings(f2)) ``` Here, no factors are correlated more than around .2 (see the Phi matrix) which is a constraint in the oblique rotation. The oblique rotations/transformations will sacrifice orthogonality a little in order to maximize another property, usually something about the shared variance of the items that load highly on a factor. # Choosing the right number of factors and evaluating goodness of fit Like all of the methods we have used, it is tough to know how many factors there are. One approach is to use pca to identify how many factors to use (looking at the scree plot and eigen decomposition). Then do a factor analysis to pick a model with that many dimensions. You can also use the goodness-of-fit statistics reported in the model. Many times, the challenge is that in order to get a model whose goodness-of-fit is large enough to satisfy the basic advice, you need to add more factors than are really interpretable. Several statistics are available for evaluating goodness of fit, and these can be used to assess the number of factors as well. Detailed tutorials are available at http://davidakenny.net/cm/fit.htm . Many of the statistics are output from the factor analysis directly, but it may be convenient to use the VSS on the correlation matrix. ```{r} fac <- fa(bytype,nfactors=5) summary(fac) fac8 <- fa(bytype,nfactors=8) summary(fac8) fac10 <- fa(bytype,nfactors=10) fac10 summary(fac10) print(c(fac$BIC,fac8$BIC,fac10$BIC)) ``` Here, the 8-factor solution has the best BIC, the 4-factor solution has high RMSEA and low TLI, so it is probably not good. ## Determining the number of factors There are a number of approaches to picking the number of factors. As suggested by the VSS help file: > 1. Extracting factors until the chi square of the residual matrix is not significant. > 2. Extracting factors until the change in chi square from factor n to factor n+1 is not significant. > 3. Extracting factors until the eigen values of the real data are less than the corresponding eigen values of a random data set of the same size (parallel analysis) using fa.parallel. > 4. Plotting the magnitude of the successive eigen values and applying the scree test (a sudden drop in eigen values analogous to the change in slope seen when scrambling up the talus slope of a mountain and approaching the rock face. > 5. Extracting principal components until the eigen value < 1, and use that many factors. > 6. Extracting factors as long as they are interpetable. > 7. Using the Very Simple Structure Criterion (VSS). > 8. Using Wayne Velicer's Minimum Average Partial (MAP) criterion. The VSS function will display many of these criteria in a table. You can use any of these criteria, and we will look at many of them more specifically below. The output includes: ``` dof: degrees of freedom (if using FA) chisq: chi square (from the factor analysis output (if using FA) prob: probability of residual matrix > 0 (if using FA) sqresid: squared residual correlations RMSEA: the RMSEA for each number of factors BIC: the BIC for each number of factors eChiSq: the empirically found chi square eRMS: Empirically found mean residual eCRMS: Empirically found mean residual corrected for df eBIC: The empirically found BIC based upon the eChiSq fit: factor fit of the complete model cfit.1: VSS fit of complexity 1 cfit.2: VSS fit of complexity 2 cfit.8: VSS fit of complexity 8 cresidiual.1: sum squared residual correlations for complexity 1 : sum squared residual correlations for complexity 2 ..8 ``` Running VSS requires giving it the raw correlation matrix: ```{r} ff <- cor(bytype,use="pairwise.complete") VSS.scree(ff) VSS(ff,n=10) ``` These parallel lines are VSS statistics for reconstituting the correlation matrix with different numbers of simple factors, with the number indicating the complexity. VSS1 picks the largest value for each factor, VSS2 shows the two largest, etc. These two are shown numerically, and complexity 3 and 4 are also shown in the graph visually. The help suggests that these will peak at the optimal number of factors. Here, the output suggests the optimal is between 5 and 8, depending on your criterion. # Summary of goodness-of-fit statistics. ### VSS VSS scores tend to peak at a number of factors that is 'most interpretable'. They compare the fit of the simplified model to the original correlations ### RMSEA RMSEA score is a measure of root mean square error residuals. It says how far off you are, on average, when you compare the predicted correlation matrix and the actual one. Here, for 5 factors, it is .058, which is reasonably 'good', but not great (a RMSEA of .01 would be great). For 10 factors, it gets down to .028--but at what cost? A RMSEA of .05 means that when you try to estimate the correlation matrix, each error is off by about .05. ### TLI TLI is based on comparing expected versus observed chi-squared tests, penalizing by the size of the model. Here, it is .764 for 5 groups and .95 for 10 groups. A value of .9 is considered marginal, .95+ is good. So, 5 groups would be considered inadequate. ### BIC and AIC BIC is a relative measure, which combines goodness of fit in its likelihood with model complexity. Smaller or more negative scores are better. Here, BIC for 5-factor is -1919, and for 10-factor it is -2854.69. We need to be careful about interpreting BIC because sometimes functions report negative BIC. In this case, we are looking for the minimum BIC score, which occurs at 8 factors. ### MAP: Velicer's Minimal Average Partial This will tend to minimize for the 'best' model. ### Interpretability More often than not, researchers rely on notions of interpretability to guide exploratory factor analysis. The statistics may tell you a ten-factor solution is needed, but you may only be able to interpret three. Ultimately, the goal of FA is usually scientific inference, and if the factor is not helping you understand anything, it might not be helpful to use. # Assessing general factors with the omega function In intelligence research, factor analysis has often revealed a general intelligence element g that is general across all skills. ```{r} library(psych) library(lavaan) dat <- HolzingerSwineford1939[,7:15] colnames(dat) <- c("vis","cubes","lozenges","pcomp","scomp","meaning","addition","counting","letters") VSS(cor(dat),n=5) p <- psych::pca(cor(dat),nfactors=3) p ``` The default 3D pca of this data set shows three main factors with strong structure. The uniqueness suggests there is substantial error in each dimension not captured otherwise. How does FA do? Can we estimate a more general factor shared across all dimensions? Let's try an EFA with both 3 and 4 dimensions. I will use varimax rotation to enforce orthogonal factors. ```{r} h.efa3 <- fa(dat,nfactors=3,rotate="varimax") h.efa3 h.efa4 <- fa(dat,nfactors=4,rotate="varimax") h.efa4 ``` The FA with 3 finds a slightly different model, with letters fitting into visual more than speed--this was a task discriminating upper and lowercase letters, so maybe there is some truth to that. The factor analysis with 4 dimensions separates that into its own dimension. None of these capture a single common model, in order to estimate a 'g' factor. A traditional version of the bifactor model is available in the omega function in psych, which fits a general factor and then an EFA on the residuals, and comparing the difference between these models. This is more like EFA with a specific structure. The model implements a factor analysis that fits one common factor and then unique factors--attempting to identify the 'g' general factor that is commonly found in intelligence research. Also, we discussed this model when examining psychometrics: this is argued to be the best way to identify whether a single factor exists, and more instructive than measures such as cohen's $\alpha$ or GLB. ```{r} holz <- omega(dat,3, title = "14 ability tests from Holzinger-Swineford") holz ``` Notice that the g factor is relatively strong here, and each of three factors load uniquely on a small subset of the other variables, and it also captures this 'intermediate' letter test. It also tests this complete model against the single group factor, so if the model fails, it suggests no more than one group is needed--that is, you have a coherent structure or a consensus. Thus, if that test fails, it may be the best approach to estimating a strong structure as an alternative to Cohen's alpha--providing the first factor is sufficiently good. We can try the ability.cov data as well using omega. 3 factors looks like it is too many, but a general factor is formed. 28% of the variance is accounted for by the common factor: ```{r} omega.ability <- omega(m=ability.cov$cov,2) print(omega.ability) omega.ability <- omega(m=ability.cov$cov,3) print(omega.ability) ``` # Examining and displaying the models It is common to display the results in several ways that show the factor structure. if you use the plot method, it will show you the points along each pair of dimensions, with point color-coded by whether they are high or low on each dimension. Looking at some of the FAs: ```{r,fig.width=10,fig.height=10} fa.diagram(h.efa4) fa.diagram(fac) fa.diagram(fac10) fa.diagram(fac8) ##Plotting the factors: fac4b<- fa(bytype,nfactors=4) plot(fac4b) fa.diagram(fac4b) ``` # Example: Michigan House Votes Use the Michigan house votes to compute a factor analysis. If necessary, determine what to do for 'impute', figure out how many factors to use, explore several rotations, and try to identify an interpretable result. # Assessing factors of political issues First we can look at a PCA to get an idea of the number of factors that might exist in the data. fvis_pca provides some interesting visualizations: ```{r} library(factoextra) house <- read.csv("mihouse.csv") votes <- house[,-(1:2)] rownames(votes) <- paste(house$Party,1:nrow(house),sep="-") pca <- princomp(~.,data=votes,scores=T) #this handles NA values fviz_screeplot(pca) fviz_pca_var(pca) fviz_pca(pca,col.ind="cos2") print(pca) (loadings(pca)) ``` Questions: * How many factors seem reasonable? * Looking at those factors, Can you make any interpretations? Try this with psych::principal, which will produce many of the same results as psych::fa ```{r} p2 <- psych::principal(votes,nfactors=5) p2 plot(p2) ``` ## Factor analysis: Perform a factor analysis with psych::fa. Determine how many dimensions are necessary, and justify model with goodness of fit parameters. - examine both orthogonal and non-orthogonal rotations - Create a plot showing the factor structure - examine models of different sizes to identify a good solution given the data set. - For the non-orthogonal rotation, examine correlations between factors. Baseline solution: ```{r} efa5 <- psych::fa(r=votes,nfactors=5) efa5 <- psych::fa(r=votes,nfactors=5,fm="ols") efa5 ```