<table width = 900 border = 0><tr><td>
# <b>NMST539 | Lab Session 6</b>

## <b>Factor Analysis with R</b>

### <font color = "#880000">LS 2017 | Tuesday 18/04/2017 </font>
###### <a href = "cvicenie2017_7.Rmd">Rmd file (UTF8 encoding)</a>

**************


The R-software is available for download from the website: <a href = "https://www.r-project.org">https://www.r-project.org</a>

A user-friendly interface (one of many): <a href = "https://www.rstudio.com">RStudio</a>.<br><br>

<b>Manuals and introduction into <i>R</i>
(in Czech or English):</b><br>
    
<ul>
<li>Bína, V., Komárek, A. a Komárková, L.: <i>Jak na jazyk R.</i>  (<a href = "NMFM301/Rmanual2.pdf">PDF súbor</a>)</li>
<li>Komárek, A.: <i>Základy práce s R.</i>  (<a href = "http://msekce.karlin.mff.cuni.cz/~komarek/vyuka/dataRko/Rmanual1.pdf">PDF súbor</a>)</li>
<li>Kulich, M.: <i>Velmi stručný úvod do R.</i> (<a href = "NMFM301/uvodr.pdf" >PDF súbor</a>)</li>
<li>De Vries, A. a Meys, J.: <i>R for Dummies.</i> (ISBN-13: 978-1119055808) </li>  	
</ul>
**************

  


### <font color = "#880000"><b>Introduction into FA</b></font>

Factor analysis is an effective statistical method for dimensionaly reduction especially in situation 
where one needs to use the data for further analysis and calculations (e.g. regression).
It is used to describe the overall correlation among all variables however, using a potentially lower number of variables which are called factors. These factors are, however, unobserved random variables.

The factor analysis approach searches for similar covariates with respect to their mutuall correlation. All variables with mutually high correlation are represented with a factor (or a linear combination of factors) instead. 

In some sense the factor analysis approach can be considered to be a generalization of the classical principal component analysis (PCA) with one great advantage at the end - much more convenient interpretation of the factors. 

In the statistical software R there is function `factanal()` available under the standard R instalation. 
Beside that, there are many more additinal functions and packages which can be downloaded and installed in R (e.g. `Factanal()` function in the 'FAiR' package; `fa.promax()` function in the 'psych' package;). 

For our purposes we mainly use the standard function `factanal()`. Let us again recall the biological metrics data from the Czech republic. The data represent 65 different river localities in the Czech Republic where on each locality there are various biological metrics assessed (17 metrics in total). 

```{r}
rm(list = ls())
bioData <- read.csv("http://msekce.karlin.mff.cuni.cz/~maciak/NMST539/bioData.csv", header = T)
```
<br><br>

The correlation structure (wich will be later assessed using the factor analysis approach) can be either estimated using a standard variance covariance matrix (command `var(bioData[,2:18])`) or it can be visualized using the `corrplot()` function from the 'corrplot' package instead. 

```{r, message=F, fig.width=10, fig.height=8}
library(corrplot)
corrplot(cor(bioData[,2:18]), method="ellipse")
```



