<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/naive-principal-component-analysis-using-r/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://r-posts.com/naive-principal-component-analysis/"> R-posts.com</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>Post from <a rel="nofollow" href="https://www.linkedin.com/in/pablobernabeu/" target="_blank">Pablo Bernabeu’s blog</a>.</p>
<p> <a rel="nofollow" href="https://www.google.nl/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwj_s7Dj85HWAhVIL1AKHblGDvsQFggxMAA&url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FPrincipal_component_analysis&usg=AFQjCNHYiXpH6Nw1a16AciftvzyCMLNaPQ" target="_blank">Principal Component Analysis</a> (PCA) is a technique used to find the core components that underlie different variables. It comes in very useful whenever doubts arise about the true origin of three or more variables. There are two main methods for performing a PCA: naive or less naive. In the naive method, you first check some conditions in your data which will determine the essentials of the analysis. In the less-naive method, you set the those yourself, based on whatever prior information or purposes you had. I will tackle the naive method, mainly by following the guidelines in<span> </span><a rel="nofollow" href="https://freethegeogbooks.files.wordpress.com/2016/08/book-for-r-language-stats.pdf" target="_blank">Field, Miles, and Field (2012)</a>, with updated code where necessary. This<span> </span><a rel="nofollow" href="https://www.researchgate.net/file.PostFileLoader.html?id=566435736225ff665e8b4577&assetKey=AS%3A303652726607873%401449407859829" target="_blank">lecture material</a><span> </span>was also useful.</p>
<p>The ‘naive’ approach is characterized by a first stage that checks whether the PCA should actually be performed with your current variables, or if some should be removed. The variables that are accepted are taken to a second stage which identifies the number of principal components that seem to underlie your set of variables. I ascribe these to the ‘naive’ or formal approach because either or both could potentially be skipped in exceptional circumstances, where the purpose is not scientific, or where enough information exists in advance.</p>
<h3>STAGE 1.  Determine whether PCA is appropriate at all, considering the variables</h3>
<ul>
<li>Variables should be<span> </span><strong>inter-correlated enough but not too much.<span> </span></strong>Field et al. (2012) provide some thresholds, suggesting that no variable should have many correlations below .30,<img data-orig-file="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/09/corrs.png?fit=1050%2C373" data-orig-size="1050,373" data-medium-file="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/09/corrs.png?fit=450%2C160" data-attachment-id="285" data-image-meta="{" data-image-description="" src="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/09/corrs.png?resize=363%2C129" data-permalink="http://r-posts.com/naive-principal-component-analysis/corrs/" data-large-file="https://i0.wp.com/r-posts.com/wp-content/uploads/2017/09/corrs.png?fit=450%2C160" alt="" data-image-title="corrs" sizes="(max-width: 363px) 100vw, 363px" data-comments-opened="1" class="wp-image-285" data-recalc-dims="1"> or<span> </span><em>any</em><span> </span>correlation at all above .90. Thus, in the example here, variable Q06 should probably be excluded from the PCA.</li>
<li><strong>Bartlett’s test</strong>, on the nature of the intercorrelations, should be significant. Significance suggests that the variables are not an ‘identity matrix’ in which correlations are a sampling error.</li>
<li><strong>KMO</strong><span> </span>(Kaiser-Meyer-Olkin), a measure of sampling adequacy based on common variance (so similar purpose as Bartlett’s). As Field et al. review, ‘values between .5 and .7 are mediocre, values between .7 and .8 are good, values between .8 and .9 are great and values above .9 are superb’ (p. 761). There’s a general score as well as one per variable. The general one will often be good, whereas the individual scores may more likely fail. Any variable with a score below .5 should probably be removed, and the test should be run again.</li>
<li><strong>Determinant:</strong><span> </span>A formula about multicollinearity. The result should preferably fall below .00001.</li>
</ul>
<p>Note that some of these tests are run on the dataframe and others on a correlation matrix of the data, as distinguished below.</p>
<pre> # Necessary libraries
library(ltm)
library(lattice)
library(psych)
library(car)
library(pastecs)
library(scales)
library(ggplot2)
library(arules)
library(plyr)
library(Rmisc)
library(GPArotation)
library(gdata)
library(MASS)
library(qpcR)
library(dplyr)
library(gtools)
library(Hmisc)

