% \VignetteIndexEntry{Overview of the psych package}
% \VignettePackage{psych}
% \VignetteKeywords{multivariate}
% \VignetteKeyword{models}
% \VignetteKeyword{Hplot}
%\VignetteDepends{psych}
%\documentclass[doc]{apa}
\documentclass[11pt]{article}
%\documentclass[11pt]{amsart}
\usepackage{geometry}                % See geometry.pdf to learn the layout options. There are lots.
\geometry{letterpaper}                   % ... or a4paper or a5paper or ... 
%\geometry{landscape}                % Activate for for rotated page geometry
\usepackage[parfill]{parskip}    % Activate to begin paragraphs with an empty line rather than an indent
\usepackage{graphicx}
\usepackage{amssymb}
\usepackage{epstopdf}
\usepackage{mathptmx}
\usepackage{helvet}
\usepackage{courier}
\usepackage{epstopdf}
\usepackage{makeidx}        % allows index generation
\usepackage[authoryear,round]{natbib} 
\usepackage{gensymb}
\usepackage{longtable}
%\usepackage{geometry}   
\usepackage{Sweave}  
%\usepackage{/Library/Frameworks/R.framework/Versions/2.7/Resources/share/texmf/Sweave}
%\usepackage[ae]{Rd}
%\usepackage[usenames]{color}
%\usepackage{setspace}
\usepackage{amssymb}    
\usepackage{amsmath}
%\DeclareGraphicsRule{.tif}{png}{.png}{`convert #1 `dirname #1`/`basename #1 .tif`.png}
\bibstyle{apacite}
\bibliographystyle{apa}   %this one plus author year seems to work?
%\usepackage{hyperref}
\usepackage[colorlinks=true,citecolor=blue]{hyperref}  %this makes reference links hyperlinks in pdf!


\DeclareGraphicsRule{.tif}{png}{.png}{`convert #1 `dirname #1`/`basename #1 .tif`.png}
\usepackage{multicol}        % used for the two-column index
\usepackage[bottom]{footmisc}% places footnotes at page bottom
\let\proglang=\textsf
\newcommand{\R}{\proglang{R}}
%\newcommand{\pkg}[1]{{\normalfont\fontseries{b}\selectfont #1}}
\newcommand{\Rfunction}[1]{{\texttt{#1}}} 
\newcommand{\fun}[1]{{\texttt{#1}\index{#1}\index{R function!#1}}}
\newcommand{\pfun}[1]{{\texttt{#1}\index{#1}\index{R function!#1}\index{R function!psych package!#1}}}\newcommand{\Rc}[1]{{\texttt{#1}}}    %R command  same as Robject
\newcommand{\Robject}[1]{{\texttt{#1}}} 
\newcommand{\Rpkg}[1]{{\textit{#1}\index{#1}\index{R package!#1}}}   %different from pkg  - which is better?
\newcommand{\iemph}[1]{{\emph{#1}\index{#1}}} 
\newcommand{\wrc}[1]{\marginpar{\textcolor{blue}{#1}}}   %bill's comments
\newcommand{\wra}[1]{\textcolor{blue}{#1}}  %bill's comments

\newcommand{\ve}[1]{{\textbf{#1}}} %trying to get a vector command


\makeindex         % used for the subject index

\title{An overview of the psych package}
\author{William Revelle\\Department of Psychology\\Northwestern University}

%\affiliation{Northwestern University}
%\acknowledgements{Written to accompany the psych package.  Comments should be directed to William Revelle \\  \url{revelle@northwestern.edu}}
%\date{}                                         % Activate to display a given date or no date


\begin{document}
\maketitle
\tableofcontents
\section{Overview of this and related documents}

The \Rpkg{psych} package \citep{psych} has been developed at Northwestern University to include functions most useful for personality, psychometric,  and psychological research.  Some of the functions (e.g., \pfun{read.clipboard}, \pfun{describe},  \pfun{pairs.panels}, \pfun{error.bars}) are useful for basic data entry and descriptive analyses.

Psychometric applications include routines for five types of \iemph{factor analysis} (\pfun{fa} does  \iemph{minimum residual}, \iemph{principal axis},   \iemph{weighted least squares}, \iemph{generalized least squares} and \iemph{maximum likelihood} factor analysis). Determining the number of factors or components to extract may be done by using the Very Simple Structure \citep{revelle:vss} (\pfun{vss}), Minimum Average Partial correlation \citep{velicer:76} (\pfun{MAP}) or parallel analysis \pfun{fa.parallel} criteria.  Item Response Theory models for dichotomous or polytomous items may be found by factoring \pfun{tetrachoric} or \pfun{polychoric} correlation matrices and expressing the resulting parameters in terms of location and discrimination \pfun{irt.fa}.  Bifactor and hierarchical factor structures may be estimated by using Schmid Leiman transformations \citep{schmid:57} (\pfun{schmid}) to transform a hierarchical factor structure into a bifactor solution \citep{holzinger:37}. Scale construction can be done using the Item Cluster Analysis \citep{revelle:iclust} (\pfun{iclust}) function to determine the structure  and to calculate reliability coefficients $\alpha$ \cite{cronbach:51}(\pfun{alpha}, \pfun{score.items}, \pfun{score.multiple.choice}), $\beta$ \citep{revelle:iclust,rz:09} (\pfun{iclust}) and McDonald's $\omega_h$ and $\omega_t$ \citep{mcdonald:tt} (\pfun{omega}). Guttman's six estimates of internal consistency reliability (\cite{guttman:45}, as well as additional estimates \citep{rz:09} are in the  \pfun{guttman} function and the six measures of Intraclass correlation coefficients (\pfun{ICC}) discussed by \cite{shrout:79} are also available.

Graphical displays include Scatter Plot Matrix (SPLOM) plots using \pfun{pairs.panels}, factor, cluster, and  structural diagrams using \pfun{fa.diagram}, \pfun{iclust.diagram}, \pfun{structure.diagram}, as well as item response characteristics and item and test information characteristic curves \pfun{plot.irt}.   


This vignette is meant to give an overview of  the  \Rpkg{psych} package.  That is, it is meant to give a summary of the main functions in the \Rpkg{psych} package with examples of how they are used for data description, dimension reduction, and scale construction.  The extended  user manual at \url{psych_manual.pdf} includes examples of graphic output and more extensive demonstrations than are found in the help menus. (Also available at \url{http://personality-project.org/r/psych_manual.pdf}).  The vignette, psych for sem,  at \url{psych_for_sem.pdf}, discusses how to use psych as a front end to the \Rpkg{sem} package of John Fox \citep{sem}. (The vignette is also available at \href{"http://personality-project.org/r/book/psych_for_sem.pdf"}{\url{http://personality-project.org/r/book/psych_for_sem.pdf}}).

For a step by step tutorial in the use of the psych package and the base functions in R for basic personality research, see the  guide for using \R{} for personality research at \url{http://personalitytheory.org/r/r.short.html}.  For an \iemph{introduction to psychometric theory with applications in \R{}}, see the draft chapters at \url{http://personality-project.org/r/book}).



\section{Getting started} 
Some of the functions described in this overview require other packages.  Particularly useful for rotating the results of factor analyses (from e.g.,  \pfun{fa}, \pfun{factor.minres}, \pfun{factor.pa}, \pfun{factor.wls}, or  \pfun {principal}) or hierarchical factor models using \pfun{omega} or \pfun{schmid}, is the \Rpkg{GPArotation} package.  For some analyses of  correlations of dichotomous data, the \Rpkg{polycor} package is suggested in order to use either the \pfun{poly.mat} or \pfun{phi2poly} functions.  However, these functions have been supplement with \pfun{tetrachoric} and \pfun{polychoric} which do not require the  
\Rpkg{polycor} package. These and other useful packages may be installed by first installing and then using the task views (\Rpkg{ctv}) package to install the ``Psychometrics" task view, but doing it this way is not necessary.  


\begin{Schunk}
\begin{Sinput}
install.packages("ctv")
library(ctv)
task.views("Psychometrics")
\end{Sinput}
\end{Schunk} 

Because of the difficulty of installing the  package \Rpkg{Rgraphviz}, alternative graphics have been developed and are available as \iemph{diagram} functions.   If \Rpkg{Rgraphviz} is available, some functions will take advantage of it.


\section{Basic data analysis}
A number of \Rpkg{psych} functions facilitate the entry of data and finding basic descriptive statistics.

Remember, to run any of the \Rpkg{psych} functions, it is necessary to make the package active by using the \fun{library} command: 

\begin{Schunk}
\begin{Sinput}
> library(psych)
\end{Sinput}
\end{Schunk} 

The other packages, once installed, will be called automatically by \Rpkg{psych}. 

It is possible to automatically load  \Rpkg{psych} and other functions by creating and then saving a ``.First" function:



\begin{Schunk}
\begin{Sinput}
.First <-  function(x) {library(psych)}
\end{Sinput}
\end{Schunk} 


\subsection{Data input and descriptive statistics}

There are of course many ways to enter data into \R.  Reading from a local file using \fun{read.table} is perhaps the most preferred.  However, many users will enter their data in a text editor or spreadsheet program and then want to copy and paste into \R{}.  This may be done by using \fun{read.table} and specifying the input file as ``clipboard" (PCs) or ``pipe(pbpaste)" (Macs). Alternatively, the  \pfun{read.clipboard} set of functions are perhaps more user friendly:

 \begin{description}
 \item [\pfun{read.clipboard}] is the base function for reading data from the clipboard.
 \item [\pfun{read.clipboard.csv}] for reading text that is comma delimited. 
  \item [\pfun{read.clipboard.tab}] for reading text  that is tab delimited. 
 \item [\pfun{read.clipboard.lower}] for reading input of a lower triangular matrix with or without a diagonal.  The resulting object is a square matrix.
 \item [\pfun{read.clipboard.upper}] for reading input of an upper triangular matrix.
 \item[\pfun{read.clipboard.fwf}] for reading in fixed width fields (some very old data sets)
 \end{description}
 
 For example, given a data set copied to the clipboard from a spreadsheet, just enter the command
 
\begin{Schunk}
\begin{Sinput}
> my.data <- read.clipboard()
\end{Sinput}
\end{Schunk} 

This will work if every data field has a value and even missing data are given some values (e.g., NA or -999). If the data were entered in a spreadsheet and the missing values were just empty cells, then the data should be read in as a tab delimited or by using the \pfun{read.clipboard.tab} function.

\begin{Schunk}
\begin{Sinput}
> my.data <- read.clipboard(sep="\t")   #define the tab option, or 
> my.tab.data <- read.clipboard.tab()   #just use the alternative function
\end{Sinput}
\end{Schunk} 
For the case of data in fixed width fields (some old data sets tend to have this format), copy to the clipboard and then specify the width of each field (in the example below, the first variable is 5 columns, the second is 2 columns, the next 5 are 1 column the last 4 are 3 columns). 
\begin{Schunk}
\begin{Sinput}
> my.data <- read.clipboard.fwf(widths=c(5,2,rep(1,5),rep(3,4))
\end{Sinput}
\end{Schunk} 
 

 Once the data are read in, then \pfun{describe} or \pfun{describe.by} will provide basic descriptive statistics arranged in a data frame format. Consider the data set \pfun{sat.act} which includes data from 700 web based participants on 3 demographic variables and 3 ability measures.
\begin{description}
\item[\pfun{describe}] reports means, standard deviations, medians, min, max, range, skew, kurtosis and standard errors for integer or real data. Non-numeric data will produce an error.
\item[\pfun{describe.by}] reports descriptive statistics broken down by some categorizing variable (e.g., gender, age, etc.)
\end{description}


<<print=FALSE,echo=TRUE>>=
library(psych)
data(sat.act) 
describe(sat.act)  #basic descriptive statistics
@


These data may then be analyzed by groups defined in a logical statement or by some other variable.  E.g., break down the descriptive data for males or females.  These descriptive data can also be seen graphically using the \pfun{error.bars.by} function (Figure~\ref{fig:error.bars}). By setting skew=FALSE and ranges=FALSE, the output is limited to the most basic statistics.


<<print=FALSE,echo=TRUE>>= 
describe.by(sat.act,sat.act$gender,skew=FALSE,ranges=FALSE) #basic descriptive statistics by a grouping variable.
@

The output from the describe.by function can be forced into a matrix form for easy analysis by other programs.  In addition, describe.by can group by several grouping variables at the same time.

<<print=FALSE,echo=TRUE>>= 
sa.mat <- describe.by(sat.act,list(sat.act$gender,sat.act$education),
 skew=FALSE,ranges=FALSE,mat=TRUE)
head(sa.mat)
tail(sa.mat)
@

\subsubsection{Basic data cleaning using \pfun{scrub}}
If, after describing the data it is apparent that there were data entry errors that need to be globally replaced with NA,  or only certain ranges of data will be analyzed, the data can be ``cleaned" using the \pfun{scrub} function.

Consider the \fun{attitude} data set (which does not need to be cleaned, but will be used as an example). All values of columns 3 - 5 that are less than 30, 40, or 50 respectively, or greater than 70 in any column will be replaced with NA.  In addition, any value exactly equal to 45 will be set to NA.  (max and isvalue are set to one value here, but they could be a different value for every column).

<<print=FALSE,echo=TRUE>>= 
x <- matrix(1:120,ncol=10,byrow=TRUE)
new.x <- scrub(x,3:5,min=c(30,40,50),max=70,isvalue=45)
new.x
@
Note that the number of subjects for those columns has decrease, and the minimums have gone up but the maximums down.  Data cleaning and examination for outliers should be a routine part of any data analysis.

\subsection{Simple descriptive graphics}

Scatter Plot Matrices (SPLOMS) are very useful for describing the data.  The \pfun{pairs.panels} function, adapted from the help menu for the \fun{pairs} function produces xy scatter plots of each pair of variables below the diagonal, shows the histogram of each variable on the diagonal, and shows the \iemph{lowess} locally fit regression line as well. An ellipse around the mean with the axis length reflecting one standard deviation of the first and second principal components is also drawn. The x axis in each scatter plot represents the column variable, the y axis the row variable  (Figure~\ref{fig:pairs.panels}).

\begin{description}
\item[\pfun{pairs.panels} ] will show the pairwise scatter plots of all the variables as well as histograms, locally smoothed regressions, and the Pearson correlation.
\end{description}

\begin{figure}[htbp]
\begin{center}
<<print=FALSE,echo=TRUE, fig=TRUE,eps=FALSE>>=
pairs.panels(sat.act)
@
\caption{Using the \pfun{pairs.panels} function to graphically show relationships. The x axis in each scatter plot represents the column variable, the y axis the row variable. Note the extreme outlier for the ACT.  }
\label{fig:pairs.panels}
\end{center}
\end{figure}

Another example of \pfun{pairs.panels} is to show differences between experimental groups.  Consider the data in the \pfun{affect} data set.  The scores reflect post test scores on positive and negative affect and energetic and tense arousal.  The colors show the results for four movie conditions: depressing, frightening movie, neutral, and a comedy.  

\begin{figure}[htbp]
\begin{center}
<<print=FALSE,echo=TRUE, fig=TRUE,eps=FALSE>>=
data(affect)
pairs.panels(flat[15:18],bg=c("red","black","white","blue")[maps$Film],pch=21,main="Affect varies by movies (study 'flat')")
@
\caption{Using the \pfun{pairs.panels} function to graphically show relationships. The x axis in each scatter plot represents the column variable, the y axis the row variable. The coloring represent four different movie conditions. }
\label{fig:pairs.panels2}
\end{center}
\end{figure}


Additional descriptive graphics include the ability to draw \iemph{error bars} on sets of data, as well as to draw error bars in both the x and y directions for paired data.  These are the functions

\begin{description}
\item [\pfun{error.bars}]  show the 95 \% confidence intervals for each variable in a data frame or matrix.
\item [\pfun{error.bars.by}] does the same, but grouping the data by some condition.
\item [\pfun{error.crosses}]  draw the confidence intervals for an x set and a y set of the same size.
\end{description}

The use of the \pfun{error.bars.by} function allows for graphic comparisons of different groups (see Figure~\ref{fig:error.bars}).  Five personality measures are shown as a function of high versus low scores on a ``lie" scale. People with higher lie scores tend to report being more agreeable, conscientious and less neurotic than people with lower lie scores.  The error bars are based upon normal theory and thus are symmetric rather than reflect any skewing in the data.

\begin{figure}[htbp]
\begin{center}
<<print=FALSE,echo=TRUE, fig=TRUE,eps=FALSE>>=
data(epi.bfi)
error.bars.by(epi.bfi[,6:10],epi.bfi$epilie<4)
@
\caption{Using the \pfun{error.bars.by} function shows that self reported personality scales on the Big Five Inventory vary as a function of the Lie scale on the EPI. }
\label{fig:error.bars}
\end{center}
\end{figure}

Although not recommended, it is possible to use the \pfun{error.bars} function to draw bar graphs with associated error bars.  (This kind of`\iemph{dynamite plot} (Figure~\ref{fig:dynamite}) can be very misleading in that the scale is arbitrary.  Go to  a discussion of the problems in presenting data this way at \url{http://emdbolker.wikidot.com/blog:dynamite}. 

\begin{figure}[htbp]
\begin{center}
<<print=FALSE,echo=TRUE, fig=TRUE,eps=FALSE>>=
error.bars.by(sat.act[5:6],sat.act$gender,bars=TRUE,labels=c("Male","Female"),ylab="SAT score",xlab="")
@
\caption{A ``Dynamite plot" of SAT scores as a function of gender is one way of misleading the reader. By using a bar graph, the range of scores is ignored. }
\label{fig:dynamite}
\end{center}
\end{figure}

It is also possible to see the structure in a correlation matrix by forming a matrix shaded to represent the magnitude of the correlation.  This is useful when considering the number of factors in a data set.  Consider the \pfun{Thurstone} data in the \pfun{bifactor} data set which has a clear 3 factor solution (Figure~\ref{fig:cor.plot}) or a simulated data set of 24 variables with a circumplex structure  (Figure~\ref{fig:cor.plot.circ}).

\begin{figure}[htbp]
\begin{center}
<<print=FALSE,echo=TRUE, fig=TRUE,eps=FALSE>>=
data(bifactor)
cor.plot(Thurstone,color=TRUE,main="9 cognitive variables from Thurstone")
@
\caption{The structure of correlation matrix can be seen more clearly if the variables are grouped by factor and then the correlations are shown by color. }
\label{fig:cor.plot}
\end{center}
\end{figure}

\begin{figure}[htbp]
\begin{center}
<<print=FALSE,echo=TRUE, fig=TRUE,eps=FALSE>>=
circ <- sim.circ(24)
r.circ <- cor(circ)
cor.plot(r.circ,color=TRUE,zlim=c(-1,1),main="24 variables in a circumplex")
@
\caption{Using the cor.plot function to show the correlations in a circumplex. Correlations are highest near the diagonal, diminish to zero further from the diagonal, and the increase again towards the corners of the matrix.  Circumplex structures are common in the study of affect.}
\label{fig:cor.plot.circ}
\end{center}
\end{figure}


\subsection{Testing correlations}
Correlations are wonderful descriptive statistics of the data but some people like to test whether these correlations differ from zero, or differ from each other. The \fun{cor.test} function (in the \Rpkg{stats} package)  will test the significance of a single correlation, and the \fun{rcorr} function in the \Rpkg{Hmisc} package will do this for many correlations.  In the \Rpkg{psych} package, the \pfun{corr.test} function reports the correlation (Pearson or Spearman) between all variables in either one or two data frames or matrices, as well as the number of observations for each case, and the (two-tailed) probability for each correlation.  These probability values have not been corrected for multiple comparisons and so should be taken with a great deal of salt.

<<print=FALSE,echo=TRUE>>=
corr.test(sat.act)
@
Testing the difference between any two correlations can be done using the \pfun{r.test} function.  The function actually does four different tests, depending upon the input:

1) For a sample size n, find the t  and p value for a single correlation as well as the confidence interval. 
<<print=FALSE,echo=TRUE>>=
r.test(50,.3)
@

2) For sample sizes of n and n2 (n2 = n if not specified) find the z of the difference between the z transformed correlations divided by the standard error of the difference of two z scores. 
<<print=FALSE,echo=TRUE>>=
r.test(30,.4,.6)
@


3) For sample size n, and correlations ra= r12, rb= r23 and r13 specified, test for the difference of two dependent correlations (Steiger case A).
<<print=FALSE,echo=TRUE>>=
r.test(103,.4,.5,.1)
@

4) For sample size n, test for the difference between two dependent correlations involving different variables. (Steiger case B).
<<print=FALSE,echo=TRUE>>=
r.test(103,.5,.6,.7,.5,.5,.8)  #steiger Case B 
@


To test whether a matrix of correlations differs from what would be expected if the population correlations were all zero, the function \pfun{cortest} follows \cite{steiger:80b} who pointed out that the sum of the squared elements of a correlation matrix, or the Fisher z score equivalents, is distributed as chi square under the null hypothesis that the values are zero (i.e., elements of the identity matrix).  This is particularly useful for examining whether correlations in a single matrix differ from zero or for comparing two matrices.  Although obvious, \pfun{cortest} can be used to test whether the \pfun{sat.act} data matrix produces non-zero correlations (it does).  This is a much more appropriate test when testing whether a residual matrix differs from zero.

<<print=FALSE,echo=TRUE>>=
cortest(sat.act)
@

\section{Item and scale analysis}

The main functions in the \Rpkg{psych} package are for analyzing the structure of items and of scales and for finding various estimates of scale reliability. These may be considered as problems of dimension reduction (e.g., factor analysis, cluster analysis, principal components analysis) and of forming and estimating the reliability of the resulting  composite scales.


\subsection{Dimension reduction through factor analysis and cluster analysis}

Parsimony of description has been a goal of science since at least the famous dictum commonly attributed to William of  Ockham to not multiply entities beyond necessity\footnote{Although probably neither original with Ockham nor directly stated by him \citep{thornburn:1918}, Ockham's razor remains a fundamental principal of science.}. The goal for parsimony is seen in psychometrics as an attempt either to describe (components) or to explain (factors) the relationships between many observed variables in terms of a more limited set of components or latent factors.  

The typical data matrix represents multiple items or scales usually thought to reflect fewer underlying constructs\footnote{\cite{cattell:fa78} as well as \cite{maccallum:07} argue that the data are the result of many more factors than observed variables, but are willing to estimate the major underlying factors.}.  At the most simple, a set of items can be be thought to represent a random sample from one underlying domain or perhaps a small set of domains.  The question for the psychometrician is how many domains are represented and how well does each item represent the domains.  Solutions to this problem are examples of \iemph{factor analysis} (\iemph{FA}), \iemph{principal components analysis} (\iemph{PCA}), and \iemph{cluster analysis} (\emph{CA}). All of these procedures aim to reduce the complexity of the observed data.  In the case of FA, the goal is to identify fewer underlying constructs to explain the observed data.  In the case of PCA, the goal can be mere data reduction, but the interpretation of components is frequently done in terms similar to those used when describing the latent variables estimated by FA.  Cluster analytic techniques, although usually used to partition the subject space rather than the variable space, can also be used to group variables to reduce the complexity of the data by forming   fewer and more homogeneous sets of tests or items.

At the data level the data reduction problem may be solved as a \iemph{Singular Value Decomposition} of the original matrix, although the more typical solution is to find either the \iemph{principal components} or \iemph{factors} of the covariance or correlation matrices. Given the pattern of regression weights from the variables to the components or from the factors to the variables, it is then possible to find (for components) individual \index{component scores} \emph{component} or \iemph{cluster scores} or estimate (for factors)  \iemph{factor scores}.

Several of the functions in \Rpkg{psych} address the problem of data reduction. 

\begin{description}

\item[\pfun{fa}] incorporates five alternative algorithms: \iemph{minres factor analysis}, \iemph{principal axis factor analysis}, \iemph{weighted least squares factor analysis}, \iemph{generalized least squares factor analysis} and \iemph{maximum likelihood factor analysis}. That is, it includes the functionality of three other functions that will be eventually phased out.

\item [\pfun{factor.minres}] Minimum residual factor analysis is a least squares, iterative solution to the factor problem.  minres attempts to minimize the residual (off-diagonal) correlation matrix.  It produces solutions similar to maximum likelihood solutions, but will work even if the matrix is singular. 

\item [\pfun{factor.pa}]  Principal Axis factor analysis is a least squares, iterative solution to the factor problem.  PA will work for cases where maximum likelihood techniques (\fun{factanal}) will not work.  The original communality estimates are either the squared multiple correlations (\pfun{smc}) for each item or 1.

\item [\pfun{factor.wls}]  Weighted least squares factor analysis is a least squares, iterative solution to the factor problem.  It minimizes the (weighted) squared residual matrix.  The  weights are based upon the independent contribution of each variable. 

\item [\pfun{principal}] Principal Components Analysis reports the largest n eigen vectors rescaled by the square root of their eigen values.  

\item [\pfun{factor.congruence}] The congruence between two factors is the cosine of the angle between them.  This is just the cross products of the loadings divided by the  sum of the squared loadings. This differs from the correlation coefficient in that the mean loading is not subtracted before taking the products. \pfun{factor.congruence} will find the cosines between two (or more) sets of factor loadings.

\item [\pfun{vss}] Very Simple Structure \cite{revelle:vss} applies a goodness of fit test to determine the optimal number of factors to extract. It can be thought of as a quasi-confirmatory model, in that it fits the very simple structure (all except the biggest c loadings per item are set to zero where c is the level of complexity of the item) of a factor pattern matrix to the original correlation matrix.  For items where the model is usually of complexity one, this is equivalent to making all except the largest loading for each item 0.  This is typically the solution that the user wants to interpret.  The analysis includes the \pfun{MAP} criterion of \cite{velicer:76} and a $\chi^2$ estimate.
\item [\pfun{fa.parallel}] The parallel factors technique compares the observed eigen values of a correlation matrix with those from random data. 
\item [\pfun{factor.plot}] will plot the loadings from a factor, principal components, or cluster analysis (just a call to plot will suffice).  If there are more than two factors, then a SPLOM of the loadings is generated.

\item[\pfun{fa.diagram}] replaces \pfun{fa.graph} and will draw a path diagram representing the factor structure.  It does not require Rgraphviz and thus  is probably preferred.
\item[\pfun{fa.graph}] requires \fun{Rgraphviz} and will draw a graphic representation of the factor structure. If factors are correlated, this will be represented as well. 


\item[\pfun{iclust} ] is meant to do item cluster analysis using a hierarchical clustering algorithm specifically asking questions about the reliability of the clusters \citep{revelle:iclust}.  Clusters are formed until either coefficient $\alpha$ \cite{cronbach:51} or $\beta$ \cite{revelle:iclust} fail to increase.  
\end{description}

\subsubsection{Minimum Residual Factor Analysis}

The factor model is an approximation of a correlation matrix by a matrix of lower rank. That is, can the correlation matrix, $\vec{_nR_n}$ be approximated by the product of a factor matrix, $\vec{_nF_k}$ and its transpose plus a diagonal matrix of uniqueness.
\begin{equation}
R = FF' + U^2
\end{equation}

The maximum likelihood solution to this equation is found by \fun{factanal} in the \Rpkg{stats} package. Five alternatives are provided in \Rpkg{psych}, all of them are included in the \pfun{fa} function and are called by specifying the factor method (e.g., fm=``minres", fm=``pa", fm=``"wls", fm="gls" and fm="ml"). In the discussion of the other algorithms, the calls shown are to the \pfun{fa} function specifying the appropriate method.


\pfun{factor.minres} attempts to minimize the off diagonal residual correlation matrix by adjusting the eigen values of the original correlation matrix.  This is similar to what is done in \fun{factanal}, but uses an ordinary least squares instead of a maximum likelihood fit function.  The solutions tend to be more similar to the MLE solutions than are the \pfun{factor.pa} solutions. \iemph{min.res} is the default for the \pfun{fa} function.

A classic data set, collected by \cite{thurstone:41} and then reanalyzed by \cite{bechtoldt:61} and discussed by \cite{mcdonald:tt}, is a set of 9 cognitive variables with a clear bi-factor structure \cite{holzinger:37}.  The minimum residual solution was transformed into an oblique solution using the  default option on rotate which uses an oblimin transformation (Table~\ref{tab:factor.minres}).  Alternative rotations and transformations include ``none", ``varimax", ``quartimax", ``bentlerT", and ``geominT" (all of which are orthogonal rotations). as well as  ``promax", ``oblimin", ``simplimax", ``bentlerQ, and``geominQ" and  ``cluster" which are  possible oblique transformations of the solution. The default is to do a oblimin transformation, although prior versions defaulted to varimax. The measures of factor adequacy reflect the multiple correlations of the factors with the best fitting linear regression estimates of the factor scores \citep{grice:01}.

\begin{scriptsize}
\begin{table}[htdp]
\caption{Three correlated factors from the Thurstone 9 variable problem.  By default, the solution is transformed obliquely using oblimin. The extraction method is (by default) minimum residual.}
\begin{center}
<<print=FALSE,echo=TRUE>>=
f3t <- fa(Thurstone,3,n.obs=213)
f3t 
@
\end{center}
\label{tab:factor.minres}
\end{table}%
\end{scriptsize}

\subsubsection{Principal Axis Factor Analysis}
 An alternative, least squares algorithm, \pfun{factor.pa}, does a  Principal Axis factor analysis by iteratively doing an eigen value decomposition of the correlation matrix with the diagonal replaced by the values estimated by the factors of the previous iteration.  This OLS solution is not as sensitive to improper matrices as is the maximum likelihood method, and will sometimes produce more interpretable results. 

The solutions from the \pfun{fa}, the \pfun{factor.minres} and \pfun{factor.pa} as well as the \pfun{principal} functions can be rotated or transformed with a number of options.  Some of these call the \Rpkg{GPArotation} package. Orthogonal rotations are \fun{varimax} and \fun{quartimax}. Oblique transformations include \fun{oblimin}, \fun{quartimin} and then two targeted rotation functions \pfun{Promax} and \pfun{target.rot}. The latter of these will transform a loadings matrix towards an arbitrary target matrix.  The default is to transform towards an independent cluster solution. 
 
Using the Thurstone data set, three factors were requested  and then transformed into an independent clusters solution using \pfun{target.rot}  (Table~\ref{tab:Thurstone}).

\begin{scriptsize}
\begin{table}[htdp]
\caption{The 9 variable problem from Thurstone is a classic example of factoring where there is a higher order factor, g, that accounts for the correlation between the factors. The extraction method was principal axis. The transformation was a targeted transformation to a simple cluster solution.}
\begin{center}
<<print=FALSE,echo=TRUE>>=
data(bifactor)
f3 <- fa(Thurstone,3,n.obs = 213,fm="pa")
f3o <- target.rot(f3)
f3o
@
\end{center}
\label{tab:Thurstone}
\end{table}
\end{scriptsize}

\subsubsection{Weighted Least Squares Factor Analysis}

Similar to the minres approach of minimizing the squared residuals, factor method ``wls" weights the squared residuals by their uniquenesses.  This tends to produce slightly smaller overall residuals. In the example of weighted least squares, the output is shown by using the \pfun{print} function with the cut option set to 0.  That is, all loadings are shown (Table~\ref{tab:Thurstone.wls}).

\begin{scriptsize}
\begin{table}[htdp]
\caption{The 9 variable problem from Thurstone is a classic example of factoring where there is a higher order factor, g, that accounts for the correlation between the factors. The factors were extracted using a weighted least squares algorithm.  All loadings are shown by using the cut=0 option in the \pfun{print.psych} function.}

<<print=FALSE,echo=TRUE>>=
data(bifactor)
f3w <- fa(Thurstone,3,n.obs = 213,fm="wls")
print(f3w,cut=0,digits=3)
@
\label{tab:Thurstone.wls}
\end{table}
\end{scriptsize}

The unweighted least squares solution may be shown graphically using the \pfun{factor.plot} function which is called by the generic \fun{plot} function (Figure~\ref{fig:thurstone}. Factors were transformed obliquely using a oblimin.   These solutions may be shown as item by factor plots  (Figure~\ref{fig:thurstone} or by a structure diagram (Figure~\ref{fig:thurstone.diagram}.

\begin{figure}[htbp]
\begin{center}
<<print=FALSE,echo=TRUE, fig=TRUE,eps=FALSE>>=
plot(f3t)
@
\caption{A graphic representation of the 3 oblique factors from the Thurstone data using \pfun{plot}.  Factors were transformed to an oblique solution using  the oblimin function from the GPArotation package.}
\label{fig:thurstone}
\end{center}
\end{figure}


\begin{figure}[htbp]
\begin{center}
<<print=FALSE,echo=TRUE, fig=TRUE,eps=FALSE>>=
fa.diagram(f3t)
@
\caption{A graphic representation of the 3 oblique factors from the Thurstone data using \pfun{fa.diagram}.  Factors were transformed to an oblique solution using oblimin.}
\label{fig:thurstone.diagram}
\end{center}
\end{figure}


A comparison of these three approaches suggests that the minres solution is more similar to a maximum likelihood solution and fits slightly better than the pa or wls solutions.  Comparisons with SPSS suggest that the pa solution matches the SPSS OLS solution, but that the minres solution is slightly better.  At least in one test data set, the weighted least squares solutions, although fitting equally well, had slightly different structure loadings.

\subsubsection{Principal Components analysis}
An alternative to factor analysis, which is unfortunately frequently confused with factor analysis, is principal components analysis.  Although the goals of PCA and FA are similar, PCA is a descriptive model of the data, while FA is a structural model. Psychologists typically use PCA in a manner similar to factor analysis and thus the \pfun{principal} function produces output that is perhaps more understandable than that produced by \fun{princomp} in the \Rpkg{stats} package. Table~\ref{tab:pca} shows a PCA of the Thurstone 9 variable problem rotated using the \pfun{Promax} function. Note how the loadings from the factor model are similar but smaller than the principal component loadings. This is because the PCA model attempts to account for the entire variance of the correlation matrix, while FA accounts for just the \iemph{common variance}.  This distinction becomes most important for small correlation matrices. Also note how the goodness of fit statistics, based upon the residual off diagonal elements, is much worse than the \pfun{fa} solution.

\begin{scriptsize}
\begin{table}[htdp]
\caption{The Thurstone problem can also be analyzed using Principal Components Analysis.  Compare this to Table~\ref{tab:Thurstone}.  The loadings are higher for the PCA because the model accounts for the unique as well as the common variance.The fit of the off diagonal elements, however, is much worse than the \pfun{fa} results.}
\begin{center}
<<print=FALSE,echo=TRUE>>=
data(bifactor)
p3p <-principal(Thurstone,3,n.obs = 213,rotate="Promax")
p3p
@
\end{center}
\label{tab:pca}
\end{table}
\end{scriptsize}



\subsubsection{Hierarchical and bi-factor solutions}
For a long time structural analysis of  the ability domain have considered the problem of factors that are themselves correlated.  These correlations may themselves be factored to produce a higher order, general factor. An alternative \citep{holzinger:37,jensen:weng} is to consider the general factor affecting each item, and then to have group factors account for  the residual variance. Exploratory factor solutions to produce a hierarchical or a bifactor solution are found using the \pfun{omega} function.  This technique has more recently been applied to the personality domain to consider such things as the structure of neuroticism (treated as a general factor, with lower order factors of anxiety, depression, and aggression).

Consider the 9 Thurstone variables analyzed in the prior factor analyses. The correlations between the factors (as shown in Figure~\ref{fig:thurstone.diagram} can themselves be factored.  This results in a higher order factor model   (Figure~\ref{fig:omega}).  An an alternative solution is to take this higher order model and then solve for the general factor loadings as well as the loadings on the residualized lower order factors  using the \iemph{Schmid-Leiman} procedure. (Figure ~\ref{fig:omega.2}).  Yet another solution is to use structural equation modeling to directly solve for the general and group factors. 

\begin{figure}[htbp]
\begin{center}
<<print=FALSE,echo=TRUE, fig=TRUE,eps=FALSE>>=
om.h <- omega(Thurstone,n.obs=213,sl=FALSE)
op <- par(mfrow=c(1,1))
@
\caption{A higher order factor solution to the Thurstone 9 variable problem}
\label{fig:omega}
\end{center}
\end{figure}

\begin{figure}[htbp]
\begin{center}
<<print=FALSE,echo=TRUE, fig=TRUE,eps=FALSE>>=
om <- omega(Thurstone,n.obs=213)
@
\caption{A bifactor factor solution to the Thurstone 9 variable problem}
\label{fig:omega.2}
\end{center}
\end{figure}

\subsubsection{Item Cluster Analysis: iclust}
 An alternative to factor or components analysis is \iemph{cluster analysis}.  The goal of cluster analysis is the same as factor or components analysis (reduce the complexity of the data and attempt to identify homogeneous subgroupings).  Mainly used for clustering people or objects (e.g., projectile points if an anthropologist, DNA if a biologist, galaxies if an astronomer), clustering may be used for clustering items or tests as well.  Introduced to psychologists by \cite{tryon:39} in the 1930's, the cluster analytic literature exploded in the 1970s and 1980s \citep{blashfield:80,blashfield:88,everitt:74,hartigan:75}.  Much of the research is in taxonmetric applications in biology \cite{sneath:73,sokal:63} and marketing \citep{cooksey:06} where clustering remains very popular.  It is also used for taxonomic work in forming clusters of people in family  \citep{henry:05}   and clinical psychology \citep{martinent:07,mun:08}. Interestingly enough it has has had limited applications to psychometrics.  This is unfortunate, for as has been pointed out by e.g. \citep{tryon:35,loevinger:53}, the theory of factors, while mathematically compelling, offers little that the geneticist or behaviorist or perhaps even non-specialist finds compelling. \cite{cooksey:06} reviews why the \pfun{iclust} algorithm is particularly appropriate for scale construction in marketing. 
 

\emph{Hierarchical cluster analysis} \index{hierarchical cluster analysis} forms clusters that are nested within clusters.  The resulting \iemph{tree diagram} (also known somewhat pretentiously as a \iemph{rooted dendritic structure}) shows the nesting structure.  Although there are many hierarchical clustering algorithms in \R{} (e.g., \fun{agnes},  \fun{hclust}, and \pfun{iclust}), the one most applicable to the problems of scale construction is \pfun{iclust}  \citep{revelle:iclust}.
\begin{enumerate}
\item Find the proximity (e.g. correlation) matrix,
\item Identify the most similar pair of items
\item Combine this most similar pair of items to form a new variable (cluster),
\item Find the similarity of this cluster to all other items and clusters,
\item Repeat  steps 2 and 3 until some criterion is reached (e.g., typicallly, if only one cluster remains or in \pfun{iclust} if there is a failure to increase reliability coefficients $\alpha$ or $\beta$). 
\item Purify the solution by reassigning items to the most similar cluster center.
\end{enumerate}


iclust  forms clusters of items using a hierarchical clustering algorithm until one of two measures of internal consistency fails to increase \citep{revelle:iclust}. The number of clusters may be specified a priori, or found empirically. The resulting statistics include the average split half reliability, $\alpha$ \citep{cronbach:51}, as well as the worst split half reliability, $\beta$ \citep{revelle:iclust}, which is an estimate of the general factor saturation of the resulting scale.
\begin{figure}[htbp]
\begin{center}
<<print=FALSE,echo=TRUE, fig=TRUE,eps=FALSE>>=
data(bfi)
ic <- iclust(bfi[1:25])
@
\caption{Using the \pfun{iclust} function to find the cluster structure of 25 personality items (the three demographic variables were excluded from this analysis.}
\label{fig:iclust}
\end{center}
\end{figure}

\begin{table}[htdp]
\caption{The summary statistics from an iclust analysis shows three large clusters and smaller cluster.}
\begin{center}
<<print=FALSE,echo=TRUE>>=
summary(ic)  #show the results
@
\end{center}
\label{tab:iclust}
\end{table}%

The previous analysis was done using the Pearson correlation. A somewhat cleaner structure is obtained when using the \pfun{polychoric} function to find polychoric correlations.   

\begin{Schunk}
\begin{Sinput}
data(bfi)
r.poly <- polychoric(bfi[1:25])
ic.poly <- iclust(r.poly)$rho
iclust.diagram(ic.poly) 
\end{Sinput}
\end{Schunk}


\subsection{Comparing factor/component/cluster solutions}
Cluster analysis, factor analysis, and principal components analysis all produce structure matrices (matrices of correlations between the dimensions and the variables) that can in turn be compared in terms of the \iemph{congruence coefficient}  which is just  cosine of the angle between the dimensions. This is done using the \pfun{factor.congruence} function.

Consider the case of a four factor solution and four cluster solution to the Big Five problem.  

<<print=FALSE,echo=TRUE>>=
f4 <- fa(bfi[1:25],4,fm="pa")
factor.congruence(f4,ic)
@

Now consider the solutions to the Thurstone problem, considering the factor, component, and bifactor solution. Note the use of the list of solutions to compare.
<<print=FALSE,echo=TRUE>>=
factor.congruence(list(f3t,f3o,om,p3p))
@

\subsection{Determining the number of dimensions to extract.}
How many dimensions to use to represent a correlation matrix is an unsolved problem in psychometrics.  There are many solutions to this problem, none of which is uniformly the best.  Henry Kaiser once said that ``a solution to the number-of factors problem in factor analysis is easy, that he used to make up one every morning before breakfast. But the problem, of course is to find \emph{the} solution, or at least a solution that others will regard quite highly not as the best" \cite{horn:79}.

Techniques most commonly used include
	
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) \pfun{fa.parallel} \citep{horn:65}.

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 \citep{cattell:scree}.

5) Extracting factors as long as they are interpretable.
	
6) Using the Very Structure Criterion (\pfun{vss} \citep{revelle:vss}.

7) Using Wayne Velicer's Minimum Average Partial (\pfun{MAP}) criterion \citep{velicer:76}. 

8) Extracting principal components until the eigen value < 1. 

	

 Each of the procedures has its advantages and disadvantages.  Using either the chi square test or the change in square test is, of course, sensitive to the number of subjects and leads to the nonsensical condition that if one wants to find many factors, one simply runs more subjects. Parallel analysis is partially sensitive to sample size in that for large samples the eigen values of random factors will be very small.   The scree test is quite appealing but can lead to differences of interpretation as to when the scree "breaks".  Extracting interpretable factors means that the number of factors reflects the investigators creativity more than the data.  vss, while very simple to understand, will not work very well if the data are very factorially complex. (Simulations suggests it will work fine if the complexities of some of the items are no more than 2). The eigen value of 1 rule, although the default for many programs, seems to be a rough way of dividing the number of variables by 3 and is probably the worst of all criteria. 
 
An additional problem in determining the number of factors is what is considered a factor.  Many treatments of factor analysis assume that the residual correlation matrix after the factors of interest are extracted is composed of just random error.  An alternative concept is that the matrix is formed from major factors of interest but that there are also numerous minor factors of no substantive interest but that account for some of the shared covariance between variables.   The presence of such minor factors can lead one to extract too many factors and to reject solutions on statistical grounds of misfit that are actually very good fits to the data.  This problem is partially addressed later in the discussion of  simulating complex structures using \pfun{sim.structure} and of small extraneous factors using the \pfun{sim.minor} function.
 
 
\subsubsection{Very Simple Structure}
The \pfun{vss} function compares the fit of a number of factor analyses with the loading matrix ``simplified" by deleting all except the c greatest loadings per item, where c is a measure of factor complexity cite{revelle:vss}.  Included in \pfun{vss} is the MAP criterion (Minimum Absolute Partial correlation) of \cite{velicer:76}.   

Using the Very Simple Structure criterion for the bfi data suggests that 4 factors are optimal (Figure~\ref{fig:vss}). However, the MAP criterion suggests that 5 is optimal.  


\begin{figure}[htbp]
\begin{center}
<<print=FALSE,echo=TRUE, fig=TRUE,eps=FALSE>>=
vss <- vss(bfi[1:25],title="Very Simple Structure of a Big 5 inventory")
@
\caption{The Very Simple Structure criterion for the number of factors compares solutions for various levels of item complexity and various numbers of factors.}
\label{fig:vss}
\end{center}
\end{figure}

<<print=FALSE,echo=TRUE>>=
vss
@

\subsubsection{Parallel Analysis}
An alternative way to determine the number of factors is to compare the solution to random data with the same properties as the real data set.  If the input is a data matrix, the comparison includes random samples from the real data, as well as normally distributed random data with the same number of subjects and variables. For the BFI data, parallel analysis suggests that 6 factors might be most appropriate (Figure~\ref{fig:parallel}). It is interesting to compare \pfun{fa.parallel} with the \fun{paran} from the \Rpkg{paran} package.  This latter uses smcs to estimate communalities.  Simulations of known structures with a particular number of major factors but with  the presence of trivial, minor (but not zero) factors, show that using smcs  will tend to lead to too many factors.  
\begin{figure}[htbp]
\begin{center}
<<print=FALSE,echo=TRUE, fig=TRUE,eps=FALSE>>=
fa.parallel(bfi[1:25],main="Parallel Analysis of a Big 5 inventory")
@
\caption{Parallel analysis compares factor and principal components solutions to the real data as well as resampled data. Although vss suggests 4 factors, MAP 5, parallel analysis suggests 6. One more demonstration of Kaiser's dictum.}
\label{fig:parallel}
\end{center}
\end{figure}


\subsection{Reliability analysis}


Surprisingly, 105 years after Spearman (1904) introduced the concept of reliability to psychologists, there are still multiple approaches for measuring it. Although very popular, Cronbach's $\alpha$  (1951) underestimates the reliability of a test and over estimates the first factor saturation \citep{rz:09}.

$\alpha$ (Cronbach, 1951) is the same as Guttman's $\lambda3$ (Guttman, 1945) and may be found by
$$
\lambda_3 =  \frac{n}{n-1}\Bigl(1 - \frac{tr(\vec{V})_x}{V_x}\Bigr) = \frac{n}{n-1} \frac{V_x - tr(\vec{V}_x)}{V_x} = \alpha
$$

Perhaps because it is so easy to calculate and is available in most commercial programs, alpha is without doubt the most frequently reported measure of internal consistency reliability. Alpha is the mean of all possible spit half reliabilities (corrected for test length).  For a unifactorial test, it is a reasonable estimate of the first factor saturation, although if the test has any microstructure (i.e., if it is ``lumpy") coefficients $\beta$ (Revelle, 1979; see \pfun{iclust}) and $\omega_h$ (see \pfun{omega})  are more appropriate estimates of the general factor saturation. $\omega_t$is a better estimate of the reliability of the total test.  

Guttman's $\lambda _6$ (G6) considers the amount of variance in each item that can be accounted for the linear regression of all of the other items (the squared multiple correlation or smc), or more precisely, the variance of the errors, $e_j^2$,  and is
$$
\lambda_6 = 1 - \frac{\sum e_j^2}{V_x} = 1 - \frac{\sum(1-r_{smc}^2)}{V_x}
.$$

The squared multiple correlation is a lower bound for the item communality and as the number of items increases, becomes a better estimate.

G6 is also sensitive to lumpiness in the test and should not be taken as a measure of unifactorial structure.  For lumpy tests, it will be greater than alpha.  For tests with equal item loadings, alpha > G6, but if the loadings are unequal or if there is a general factor, G6 > alpha. G6 estimates item reliability by the squared multiple correlation of the other items in a scale.  A modification of G6, G6*, takes as an estimate of an item reliability the smc with all the items in an inventory, including those not keyed for a particular scale.  This will lead to a better estimate of the reliable variance of a particular item.

Alpha, G6 and G6* are positive functions of the number of items in a test as well as the average intercorrelation of the items in the test.  When calculated from the item variances and total test variance, as is done here, raw alpha is sensitive to differences in the item variances. Standardized alpha is based upon the correlations rather than the covariances.  

More complete reliability analyses of a single scale can be done using the \pfun{omega} function which finds $\omega_h$ and $\omega_t$ based upon a hierarchical factor analysis.  

Alternative functions \pfun{score.items} and \pfun{cluster.cor} will also score multiple scales and report more useful statistics. ``Standardized" alpha is calculated from the inter-item correlations and will differ from raw alpha. 

Functions for examining the reliability of a single scale or a set of scales include:

\begin{description}
\item [alpha]   Internal consistency measures of reliability range from $\omega_h$ to $\alpha$ to $\omega_t$.  The \pfun{alpha} function reports two estimates: Cronbach's coefficient $\alpha$ and Guttman's $\lambda_6$.  Also reported are item - whole correlations, $\alpha$ if an item is omitted, and item means and standard deviations.
\item [guttman] Eight alternative estimates of test reliability include the six discussed by Guttman (1945), four discussed by ten Berge and Zergers (1978) ($\mu_0 \dots \mu_3$) as well as $\beta$ (the worst split half, Revelle, 1979),  the glb (greatest lowest bound) discussed by Bentler and Woodward (1980), and $\omega_h$ and$\omega_t$ (McDonald, 1999; Zinbarg et al., 2005). 
\item [omega] Calculate McDonald's  omega estimates of general and total factor saturation. (\cite{rz:09} compare these coefficients with real and artificial data sets.)
\item [cluster.cor] Given a n x c cluster definition matrix of -1s, 0s, and 1s (the keys) , and a n x n correlation matrix, find the correlations of the composite clusters.
\item [score.items] Given a matrix or data.frame of k keys for m items (-1, 0, 1), and a matrix or data.frame of items scores for m items and n people, find the sum scores or average scores for each person and each scale. If the input is a square matrix, then it is assumed that correlations or covariances were used, and the raw scores are not available. In addition, report Cronbach's alpha, coefficient G6*, the average r, the scale intercorrelations, and the item by scale correlations (both raw and corrected for item overlap and scale reliability). Replace missing values with the item median or mean if desired. Will adjust scores for reverse scored items.
\item [score.multiple.choice] Ability tests are typically multiple choice with one right answer. score.multiple.choice takes a scoring key and a data matrix (or data.frame) and finds total or average number right for each participant. Basic test statistics (alpha, average r, item means, item-whole correlations) are also reported.
\end{description}

\subsubsection{Reliability of a single scale}
A conventional (but non-optimal) estimate of the internal consistency reliability of a test is coefficient $\alpha$ \citep{cronbach:51}. Alternative estimates are Guttman's $\lambda_6$, Revelle's $\beta$,  McDonald's $\omega_h$ and $\omega_t$. Consider a simulated data set, representing 9 items with a hierarchical structure and the following correlation matrix.  Then using the \pfun{alpha} function, the $\alpha$ and $\lambda_6$ estimates of reliability may be found for all 9 items, as well as the if one item is dropped at a time.

<<print=FALSE,echo=TRUE>>=
set.seed(42)
r9 <- sim.hierarchical(n=500,raw=TRUE)$observed
round(cor(r9),2)
alpha(r9)
@
Some scales have items that need to be reversed before being scored. Rather than reversing the items in the raw data, it is more convenient to just specify which items need to be reversed scored.  This may be done in \pfun{alpha} by specifying a \iemph{keys} vector of 1s and -1s.  (This concept of keys vector is more useful when scoring multiple scale inventories, see below.) As an example, consider scoring the 7 attitude items in the attitude data set.  Assume a conceptual mistake in that item 2 is to be scored (incorrectly) negatively.
<<print=FALSE,echo=TRUE>>=
keys <- c(1,-1,1,1,1,1,1)
alpha(attitude,keys)
@
Note how the reliability of the 7 item scales with an incorrectly reversed item is very poor, but if the item 2 is dropped then the reliability is improved substantially.  This suggests that item 2 was incorrectly scored.  Doing the analysis again with item 2 positively scored produces much more favorable results.

<<print=FALSE,echo=TRUE>>=
keys <- c(1,1,1,1,1,1,1)
alpha(attitude,keys)
@

It is useful when considering items for a potential scale to examine the item distribution.  This is done in \pfun{score.items} as well as in \pfun{alpha}.

\begin{scriptsize}
<<print=FALSE,echo=TRUE>>=
items <- sim.congeneric(N=500,short=FALSE,low=-2,high=2,categorical=TRUE) #500 responses to 4 discrete items
alpha(items$observed)  #item response analysis of congeneric measures
@
\end{scriptsize}
\subsubsection{Using \pfun{omega} to find the reliability of a single scale}
Two alternative estimates of reliability that take into account the hierarchical structure of the inventory are McDonald's $\omega_h$ and $\omega_t$.  These may be found using the \pfun{omega} function for an exploratory analysis (See Figure~\ref{fig:omega.9}) or \pfun{omegaSem} for a confirmatory analysis using the \Rpkg{sem} based upon the exploratory solution from \pfun{omega}.


McDonald has proposed coefficient omega (hierarchical) ($\omega_h$) as an estimate of the general factor saturation of a test.  Zinbarg, Revelle, Yovel and Li (2005) 
\url{http://personality-project.org/revelle/publications/zinbarg.revelle.pmet.05.pdf} compare McDonald's $\omega_h$ to Cronbach's  $\alpha$ and Revelle's $\beta$. They conclude that $\omega_h$ is the best estimate. (See also Zinbarg et al., 2006 and Revelle and Zinbarg (2009) \url{http://personality-project.org/revelle/publications/revelle.zinbarg.08.pdf} ).   

One way to find $\omega_h$ is to do a factor analysis of the original data set, rotate the factors obliquely, factor that correlation matrix, do a   Schmid-Leiman (\pfun{schmid}) transformation to find general factor loadings, and then find $\omega_h$  

$\omega_h$  differs slightly as a function of how the factors are estimated.  Four options are available, the default will do a minimum residual factor analysis, fm=``pa"  does a principal axes factor analysis (\pfun{factor.pa}), fm=``mle" uses the factanal function, and fm=``pc" does a principal components analysis (\pfun{principal}).  

For ability items, it is typically the case that all items will have positive loadings on the general factor.  However, for non-cognitive items it is frequently the case that some items are to be scored positively, and some negatively.  Although probably better to specify which directions the items are to be scored by specifying a key vector, if flip =TRUE (the default), items will be reversed so that they have positive loadings on the general factor.  The keys are reported so that scores can be found using the \pfun{score.items} function.  Arbitrarily reversing items this way can overestimate the general factor. (See the example with a simulated circumplex).

$\beta$, an alternative to $\omega$, is defined as the worst split half reliability.  It can be estimated by using \pfun{iclust} (Item Cluster analysis: a hierarchical clustering algorithm). For a very complimentary review of why the iclust algorithm is useful in scale construction, see Cooksey and Soutar, 2005. 

The \pfun{omega} function uses exploratory factor analysis to estimate the $\omega_h$ coefficient.  It is important to remember that  ``A recommendation that should be heeded, regardless of the method chosen to estimate $\omega_h$, is to always examine the pattern of the estimated general factor loadings prior to estimating $\omega_h$. Such an examination constitutes an informal test of the assumption that there is a latent variable common to all of the scale's indicators that can be conducted even in the context of EFA. If the loadings were salient for only a relatively small subset of the indicators, this would suggest that there is no true general factor underlying the covariance matrix. Just such an informal assumption test would have afforded a great deal of protection against the possibility of misinterpreting the misleading $\omega_h$ estimates occasionally produced in the simulations reported here." (Zinbarg et al., 2006, p 137).


Although $\omega_h$ is uniquely defined only for cases where 3 or more subfactors are extracted, it is sometimes desired to have a two factor solution.  By default this is done by forcing the \pfun{schmid} extraction to treat the two subfactors as having equal loadings.  

There are three possible options for this condition: setting the general factor loadings between the two lower order factors to be ``equal" which will be the $\sqrt{r_{ab}}$ where $r_{ab}$ is the oblique correlation between the factors) or to ``first" or ``second" in which case the general factor is equated with either the first or second group factor. A  message is issued suggesting that the model is not really well defined. This solution discussed in Zinbarg et al., 2007.  To do this in omega, add the option=``first" or option=``second" to the call.

Although obviously not meaningful for a 1 factor solution, it is of course possible to find the sum of the loadings on the first (and only) factor, square them, and compare them to the overall matrix variance.  This is done, with appropriate complaints.


In addition to $\omega_h$, another of McDonald's coefficients is $\omega_t$.  This is an estimate of the total reliability of a test. 

McDonald's $\omega_t$, which is similar to Guttman's $\lambda_6$, (see \pfun{guttman}) uses the estimates of uniqueness $u^2$ from factor analysis to find $e_j^2$. This is based on a decomposition of the variance of a test score, $V_x$ into four parts: that due to a general factor, $\vec{g}$, that due to a set of group factors, $\vec{f}$,  (factors common to some but not all of the items), specific factors, $\vec{s}$ unique to each item, and $\vec{e}$, random error.  (Because specific variance can not be distinguished from random error unless the test is given at least twice,  some combine these both into error). 

Letting $\vec{x} =  \vec{cg} + \vec{Af} + \vec {Ds} + \vec{e} $
then the communality of item$_j$, based upon general as well as group factors,
$h_j^2 = c_j^2 + \sum{f_{ij}^2}$
and the unique variance for the item
$u_j^2 = \sigma_j^2 (1-h_j^2)$
may be used to estimate the test reliability.
That is, if $h_j^2$ is the communality of item$_j$, based upon general as well as group factors,  then for standardized items, $e_j^2 = 1 - h_j^2$ and
$$
\omega_t = \frac{\vec{1}\vec{cc'}\vec{1} + \vec{1}\vec{AA'}\vec{1}'}{V_x} = 1 - \frac{\sum(1-h_j^2)}{V_x} = 1 - \frac{\sum u^2}{V_x}
$$
Because $h_j^2 \geq r_{smc}^2$, $\omega_t \geq \lambda_6$.

It is important to distinguish here between the two $\omega$ coefficients of McDonald, 1978 and Equation 6.20a of McDonald, 1999, $\omega_t$ and $\omega_h$.  While the former is based upon the sum of squared loadings on all the factors, the latter is based upon the sum of the squared loadings on the  general factor. 
$$\omega_h = \frac{ \vec{1}\vec{cc'}\vec{1}}{V_x}$$

Another estimate reported is the omega for an infinite length test with a structure similar to the observed test.  This is found by 
$$\omega_{\inf} = \frac{ \vec{1}\vec{cc'}\vec{1}}{\vec{1}\vec{cc'}\vec{1} + \vec{1}\vec{AA'}\vec{1}'}$$


\begin{figure}[htbp]
\begin{center}
<<print=FALSE,echo=TRUE, fig=TRUE,eps=FALSE>>=
om.9 <- omega(r9,title="9 simulated variables")
@
\caption{A bifactor solution for 9 simulated variables with a hierarchical structure. }
\label{fig:omega.9}
\end{center}
\end{figure}


In the case of these simulated 9 variables, the amount of variance attributable to a general factor ($\omega_h$) is quite large, and the reliability of the set of 9 items is somewhat greater than that estimated by $\alpha$ or $\lambda_6$.  

<<print=FALSE,echo=TRUE>>=
om.9
@
\subsubsection{Estimating $\omega_h$ using Confirmatory Factor Analysis}
The \pfun{omegaSem} function will do an exploratory analysis and then take the highest loading items on each factor and do a confirmatory factor analysis using the \Rpkg{sem} package.  These results can produce slightly different estimates of $\omega_h$, primarily because cross loadings are modeled as part of the general factor.

<<print=FALSE,echo=TRUE>>=
omegaSem(r9,n.obs=500)
@


\subsubsection{Other estimates of reliability}
Other estimates of reliability are found by the \pfun{guttman} function. These are described in more detail in \cite{rz:09}. They include the 6 estimates from Guttman, four from TenBerge, and an estimate of the greatest lower bound. 
<<print=FALSE,echo=TRUE>>=
guttman(r9)
@

\subsubsection{Reliability of multiple scales within an inventory}


A typical research question in personality involves an inventory of multiple items purporting to measure multiple constructs.  For example, the data set \pfun{bfi} includes 25 items thought to measure five dimensions of personality (Extraversion, Emotional Stability, Conscientiousness, Agreeableness, and Openness).  The data may either be the raw data or a correlation matrix (\pfun{score.items}) or just a correlation matrix of the items ( \pfun{cluster.cor} and \pfun{cluster.loadings}). When finding reliabilities for multiple scales, item reliabilities can be estimated using the squared multiple correlation of an item with all other items, not just those that are keyed for a particular scale.  This leads to an estimate of G6*.  

\paragraph{Scoring from raw data}
To score these five scales from the 25 items, use the \pfun{score.items} function with the helper function \pfun{make.keys}.  Logically, scales are merely the weighted composites of a set of items.  The weights used are -1, 0, and 1.  0 implies do not use that item in the scale, 1 implies a positive weight (add the item to the total score), -1 a negative weight (subtract the item from the total score, i.e., reverse score the item).  Reverse scoring an item is equivalent to subtracting the item from the maximum  + minimum possible value for that item.  The minima and maxima can be estimated from all the items, or can be specified by the user.

There are two different ways that scale scores tend to be reported.  Social psychologists and educational psychologists tend to report the scale score as the \emph{average item score} while many personality psychologists tend to report the \emph{total item score}.  The default option for \pfun{score.items} is to report item averages (which thus allows interpretation in the same metric as the items) but totals can be found as well. 

The printed output includes coefficients $\alpha$ and G6*, the average correlation of the items within the scale (corrected for item ovelap and scale relliability), as well as the correlations between the scales (below the diagonal, the correlations above the diagonal are corrected for attenuation.  As is the case for most of the \Rpkg{psych} functions, additional information is returned as part of the object.

First, create keys matrix using the \pfun{make.keys} function.   (The keys matrix could also be prepared externally using a spreadsheet and then copying it into \R{}). Although not normally necessary, show the keys to understand what is happening.

Note that the number of items to specify in the \pfun{make.keys} function is the total number of items in the inventory.  That is, if scoring just 5 items from a 25 item inventory, \pfun{make.keys} should be told that there are 25 items. \pfun{make.keys} just changes a list of items on each scale to make up a scoring matrix.  Because the \pfun{bfi} data set has 25 items as well as 3 demographic items, the number of variables is specified as 28. 

\begin{scriptsize}
<<print=FALSE,echo=TRUE>>=
 keys <- make.keys(nvars=28,list(Agree=c(-1,2:5),Conscientious=c(6:8,-9,-10),
 Extraversion=c(-11,-12,13:15),Neuroticism=c(16:20),
 Openness = c(21,-22,23,24,-25)),
 item.labels=colnames(bfi))
 keys
@
\end{scriptsize}

The use of multiple key matrices for different inventories is facilitated by using the \pfun{super.matrix} function to combine matrices.  This allows convenient scoring of large data sets combining multiple inventories with keys based upon each individual inventory.  Pretend for the moment that the big 5 items were made up of two inventories, one consisting of the first 10 items, the second the last 18 items. (15 personality items + 3 demographic items.) Then the following code would work:

\begin{scriptsize}
<<print=FALSE,echo=TRUE>>=
 keys.1<- make.keys(10,list(Agree=c(-1,2:5),Conscientious=c(6:8,-9,-10)))
keys.2 <- make.keys(15,list(Extraversion=c(-1,-2,3:5),Neuroticism=c(6:10),
 Openness = c(11,-12,13,14,-15)))
 keys.25 <- super.matrix(keys.1,keys.2)
@
\end{scriptsize}
The resulting keys matrix is identical to that found above except that it does not include the extra 3 demographic items.  This is useful when scoring the raw items because the response frequencies for each category are reported, and for the demographic data,  

This use of making multiple key matrices and then combining them into one super matrix of keys is particularly useful when combining demographic information with items to be scores.  A set of demographic keys can be made and then these can be combined with the keys for the particular scales.

Now use these keys in combination with the raw data to score the items, calculate basic reliability and intercorrelations, and find the item-by scale correlations for each item and each scale.  By default, missing data are replaced by the median for that variable. 
<<print=FALSE,echo=TRUE>>=
 scores <- score.items(keys,bfi)
 scores
@
To see the additional information (the raw correlations, the individual scores, etc.), they may be specified by name.  Then, to visualize the correlations between the raw scores, use the \pfun{pairs.panels} function on the scores values of scores.

\begin{figure}[htbp]
\begin{center}
<<print=FALSE,echo=TRUE, fig=TRUE,eps=FALSE>>=
pairs.panels(scores$scores)
@
\caption{A graphic analysis of the Big Five scales found by using the score.items function.}
\label{default}
\end{center}
\end{figure}

\paragraph{Forming scales from a correlation matrix}
There are some situations when the raw data are not available, but the correlation matrix between the items is available. In this case, it is not possible to find individual scores, but it is possible to find the reliability and intercorrelations of the scales.  This may be done using the \pfun{cluster.cor} function or the \pfun{score.items} function.  The use of a keys matrix is the same as in the raw data case.

Consider the same \pfun{bfi} data set, but first find the correlations, and then use \pfun{cluster.cor}.

<<print=FALSE,echo=TRUE>>=
r.bfi <- cor(bfi,use="pairwise")
scales <- cluster.cor(keys,r.bfi)
summary(scales)
@
To find the correlations of the items with each of the scales (the ``structure" matrix) or the correlations of the items controlling for the other scales (the ``pattern" matrix), use the \pfun{cluster.loadings} function.  To do both at once (e.g., the correlations of the scales as well as the item by scale correlations, it is also possible to just use \pfun{score.items}.

\subsection{Item analysis}

Basic item analysis starts with describing the data (\pfun{describe}, finding the number of dimensions using factor analysis (\pfun{fa}), perhaps using the Very Simple Structure criterion  (\pfun{vss}), or perhaps parallel analysis \pfun{fa.parallel}.  Item whole correlations may then be found for scales scored on one dimension (\pfun{alpha} or many scales simultaneously (\pfun{score.items}).  Scales can be modified by changing the keys matrix (i.e., dropping particular items, changing the scale on which an item is to be scored). 

\section{Item Response Theory analysis}
The use of Item Response Theory has become is said to be the ``new psychometrics".  The emphasis is upon item properties, particularly those of item difficulty or location and item discrimination.  These two parameters are easily found from classic techniques when using factor analyses of correlation matrices formed by \pfun{polychoric} or \pfun{tetrachoric} correlations.  The \pfun{irt.fa} function does this and then graphically displays item discrimination and item location as well as item and test information (see Figure~\ref{fig:irt}).

If the correlations of all of the items reflect one underlying latent variable, then factor analysis of the matrix of tetrachoric correlations should allow for the identification of the regression slopes ($\alpha$) of the items on the latent variable.  These regressions are, of course just the factor loadings.  Item difficulty, $\delta_j$  and item discrimination, $\alpha_j$ may be found from factor analysis of the tetrachoric correlations where $\lambda_j$ is just the factor loading on the first factor and $\tau_j$ is the normal threshold reported by the \pfun{tetrachoric} function. 
\begin{equation}
\delta_j = \frac{D\tau}{\sqrt{1-\lambda_j^2}}, \;\;\;\;\;\; \;\;\;\;\;\; \;\;\;\;\;\;\; \alpha_j = \frac{\lambda_j}{\sqrt{1-\lambda_j^2}} 
\label{eq:irt:diff}
\end{equation}
where D is a scaling factor used when converting to the parameterization of \iemph{logistic} model and is 1.702 in that case and 1 in the case of the normal ogive model.  Thus, in the case of the normal model, factor loadings ($\lambda_j$) and item medians ($\tau$) are just
\begin{equation*}
\lambda_j = \frac{\alpha_j}{\sqrt{1+\alpha_j^2}}, \;\;\;\;\;\; \;\;\;\;\;\; \;\;\;\;\;\;\;\tau_j = \frac{\delta_j}{\sqrt{1+\alpha_j^2}}.
\end{equation*}



Consider 9 dichotomous items representing one factor but differing in their levels of difficulty
<<print=FALSE,echo=TRUE>>=
set.seed(17)
d9 <- sim.irt(9,1000,-2.5,2.5,mod="normal") #dichotomous items
test <- irt.fa(d9$items)
test 
@

\begin{figure}[htbp]
\begin{center}
<<print=FALSE,echo=TRUE, fig=TRUE,eps=FALSE>>=
op <- par(mfrow=c(3,1))
plot(test,type="ICC")
plot(test,type="IIC")
plot(test,type="test")
op <- par(mfrow=c(1,1))
@
\caption{A graphic analysis of 9 dichotomous (simulated) items. The top panel shows the probability of item endorsement as the value of the latent trait increases.  Items differ in their location (difficulty) and discrimination (slope).  The middle panel shows the information in each item as a function of latent trait level.  An item is most informative when the probability of endorsement is 50\%.  The lower panel shows the total test information.  These items form a test that is most informative (most accurate) at the middle range of the latent trait.}
\label{fig:irt}
\end{center}
\end{figure}

\begin{scriptsize}
Similar analyses can be done for polytomous items such as those of the bfi extraversion scale:
<<print=FALSE,echo=TRUE>>=
data(bfi)
e.irt <- irt.fa(bfi[11:15])
e.irt 
@
\end{scriptsize}
The item information functions show that not all of items are equally good (Figure~\ref{fig:e.irt}):
\begin{figure}[htbp]
\begin{center}
<<print=FALSE,echo=TRUE, fig=TRUE,eps=FALSE>>=
plot(e.irt,type="IIC")
@
\caption{A graphic analysis of 5 extraversion items from the bfi. The curves represent the amount of information in the item as a function of the latent score for an individual.  That is, each item is maximally discriminating at a different part of the latent continuum.}
\label{fig:e.irt}
\end{center}
\end{figure}

More extensive IRT packages include the \Rpkg{ltm} and \Rpkg{eRm} and should be used for serious Item Response Theory analysis.


\section{Multiple Regression from the correlation matrix}
Although the standard multiple regression (using the \fun{lm} function in base R) uses the raw data, it is sometimes useful to do multiple regression from a correlation matrix.  This may be done using the \pfun{mat.regress} function.  

Consider the correlations of the 6 variables in the \pfun{sat.act} data set.  First do the normal multiple regression, and then compare it with the results using \pfun{mat.regress}. Two things to notice.  \pfun{mat.regress} works on the \emph{correlation} or \emph{covariance} matrix, and thus if using the correlation matrix, will report standardized $\beta$ weights.  Secondly, it is possible to do several multiple regressions simultaneously.  If the number of observations is specified, statistical tests of significance are applied.

<<print=FALSE,echo=TRUE>>=
data(sat.act)

C <- cov(sat.act,use="pairwise")
model1 <- lm(ACT~ gender + education + age, data=sat.act)
summary(model1)
@
Compare this with the output from \pfun{mat.regress}.
<<print=FALSE,echo=TRUE>>=
#compare with mat.regress
mat.regress(C,c(1:3),c(4:6), n.obs=700)
@


\section{Simulation functions}
It is particularly helpful, when teaching psychometric concepts, to be able to generate sample data sets that meet certain specifications.   By knowing ``truth" it is possible to see how well various algorithms can capture it. Several of the \pfun{sim} functions create artificial data sets with known structures. 

A number of functions in the psych package will generate simulated data. These functions include \pfun{sim} for a factor simplex, and \pfun{sim.simplex} for a data simplex, \pfun{sim.circ} for a circumplex structure, \pfun{sim.congeneric} for a one factor factor congeneric model, \pfun{sim.dichot} to simulate dichotomous items, \pfun{sim.hierarchical} to create a hierarchical factor model, \pfun{sim.item} is  a more general item simulation, \pfun{sim.minor} to simulate major and minor factors, \pfun{sim.omega} to test various examples of omega, \pfun{sim.parallel} to compare the efficiency of various ways of determining the number of factors, \pfun{sim.rasch} to create simulated rasch data, \pfun{sim.irt}to create general 1 to 4 parameter IRT data by calling \pfun{sim.npl} 1 to 4 parameter logistic IRT or \pfun{sim.npn} 1 to 4 paramater normal IRT, \pfun{sim.structural} a general simulation of structural models, and \pfun{sim.anova} for ANOVA and lm simulations, and \pfun{sim.vss}. Some of these functions are separately documented and are listed here for ease of the help function. See each function for more detailed help.



\begin{description}
\item [\pfun{sim}]  The default version is to generate a four factor simplex structure over three occasions, although more general models are possible.
\item [\pfun{sim.simple}]   Create major and minor factors.  The default is for 12 variables with 3 major factors and 6 minor factors.  
\item [\pfun{sim.structure}]  To combine a measurement and structural model into one data matrix. Useful for understanding structural equation models.
\item [\pfun{sim.hierarchical}] To create data with a hierarchical (bifactor) structure.
\item [\pfun{sim.congeneric}]  To create congeneric items/tests for demonstrating classical test theory. This is just a special case of sim.structure.
\item [\pfun{sim.circ}]  To create data with a circumplex structure.
\item [\pfun{sim.item}]To create items that either have a simple structure or a circumplex structure.
\item [\pfun{sim.dichot}] Create dichotomous item data with a simple or circumplex structure.
\item[\pfun{sim.rasch}] Simulate a 1 parameter logistic (Rasch) model.
\item[\pfun{sim.irt}] Simulate a 2 parameter logistic (2PL) or 2 parameter Normal model.  Will also do 3 and 4 PL and PN models.
\end{description}


Some of these functions are described in more detail in the companion vignette: \href{"psych_for_sem.pdf"}{psych for sem}.

The default values for \pfun{sim.structure} is to generate a 4 factor, 12 variable data set with a simplex structure between the factors.

Two data structures that are particular challenges to exploratory factor analysis are the simplex structure and the presence of minor factors. Simplex structures \pfun{sim.simplex} will typically occur in developmental or learning contexts and have a correlation structure of r between adjacent variables and $r^n$ for variables n apart. Although just one latent variable (r) needs to be estimated, the structure will have nvar-1 factors.

Many simulations of factor structures assume that except for the major factors, all residuals are normally distributed around 0. An alternative, and perhaps more realistic situation, is that the there are a few major (big) factors and many minor (small) factors. The challenge is thus to identify the major factors. \pfun{sim.minor} generates such structures. The structures generated can be thought of as having a a major factor structure with some small correlated residuals.

Although coefficient $\omega_h$ is a very useful indicator of the general factor saturation of a unifactorial test (one with perhaps several sub factors), it has problems with the case of multiple, independent factors. In this situation, one of the factors is labelled as ÒgeneralÓ and the omega estimate is too large. This situation may be explored using the \pfun{sim.omega} function.

The four irt simulations, \pfun{sim.rasch}, \pfun{sim.irt}, \pfun{sim.npl} and \pfun{sim.npn}, simulate dichotomous items following the Item Response model. \pfun{sim.irt} just calls either \pfun{sim.npl} (for logistic models) or \pfun{sim.npn} (for normal models) depending upon the specification of the model.

The logistic model is
\begin{equation}
P(x | \theta_i, \delta_j, \gamma_j, \zeta_j )= \gamma_j + \frac{\zeta_j - \gamma_j}{1+e^{\alpha_j(\delta_j - \theta_i}}.
\end{equation}



where $\gamma$ is the lower asymptote or guessing parameter, $\zeta$ is the upper asymptote (normally 1), $\alpha_j$ is item discrimination and $\delta_j$ is item difficulty. For the 1 Paramater Logistic (Rasch) model, gamma=0, zeta=1, alpha=1 and item difficulty is the only free parameter to specify.

(Graphics of these may be seen in the demonstrations for the logistic function.)

The normal model (\pfun{irt.npn} calculates the probability using \fun{pnorm} instead of the logistic function used in \pfun{irt.npl}, but the meaning of the parameters are otherwise the same. With the a = $\alpha$ parameter = 1.702 in the logiistic model the two models are practically identical.

\section{Graphical Displays}

Many of the functions in the \Rpkg{psych} package include graphic output and examples have been shown in the previous figures. After running \pfun{fa}, \pfun{iclust}, \pfun{omega}, \pfun{irt.fa}, plotting the resulting object is done by the \pfun{plot.psych} function as well as specific diagram functions.  e.g.,

\begin{Schunk}
\begin{Sinput}
data(bifactor)
f3 <- fa(Thurstone,3)  
plot(f3)
fa.diagram(f3)
c <- iclust(Thurstone)
plot(c)  #a pretty boring plot
iclust.diagram(c)  #a better diagram
c3 <- iclust(Thurstone,3)
plot(c3)  #a more interesting plot
data(bfi)
e.irt <- irt.fa(bfi[11:15])
plot(e.irt)
ot <- omega(Thurstone)
plot(ot)
omega.diagram(ot)
\end{Sinput}
\end{Schunk}


The ability to show path diagrams to represent factor analytic and structural models is discussed in somewhat more detail in the accompanying vignette, \href{"psych_for_sem.pdf"}{psych for sem}.   Basic routines to draw path diagrams are included in the \pfun{dia.rect} and accompanying functions.  These are used by the \pfun{fa.diagram}, \pfun{structure.diagram} and \pfun{iclust.diagram} functions.

\begin{figure}[htbp]
\begin{center}
<<print=FALSE,echo=TRUE, fig=TRUE,eps=FALSE>>=
xlim=c(0,10)
ylim=c(0,10)
plot(NA,xlim=xlim,ylim=ylim,main="Demontration of dia functions",axes=FALSE,xlab="",ylab="")
ul <- dia.rect(1,9,labels="upper left",xlim=xlim,ylim=ylim)
ll <- dia.rect(1,3,labels="lower left",xlim=xlim,ylim=ylim)
lr <- dia.ellipse(9,3,"lower right",xlim=xlim,ylim=ylim)
ur <- dia.ellipse(9,9,"upper right",xlim=xlim,ylim=ylim)
ml <- dia.ellipse(3,6,"middle left",xlim=xlim,ylim=ylim)
mr <- dia.ellipse(7,6,"middle right",xlim=xlim,ylim=ylim)
bl <- dia.ellipse(1,1,"bottom left",xlim=xlim,ylim=ylim)
br <- dia.rect(9,1,"bottom right",xlim=xlim,ylim=ylim)
dia.arrow(from=lr,to=ul,labels="right to left")
dia.arrow(from=ul,to=ur,labels="left to right")
dia.curved.arrow(from=lr,to=ll$right,labels ="right to left")
dia.curved.arrow(to=ur,from=ul$right,labels ="left to right")
dia.curve(ll$top,ul$bottom,"double")  #for rectangles, specify where to point 
dia.curved.arrow(mr,ur,"up")  #but for ellipses, just point to it.
dia.curve(ml,mr,"across")
dia.arrow(ur,lr,"top down")
dia.curved.arrow(br$top,lr$bottom,"up")
dia.curved.arrow(bl,br,"left to right")
dia.arrow(bl,ll$bottom)
dia.curved.arrow(ml,ll$right)
dia.curved.arrow(mr,lr$top)
@
\caption{The basic graphic capabilities of the dia functions are shown in this figure.}
\label{fig:dia}
\end{center}
\end{figure}


\section{Data sets}
A number of data sets for demonstrating psychometric techniques are included in the \Rpkg{psych} package. These include six data sets in \pfun{bifactor} showing a hierarchical factor structure (five cognitive examples, \pfun{Thurstone}, \pfun{Thurstone.33}, \pfun{Holzinger}, \pfun{Bechtoldt.1}, \pfun{Bechtoldt.2}, and  one from health psychology \pfun{Reise}). One of these (\pfun{Thurstone}) is used as an example in the \Rpkg{sem} package as well as \cite{mcdonald:tt}. The original data are from \cite{thurstone:41} and reanalyzed by \cite{bechtoldt:61}.  Personality item data representing five personality factors on 25 items (\pfun{bfi}) or 13 personality inventory scores (\pfun{epi.bfi}), and 14 multiple choice iq items (\pfun{iqitems}).  The \pfun{vegetables} example has paired comparison preferences for 9 vegetables. This is an example of Thurstonian scaling used by \cite{guilford:54} and \cite{nunnally:67}. Other data sets include \pfun{cubits}, \pfun{peas}, and \pfun{heights} from Galton.

\begin{description}
\item[bifactor] Holzinger-Swineford (1937) introduced the bifactor model of a general factor and uncorrelated group factors. The Holzinger correlation matrix is a 14 * 14 matrix from their paper. The Thurstone correlation matrix is a 9 * 9 matrix of correlations of ability items. The Reise data set is 16 * 16 correlation matrix of mental health items. The Bechtholdt data sets are both 17 x 17 correlation matrices of ability tests.
\item [bfi]  25 personality self report items taken from the International Personality Item Pool (ipip.ori.org) were included as part of the Synthetic Aperture Personality Assessment (SAPA) web based personality assessment project. The data from 2800 subjects are included here as a demonstration set for scale construction, factor analysis and Item Response Theory analyses.
\item [sat.act] Self reported scores on the SAT Verbal, SAT Quantitative and ACT were collected as part of the Synthetic Aperture Personality Assessment (SAPA) web based personality assessment project. Age, gender, and education are also reported. The data from 700 subjects are included here as a demonstration set for correlation and analysis.
\item [epi.bfi] A small data set of 5 scales from the Eysenck Personality Inventory, 5 from a Big 5 inventory, a Beck Depression Inventory, and State and Trait Anxiety measures. Used for demonstrations of correlations, regressions, graphic displays.
\item [iq] 14 multiple choice ability items were included as part of the Synthetic Aperture Personality Assessment (SAPA) web based personality assessment project. The data from 1000 subjects are included here as a demonstration set for scoring multiple choice inventories and doing basic item statistics.
\item [galton] Two of the earliest examples of the correlation coefficient were Francis Galton's data sets on the relationship between mid parent and child height and the similarity of parent generation peas with child peas. \pfun{galton} is the data set for the Galton height. \pfun{peas} is the data set Francis Galton used to ntroduce the correlation coefficient with an analysis of the similarities of the parent and child generation of 700 sweet peas.
\item [miscellaneous] \pfun{cities} is a matrix of airline distances between 11 US cities and may be used for demonstrating multiple dimensional scaling.  \pfun{vegetables} is a classic data set for demonstrating Thurstonian scaling and is the preference matrix of 9 vegetables from Guilford (1954). Used by Guiford, Nunnally, and Nunnally and Bernstein, this data set allows for examples of basic scaling techniques. 
\end{description}
 
 
\section{Development version and a users guide} 

The most recent development version is available as a source file at the repository maintained at \href{ href="http://personality-project.org/r"}{\url{http://personality-project.org/r}}.  That version will have removed the most recently discovered bugs (but perhaps introduced other, yet to be discovered ones). To download that version, go to the repository %\href{"http://personality-project.org/r/src/contrib/}{
\url{http://personality-project.org/r/src/contrib/} and wander around. For a Mac, this version can be installed directly using the ``other repository" option in the package installer.  For a PC, the zip file for the most recent release has been created using the win-builder facility at CRAN.  

Although the individual help pages for the \Rpkg{psych} package are available as part of \R{} and may be accessed directly (e.g. ?psych) , the full manual for the \pfun{psych} package is also available as a pdf at  \url{http://personality-project.org/r/psych_manual.pdf}
 %psych\_manual.pdf.

News and a history of changes are available in the NEWS and CHANGES files in the source files.

\section{Psychometric Theory}
The \Rpkg{psych} package has been developed to help psychologists do basic research.  Many of the functions were developed to supplement a book (\url{http://personality-project.org/r/book} An introduction to Psychometric Theory with Applications in R (Revelle, in prep).  More information about the use of some of the functions may be found in the book . 


For more extensive discussion of the use of psych in particular and R in general, consult  \url{http://personality-project.org/r/r.guide.html} A short guide to R.


\section{SessionInfo}
This document was prepared using the following settings.
<<print=FALSE,echo=TRUE>>=
sessionInfo()
@

\newpage
%\bibliography{/Volumes/WR/bill/Documents/Active/book/all}
%\bibliography{all} 
\begin{thebibliography}{}

\bibitem[\protect\astroncite{Bechtoldt}{1961}]{bechtoldt:61}
Bechtoldt, H. (1961).
\newblock An empirical study of the factor analysis stability hypothesis.
\newblock {\em Psychometrika}, 26(4):405--432.

\bibitem[\protect\astroncite{Blashfield}{1980}]{blashfield:80}
Blashfield, R.~K. (1980).
\newblock The growth of cluster analysis: {Tryon, Ward, and Johnson}.
\newblock {\em Multivariate Behavioral Research}, 15(4):439 -- 458.

\bibitem[\protect\astroncite{Blashfield and Aldenderfer}{1988}]{blashfield:88}
Blashfield, R.~K. and Aldenderfer, M.~S. (1988).
\newblock The methods and problems of cluster analysis.
\newblock In Nesselroade, J.~R. and Cattell, R.~B., editors, {\em Handbook of
  multivariate experimental psychology (2nd ed.)}, pages 447--473. Plenum
  Press, New York, NY.

\bibitem[\protect\astroncite{Cattell}{1966}]{cattell:scree}
Cattell, R.~B. (1966).
\newblock The scree test for the number of factors.
\newblock {\em Multivariate Behavioral Research}, 1(2):245--276.

\bibitem[\protect\astroncite{Cattell}{1978}]{cattell:fa78}
Cattell, R.~B. (1978).
\newblock {\em The scientific use of factor analysis}.
\newblock Plenum Press, New York.

\bibitem[\protect\astroncite{Cooksey and Soutar}{2006}]{cooksey:06}
Cooksey, R. and Soutar, G. (2006).
\newblock Coefficient beta and hierarchical item clustering - an analytical
  procedure for establishing and displaying the dimensionality and homogeneity
  of summated scales.
\newblock {\em Organizational Research Methods}, 9:78--98.

\bibitem[\protect\astroncite{Cronbach}{1951}]{cronbach:51}
Cronbach, L.~J. (1951).
\newblock Coefficient alpha and the internal structure of tests.
\newblock {\em Psychometrika}, 16:297--334.

\bibitem[\protect\astroncite{Everitt}{1974}]{everitt:74}
Everitt, B. (1974).
\newblock {\em Cluster analysis}.
\newblock John Wiley \& Sons, Cluster analysis. 122 pp. Oxford, England.

\bibitem[\protect\astroncite{Fox}{2009}]{sem}
Fox, J. (2009).
\newblock {\em sem: Structural Equation Models}.
\newblock R package version 0.9-15.

\bibitem[\protect\astroncite{Grice}{2001}]{grice:01}
Grice, J.~W. (2001).
\newblock Computing and evaluating factor scores.
\newblock {\em Psychological Methods}, 6(4):430--450.

\bibitem[\protect\astroncite{Guilford}{1954}]{guilford:54}
Guilford, J.~P. (1954).
\newblock {\em Psychometric Methods}.
\newblock McGraw-Hill, New York, 2nd edition.

\bibitem[\protect\astroncite{Guttman}{1945}]{guttman:45}
Guttman, L. (1945).
\newblock A basis for analyzing test-retest reliability.
\newblock {\em Psychometrika}, 10(4):255--282.

\bibitem[\protect\astroncite{Hartigan}{1975}]{hartigan:75}
Hartigan, J.~A. (1975).
\newblock {\em Clustering Algorithms}.
\newblock John Wiley \& Sons, Inc., New York, NY, USA.

\bibitem[\protect\astroncite{Henry et~al.}{2005}]{henry:05}
Henry, D.~B., Tolan, P.~H., and Gorman-Smith, D. (2005).
\newblock Cluster analysis in family psychology research.
\newblock {\em Journal of Family Psychology}, 19(1):121--132.

\bibitem[\protect\astroncite{Holzinger and Swineford}{1937}]{holzinger:37}
Holzinger, K. and Swineford, F. (1937).
\newblock The bi-factor method.
\newblock {\em Psychometrika}, 2(1):41--54.

\bibitem[\protect\astroncite{Horn}{1965}]{horn:65}
Horn, J. (1965).
\newblock A rationale and test for the number of factors in factor analysis.
\newblock {\em Psychometrika}, 30(2):179--185.

\bibitem[\protect\astroncite{Horn and Engstrom}{1979}]{horn:79}
Horn, J.~L. and Engstrom, R. (1979).
\newblock Cattell's scree test in relation to bartlett's chi-square test and
  other observations on the number of factors problem.
\newblock {\em Multivariate Behavioral Research}, 14(3):283--300.

\bibitem[\protect\astroncite{Jensen and Weng}{1994}]{jensen:weng}
Jensen, A.~R. and Weng, L.-J. (1994).
\newblock What is a good g?
\newblock {\em Intelligence}, 18(3):231--258.

\bibitem[\protect\astroncite{Loevinger et~al.}{1953}]{loevinger:53}
Loevinger, J., Gleser, G., and DuBois, P. (1953).
\newblock Maximizing the discriminating power of a multiple-score test.
\newblock {\em Psychometrika}, 18(4):309--317.

\bibitem[\protect\astroncite{MacCallum et~al.}{2007}]{maccallum:07}
MacCallum, R.~C., Browne, M.~W., and Cai, L. (2007).
\newblock Factor analysis models as approximations.
\newblock In Cudeck, R. and MacCallum, R.~C., editors, {\em Factor analysis at
  100: Historical developments and future directions}, pages 153--175. Lawrence
  Erlbaum Associates Publishers, Mahwah, NJ.

\bibitem[\protect\astroncite{Martinent and Ferrand}{2007}]{martinent:07}
Martinent, G. and Ferrand, C. (2007).
\newblock A cluster analysis of precompetitive anxiety: Relationship with
  perfectionism and trait anxiety.
\newblock {\em Personality and Individual Differences}, 43(7):1676--1686.

\bibitem[\protect\astroncite{McDonald}{1999}]{mcdonald:tt}
McDonald, R.~P. (1999).
\newblock {\em Test theory: {A} unified treatment}.
\newblock L. Erlbaum Associates, Mahwah, N.J.

\bibitem[\protect\astroncite{Mun et~al.}{2008}]{mun:08}
Mun, E.~Y., von Eye, A., Bates, M.~E., and Vaschillo, E.~G. (2008).
\newblock Finding groups using model-based cluster analysis: Heterogeneous
  emotional self-regulatory processes and heavy alcohol use risk.
\newblock {\em Developmental Psychology}, 44(2):481--495.

\bibitem[\protect\astroncite{Nunnally}{1967}]{nunnally:67}
Nunnally, J.~C. (1967).
\newblock {\em Psychometric theory}.
\newblock McGraw-Hill, New York,.

\bibitem[\protect\astroncite{Revelle}{1979}]{revelle:iclust}
Revelle, W. (1979).
\newblock Hierarchical cluster-analysis and the internal structure of tests.
\newblock {\em Multivariate Behavioral Research}, 14(1):57--74.

\bibitem[\protect\astroncite{Revelle}{2010}]{psych}
Revelle, W. (2010).
\newblock {\em psych: Procedures for Personality and Psychological Research}.
\newblock R package version 1.0-86.

\bibitem[\protect\astroncite{Revelle and Rocklin}{1979}]{revelle:vss}
Revelle, W. and Rocklin, T. (1979).
\newblock {Very Simple Structure} - alternative procedure for estimating the
  optimal number of interpretable factors.
\newblock {\em Multivariate Behavioral Research}, 14(4):403--414.

\bibitem[\protect\astroncite{Revelle and Zinbarg}{2009}]{rz:09}
Revelle, W. and Zinbarg, R.~E. (2009).
\newblock Coefficients alpha, beta, omega and the glb: comments on {Sijtsma}.
\newblock {\em Psychometrika}, 74(1):145--154.

\bibitem[\protect\astroncite{Schmid and Leiman}{1957}]{schmid:57}
Schmid, J.~J. and Leiman, J.~M. (1957).
\newblock The development of hierarchical factor solutions.
\newblock {\em Psychometrika}, 22(1):83--90.

\bibitem[\protect\astroncite{Shrout and Fleiss}{1979}]{shrout:79}
Shrout, P.~E. and Fleiss, J.~L. (1979).
\newblock Intraclass correlations: Uses in assessing rater reliability.
\newblock {\em Psychological Bulletin}, 86(2):420--428.

\bibitem[\protect\astroncite{Sneath and Sokal}{1973}]{sneath:73}
Sneath, P. H.~A. and Sokal, R.~R. (1973).
\newblock {\em Numerical taxonomy: the principles and practice of numerical
  classification}.
\newblock A Series of books in biology. W. H. Freeman, San Francisco.

\bibitem[\protect\astroncite{Sokal and Sneath}{1963}]{sokal:63}
Sokal, R.~R. and Sneath, P. H.~A. (1963).
\newblock {\em Principles of numerical taxonomy}.
\newblock A Series of books in biology. W. H. Freeman, San Francisco.

\bibitem[\protect\astroncite{Steiger}{1980}]{steiger:80b}
Steiger, J.~H. (1980).
\newblock Tests for comparing elements of a correlation matrix.
\newblock {\em Psychological Bulletin}, 87(2):245--251.

\bibitem[\protect\astroncite{Thorburn}{1918}]{thornburn:1918}
Thorburn, W.~M. (1918).
\newblock The myth of occam's razor.
\newblock {\em Mind}, 27:345--353.

\bibitem[\protect\astroncite{Thurstone and Thurstone}{1941}]{thurstone:41}
Thurstone, L.~L. and Thurstone, T.~G. (1941).
\newblock {\em Factorial studies of intelligence}.
\newblock The University of Chicago press, Chicago, Ill.

\bibitem[\protect\astroncite{Tryon}{1935}]{tryon:35}
Tryon, R.~C. (1935).
\newblock A theory of psychological components--an alternative to "mathematical
  factors.".
\newblock {\em Psychological Review}, 42(5):425--454.

\bibitem[\protect\astroncite{Tryon}{1939}]{tryon:39}
Tryon, R.~C. (1939).
\newblock {\em Cluster analysis}.
\newblock Edwards Brothers, Ann Arbor, Michigan.

\bibitem[\protect\astroncite{Velicer}{1976}]{velicer:76}
Velicer, W. (1976).
\newblock Determining the number of components from the matrix of partial
  correlations.
\newblock {\em Psychometrika}, 41(3):321--327.

\end{thebibliography}

\printindex
\end{document}  