The idea behind the `factanal()` function is to consider a $p$-dimensional (random) vector $\boldsymbol{X}$ and to express this vector using a set of $k$ factors  where we require want that $k \ll p$ (dimensionaly reduction). The model which is fitted by the factor analysis approch by appling the `factanal()' function in R is the following one:

$$
\boldsymbol{X} = \Lambda \boldsymbol{F} + \boldsymbol{e}, 
$$

where $\Lambda$ is a $p\times k$ dimensional matrix of so called <b>factor loadings</b>, $\boldsymbol{F}$ is a $k$-dimensional (random) vector represending $k$ factors (common factors or scores respectively) and $\boldsymbol{e}$ is an approximation error (or specific factors).  

The tricky part in this expresssion is that beside the random vector $\boldsymbol{X}$ no other quantity is directly observed. The problem, as such, is unsolvable unless we pose some additional restrictions. 
This is done by specifying a varinace covariance structure among all quantities which appear in the expression above: 

<ul>
<li>The scores $\boldsymbol{F}$ are required to be uncorrelated with unit variance ($Var (\boldsymbol{F}) = \mathbb{I}_{k});$</li>
<li>Error terms $\boldsymbol{e}$ are independent with some variance ($Var (\boldsymbol{e}) = \boldsymbol{\Psi}$, where $var (e_{i}) = \psi_{ii}$);</li>
<li>The correlation matrix of $\boldsymbol{X}$ is decomposed as $\Sigma = \Lambda \Lambda^{T} + \boldsymbol{\Psi}$.</li>
</ul>

<br><br>



#### <font color = "#880000">Note</font>
<hr size="3" width="100%" noshade style="color:#440000" align="left" />
<ul>
<li>Factor analysis is not unique -- the rotation of $X$ gives the same results;</li>
<li>Factor analysis is invariant with respect to the scale;</li>
</ul>
<hr size="3" width="100%" noshade style="color:#440000" align="left" />

<br><br>

Since the factors are not unique with respect to the rotation, it is usefull to provide some rotation which makes sense. 
The automatic proceduce which tries to find factors in a way that original covariates can be splitted into disjoint sents is called the \textbf{varimax} procedure. <br>
To use the varimax procedure for detecting the right rotation we can use the additional parameter 'rotation="varimax"' when calling the function `factanal()` in R. 


```{r}
fa1 <- factanal(bioData[,2:18], factors = 3, rotation="varimax")
print(fa1, digits=2, cutoff=.6, sort=TRUE)
```

Is such factor representation enough? Compare the model with some others for the increasing number of factors used: 

```{r}
fa2 <- factanal(bioData[,2:18], factors = 4, rotation="varimax")
fa3 <- factanal(bioData[,2:18], factors = 5, rotation="varimax")
fa4 <- factanal(bioData[,2:18], factors = 9, rotation="varimax")
```

There are mainly two different approaches on how to define the number of factors which should be used. 
For instance, it is easy to see that for each element $X_{j}$ from the random vector $\boldsymbol{X} = (X_{1}, \dots, X_{p})^\top$
it holds that

$$
var(X_{j}) =h_{j}^2 + \psi_{j}, \qquad \textrm{where} \qquad h_{j}^2 = \sum_{\ell = 1}^{k} q_{j \ell}^2,
 $$
 
 and $\boldsymbol{\psi} = Diag\{\psi_{1}, \dots, \psi_{k}\}$, and $\Lambda = \{q_{i j}\}_{i, j = 1}^{k}$. The quantity $h_{j}^2$ is the overall variability of $X_{j}$
 which is explained by the common factors in $F$ (also called the communality) while the second quantity, $\psi_{j}$ is the variability which is left (also called the specific variability).<br><br>
 
To decide on how many factors are needed, one can base his decision on the comparison of the communality and the specific varibility. It is obvious, that for $k = p$ the following holds: $h_{j}^2 = var(X_{j})$ and $\psi_{j} = 0$.<br><br>

<b>Alternative approaches to judge the right number of factors:</b>
<ul>
<li><b>Statistical pre-analysis</b><br>
One usually runs e.g. a principal components analysis to determin how many factors should be enough (in order to have some reasonable proportion of the overal variability explained);<br><br></li>

<li><b>Expert judgement</b><br>
Sometimes (under some optimal interpretation options) the estimated factors nice correspond with some latent variables which are not observed, however, can be indentified by some expert judgement. <br><br></li>

<li><b>Maximum Likelihood Test</b><br>
Using the likelihood approach we can also test the null hypothesis $H_{0}$ that $\Sigma = \Lambda\Lambda^\top + \boldsymbol{\psi}$ against a general altternative $H_{1}$ 
specifing no restrictions on the variance covariance matrix $\Sigma$. The likelihood ratio test is given by the test statistic
$$
T = - 2 log \Bigg[\frac{\textrm{maximum likelihood under $H_{0}$}}{\textrm{maximum likelihood under $H_{1}$}}\Bigg]
$$
<br><br></li>
</ul>

<br><br>


#### <font color = "#880000">Note</font>
<ul>
<li>Another option on how to determine the optimal number of factor to be extracted in the analysis is 
to use the tools from the library 'nFactors' (the library can be installed by `install.packages("nFactors")`);</li>
</ul>
<hr size="3" width="100%" noshade style="color:#440000" align="left" />


```{r, warning = F, message = F, fig.width=10, fig.height=6}
library(nFactors)
ev <- eigen(cor(bioData[,2:18])) 
ap <- parallel(subject=nrow(bioData[,2:18]),var=ncol(bioData[,2:18]), rep=100, cent=.05)
nS <- nScree(x=ev$values, aparallel=ap$eigen$qevpea)