# Select only your variables of interest for the PCA
dataset = mydata[, c('select_var1','select_var1',
'select_var2','select_var3','select_var4',
'select_var5','select_var6','select_var7')]

# Create matrix: some tests will require it
data_matrix = cor(dataset, use = 'complete.obs')

# See intercorrelations
round(data_matrix, 2)

# Bartlett's
cortest.bartlett(dataset)

# KMO<span> (Kaiser-Meyer-Olkin)</span>
KMO(data_matrix)

# Determinant
det(data_matrix)</pre>
<h3>STAGE 2.  Identify number of components (aka factors)</h3>
<p>In this stage, principal components (formally called ‘factors’ at this stage) are identified among the set of variables.</p>
<ul>
<li>The identification is done through a basic, ‘unrotated’ PCA. The number of components set a priori must equal the number of variables that are being tested.</li>
</ul>
<pre> # Start off with unrotated PCA

pc1 = psych::principal(dataset, nfactors = 
length(dataset), rotate=&quot;none&quot;)
pc1 </pre>
<p><span>Below, an example result:</span></p>
<pre> ## Principal Components Analysis
## Call: psych::principal(r = eng_prop, nfactors = 3, rotate = &quot;none&quot;)
## Standardized loadings (pattern matrix) based upon correlation matrix
##           PC1   PC2  PC3 h2       u2 com
## Aud_eng -0.89  0.13 0.44  1 -2.2e-16 1.5
## Hap_eng  0.64  0.75 0.15  1  1.1e-16 2.0
## Vis_eng  0.81 -0.46 0.36  1 -4.4e-16 2.0
## 
##                        PC1  PC2  PC3
## SS loadings           1.87 0.79 0.34
## Proportion Var        0.62 0.26 0.11
## Cumulative Var        0.62 0.89 1.00
## Proportion Explained  0.62 0.26 0.11
## Cumulative Proportion 0.62 0.89 1.00
## 
## Mean item complexity =  1.9
## Test of the hypothesis that 3 components are sufficient.
## 
## The root mean square of the residuals (RMSR) is  0 
##  with the empirical chi square  0  with prob &lt;  NA 
## 
## Fit based upon off diagonal values = 1 </pre>
<p></p>
<p>Among the columns, there are first the correlations between variables and components, followed by a column (h2) with the ‘<strong>communalities</strong>‘. If less factors than variables had been selected, communality values would be below 1. Then there is the uniqueness column (u2):<span> </span><strong>uniqueness</strong><span> </span>is equal to 1 minus the communality. Next is ‘com’, which reflects the<span> </span><strong>complexity</strong><span> </span>with which a variable relates to the principal components. Those components are precisely found below. The first row contains the sums of squared loadings, or eigenvalues, namely, the total variance explained by each linear component. This value corresponds to the number of units explained out of all possible factors (which were three in the above example). The rows below all cut from the same cloth.<span> </span><em>Proportion var</em><span> </span>= variance explained over a total of 1. This is the result of dividing the eigenvalue by the number of components. Multiply by 100 and you get the percentage of total variance explained, which becomes useful. In the example, 99% of the variance has been explained. Aside from the meddling maths, we should actually expect 100% there because the number of factors equaled the number of variables.<span> </span><em>Cumulative var:</em><span> </span>variance added consecutively up to the last component.<span> </span><em>Proportion explained:</em><span> </span>variance explained over what has actually been explained (only when variables = factors is this the same as Proportion var).<span> </span><em>Cumulative proportion:</em><span> </span>the actually explained variance added consecutively up to the last component.</p>
<p>Two sources will determine the number of components to select for the next stage:</p>
<ul>
<li><strong>Kaiser’s criterion:</strong> components with SS loadings > 1. In our example, only PC1.</li>
</ul>
<p>A more lenient alternative is Joliffe’s criterion, SS loadings > .7.</p>
<ul>
<li><strong>Scree plot:<span> </span></strong>the number of points after point of inflexion. For this plot, call:</li>
</ul>
<pre> plot(pc1$values, type = 'b') </pre>
<p><img data-orig-file="https://i2.wp.com/r-posts.com/wp-content/uploads/2017/09/sc.png?fit=1326%2C748" data-orig-size="1326,748" data-medium-file="https://i2.wp.com/r-posts.com/wp-content/uploads/2017/09/sc.png?fit=450%2C254" data-attachment-id="291" data-image-meta="{" data-image-description="" src="https://i2.wp.com/r-posts.com/wp-content/uploads/2017/09/sc.png?resize=303%2C171" data-permalink="http://r-posts.com/naive-principal-component-analysis/sc/" data-large-file="https://i2.wp.com/r-posts.com/wp-content/uploads/2017/09/sc.png?fit=450%2C254" alt="" data-image-title="sc" sizes="(max-width: 303px) 100vw, 303px" data-comments-opened="1" class="wp-image-291" data-recalc-dims="1"></p>
<p>Imagine a straight line<span> </span><strong>from the first point on the right.<span> </span></strong>Once this line bends considerably, count the points after the bend and up to the last point on the left. The number of points is the number of components to select. The example here is probably the most complicated (two components were finally chosen), but normally it’s<span> </span><a rel="nofollow" href="https://www.google.nl/search?q=select+principal+components+scree+plot+point+inflexion&source=lnms&tbm=isch&sa=X&ved=0ahUKEwi00ujoto_WAhXJbVAKHbTCBAgQ_AUICigB&biw=1280&bih=619" target="_blank">not difficult</a>.</p>
<p>Based on both criteria, go ahead and select the definitive number of components.</p>
<h3>STAGE 3.  Run definitive PCA</h3>
<p>Run a very similar command as you did before, but now with a more advanced method. The first PCA, a heuristic one, worked essentially on the inter-correlations. The definitive PCA, in contrast, will implement a prior shuffling known as ‘rotation’, to ensure that the result is robust enough (just like cards are shuffled). Explained variance is captured better this way. The go-to rotation method is the orthogonal, or ‘varimax’ (though others may be considered too).</p>
<pre> # Now with varimax rotation, Kaiser-normalized 
# by default:
pc2 = psych::principal(dataset, nfactors=2, 
rotate = &quot;varimax&quot;, scores = TRUE)
pc2
pc2$loadings

# Healthcheck
pc2$residual
pc2$fit
pc2$communality </pre>
<p>We would want:</p>
<ul>
<li>Less than half of<span> </span><strong>residuals<span> </span></strong>with absolute values > 0.05</li>
<li>Model<span> </span><strong>fit<span> </span></strong>> .9</li>
<li>All<span> </span><strong>communalities</strong><span> </span>> .7</li>
</ul>
<p>If any of this fails, consider changing the number of factors. Next, the rotated components that have been ‘extracted’ from the core of the set of variables can be added to the dataset. This would enable the use of these components as new variables that might prove powerful and useful (as in<span> </span><a rel="nofollow" href="http://onlinelibrary.wiley.com/doi/10.1111/j.1551-6709.2010.01157.x/full" target="_blank">this research</a>).</p>
<pre> dataset = cbind(dataset, pc2$scores)
summary(dataset$RC1, dataset$RC2) </pre>
<h3>STAGE 4.  Determine ascription of each variable to components<br>
<img data-orig-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/09/corrrs.png?fit=2003%2C521" data-orig-size="2003,521" data-medium-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/09/corrrs.png?fit=450%2C117" data-attachment-id="290" data-image-meta="{" data-image-description="" src="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/09/corrrs.png?resize=450%2C117" data-permalink="http://r-posts.com/naive-principal-component-analysis/corrrs/" data-large-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/09/corrrs.png?fit=450%2C117" alt="" data-image-title="corrrs" sizes="(max-width: 450px) 100vw, 450px" data-comments-opened="1" class="wp-image-290" data-recalc-dims="1"></h3>
<p><span>Check the main summary by just calling pc2, and see how each variable correlates with the rotated components. This is essential because it reveals how variables load on each component, or in other words, to which component a variable belongs. For instance, the table shown here belongs to a </span><a rel="nofollow" href="https://www.linkedin.com/pulse/modality-exclusivity-norms-336-properties-411-dutch-english-bernabeu/?published=t" target="_blank">study about meaning of words</a><span>. These results suggest that the visual and haptic modalities of words are quite related, whereas the auditory modality is relatively unique. When the analysis works out well, a cut-off point of </span><em>r</em><span> = .8 may be applied for considering a variable as part of a component.</span></p>
<h3>STAGE 5.  Enjoy the plot</h3>
<p>The plot is perhaps the coolest part about PCA. It really makes an awesome illustration of the power of data analysis.</p>
<pre> ggplot(dataset,
  aes(RC1, RC2, label = as.character(main_eng))) +
  aes (x = RC1, y = RC2, by = main_eng) + stat_density2d(color = &quot;gray87&quot;)+
  geom_text(size = 7) +
    ggtitle ('English properties') +
    theme_bw() +
    theme(  
    plot.background = element_blank()
   ,panel.grid.major = element_blank()
   ,panel.grid.minor = element_blank()
   ,panel.border = element_blank()
  ) +
  theme(axis.line = element_line(color = 'black')) + 
    theme(axis.title.x = element_text(colour = 'black', size = 23, 
    margin=margin(15,15,15,15)),
         axis.title.y = element_text(colour = 'black', size = 23, 
    margin=margin(15,15,15,15)),
         axis.text.x  = element_text(size=16),
       axis.text.y  = element_text(size=16)) +
  labs(x = &quot;&quot;, y = &quot;Varimax-rotated Principal Component 2&quot;) +
    theme(plot.title = element_text(hjust = 0.5, size = 32, face = &quot;bold&quot;,
    margin=margin(15,15,15,15))) </pre>