plotnScree(nS)
```



```{r, fig.width=10, fig.height=6}
load <- fa1$loadings[,1:2] 
plot(load,type="n") 
text(load,labels=names(bioData[,2:18]),cex=.7)
```


Alternatively, using the library `FactoMineR` and function `PCA()` we can obtain the complete factor map (covariate map with the mutual correlation). 

```{r, fig.width = 10}
library(FactoMineR)
result <- PCA(bioData[,2:18])
```

<br><br>

#### <font color = "#880000">Note</font>
<hr size="3" width="100%" noshade style="color:#440000" align="left" />
<ul>
<li>The `factanal()` function in R uses scaled variables as the starting point for the factor analysis - the variance-covariance matrix of $\boldsymbol{X}$ is replaced by the corresponding correlation matrix with ones on its diagonal. </li>
</ul>
<hr size="3" width="100%" noshade style="color:#440000" align="left" />
<br>


Now, we an idea that maybe three factors should be ok. In orther to get the corresponding score values (those are values of $\boldsymbol{F}$ in the expression above given for each observations - in our case $n = 65$) from the `factanal()` function we need an additional parameter to be specified: 

```{r}
fa1 <- factanal(bioData[,2:18], factors = 3, scores = "regression")
fa1$scores
```

and the corresponding loadings (matrix $\Lambda$ in the expression above) is obtained as

```{r}
fa1$loadings
```

<br><br>

### <font color = "#880000"><b>Application in Regression or SEM</b></font>
Structural Equation Models (SEM) are statistical modelling techniqes showing great potential especially in causal dependencies between endogenous and exogenous variables, and the measurement model showing the relations between latent variables and their indicators (which is also the case of the latent factors $F$ in the factor analysis). <br><br>

It this situations is common to firstly draw a schematic diagram with the assumed underlying structure. Later, the diagram is used to specify the final model. <br><br>

An example of such diagram is below. 

<center>
<img src = "sem.jpg", width = 900>
</center>

<br><br>


In the R software there is package 'sem' available for the structural equation modelling. 

```{r}
library("sem")
```

and a simple example using the dataset 'PoliticalDemocracy' from the package `library("lavaan")`: 

```{r}
library("lavaan")
data(PoliticalDemocracy)
PoliticalDemocracy
```

with the corresponding model structure, which we want to fit: 

<center>
<img src = "lavaan.png", width = 900>
</center>

Firstly, we define the model:

```{r}
model <- '
  # measurement model
    ind60 =~ x1 + x2 + x3
    dem60 =~ y1 + y2 + y3 + y4
    dem65 =~ y5 + y6 + y7 + y8
  # regressions
    dem60 ~ ind60
    dem65 ~ ind60 + dem60
  # residual correlations
    y1 ~~ y5
    y2 ~~ y4 + y6
    y3 ~~ y7
    y4 ~~ y8
    y6 ~~ y8
'
```

later, the covariates: 

```{r}
variable ~~ variable
```


and finaly, we can fit the model: 

```{r}
fit <- sem(model, data=PoliticalDemocracy)
summary(fit, standardized=TRUE)
```


<br><br><br>

## <font color = "#880000"><b>Homework Assignment</b></font>
### (Deadline: Lab Session 8 / 25.04.2007)

Use the command below to instal the `SMSdata` packages with various multivariate datasets: 

```{r, eval = F}
install.packages(pkgs="http://www.karlin.mff.cuni.cz/~hlavka/sms2/SMSdata_1.0.tar.gz", repos=NULL, type="source")
```

Chose one dataset of your choise from the list of all available datasets in the package:

```{r, eval = F}
data(package = "SMSdata") 
```
 
 There are 21 different datasets and you can load each of them by typing and running 
`data(dataset_name)`, for instance:

```{r, eval = F}
data(plasma) 
```

<ul>
<li>Consider the same dataset you applied the principal component analysis to and apply the factor analysis now; </li>

<li>Compare the outcomes of both, PCA and FA;</li>

<li>Chose one covariate as the dependent covariate and try to use the regression modelling approach to model the expectation of this 
covariate using the factors obtained from the factor analysis. Try to find some reasonable interpretation of the final model.</li>
</ul>


</td></tr></table>
<br><br><br>