<p><span><br>
Below is an example combining PCA plots with code similar to the above. These plots illustrate something further with regard to the relationships among modalities. In property words, the different modalities spread out more clearly than they do in concept words. This makes sense because in language, properties define concepts (</span><a rel="nofollow" href="https://www.linkedin.com/pulse/modality-exclusivity-norms-336-properties-411-dutch-english-bernabeu?published=t" target="_blank">see more</a><span>).<br>
</span><br>
<img data-orig-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/09/all-four-plots.png?fit=1188%2C1174" data-orig-size="1188,1174" data-medium-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/09/all-four-plots.png?fit=304%2C300" data-attachment-id="289" data-image-meta="{" data-image-description="" src="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/09/all-four-plots.png?resize=660%2C652" data-permalink="http://r-posts.com/naive-principal-component-analysis/all-four-plots/" data-large-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2017/09/all-four-plots.png?fit=450%2C445" alt="" data-image-title="all four plots" sizes="(max-width: 660px) 100vw, 660px" data-comments-opened="1" class="wp-image-289" data-recalc-dims="1"></p>
<p>An example of this code is use is<span> </span><a rel="nofollow" href="https://osf.io/mkv94/" target="_blank">available here</a><span> </span>(with<span> </span><a rel="nofollow" href="https://osf.io/ge7pn/" target="_blank">data here</a>).</p>
<p>References<br>
Field, A. P., Miles, J., &amp; Field, Z. (2012). <em>Discovering statistics using R</em>. London: Sage.</p>
<p>Feel free to comment below or on the <a rel="nofollow" href="https://www.linkedin.com/pulse/naive-principal-component-analysis-r-pablo-bernabeu" target="_blank">original post</a>.</p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://r-posts.com/naive-principal-component-analysis/"> R-posts.com</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/-JvwfaERAeY" height="1"></a></div>