\name{Harman23.cor}
\alias{Harman23.cor}
\non_function{}
\title{Harman Example 2.3}
\description{
  A correlation matrix of eight physical measurements on 305 girls between
  ages seven and seventeen.
}
\usage{data(Harman23.cor)}
\source{
  Harman, H. H. (1976)
  \emph{Modern Factor Analysis}, Third Edition Revised,
  University of Chicago Press, Table 2.3.
}
\examples{
data(Harman23.cor)
(Harman23.FA <- factanal(factors = 1, covmat = Harman23.cor))
for(factors in 2:4) print(update(Harman23.FA, factors = factors))
}
\keyword{datasets}
\name{Harman74.cor}
\alias{Harman74.cor}
\non_function{}
\title{Harman Example 7.4}
\description{
  A correlation matrix of 24 psychological tests given to 145 seventh and
  eight-grade children in a Chicago suburb by Holzinger and Swineford.
}
\usage{data(Harman74.cor)}
\source{
  Harman, H. H. (1976)
  \emph{Modern Factor Analysis}, Third Edition Revised,
  University of Chicago Press, Table 7.4.
}
\examples{
data(Harman74.cor)
(Harman74.FA <- factanal(factors = 1, covmat = Harman74.cor))
for(factors in 2:5) print(update(Harman74.FA, factors = factors))
Harman74.FA <- factanal(factors = 5, covmat = Harman74.cor,
                        rotation="promax")
print(Harman74.FA$loadings, sort = TRUE)
}
\keyword{datasets}
\name{ability.cov}
\alias{ability.cov}
\non_function{}
\title{Ability and Intelligence Tests}
\description{
  Six tests were given to 112 individuals. The covariance matrix is
  given in this object.
}
\details{
  The tests are described as
  \describe{
    \item{general:}{a non-verbal measure of general intelligence using
      Cattell's culture-fair test.}
    \item{picture:}{a picture-completion test}
    \item{blocks:}{block design}
    \item{maze:}{mazes}
    \item{reading:}{reading comprehension}
    \item{vocab:}{vocabulary}
  }
  
  Bartholomew gives both covariance and correlation matrices,
  but these are inconsistent.  Neither are in the original paper.
}
\usage{data(ability.cov)}
\source{
  Barthlomew, D. J. (1987) \emph{Latent Variable Analysis and Factor
    Analysis.} Griffin.  

  Barthlomew, D. J.  and Knott, M. (1990) \emph{Latent Variable Analysis
    and Factor Analysis.} Second Edition, Arnold.  
}
\references{
  Smith, G. A. and Stanley G. (1983)
  Clocking \eqn{g}: relating intelligence and measures of timed
  performance. \emph{Intelligence}, \bold{7}, 353--368.
}
\examples{
data(ability.cov)
(ability.FA <- factanal(factors = 1, covmat=ability.cov))
update(ability.FA, factors=2)
update(ability.FA, factors=2, rotation="promax")
}
\keyword{datasets}
\name{as.hclust}
\alias{as.hclust}
\alias{as.hclust.twins}
\title{Convert Objects to Class hclust}
\usage{
as.hclust(x, ...)
as.hclust.twins(x, ...)
}
\arguments{
  \item{x}{Hierarchical clustering object}
  \item{\dots}{further arguments passed to or from other methods.}
}
\description{
  Converts objects from other hierarchical clustering functions to
  class \code{"hclust"}.
}
\details{
  Currently there is only support for converting objects of
  class \code{"twins"} as produced by the functions \code{diana} and
  \code{agnes} from the package \file{cluster}.
}
\value{
  An object of class \code{"hclust"}.
}
\seealso{
  \code{\link{hclust}}, \code{\link[cluster]{diana}},
  \code{\link[cluster]{agnes}}
}
\examples{
\dontrun{
x <- matrix(rnorm(30), ncol=3)
hc <- hclust(dist(x), method="complete")

library(cluster)
ag <- agnes(x, method="complete")

x11()
par(mfrow=c(1,2))
plot(hc)
mtext("hclust", side=1)
plot(as.hclust(ag))
mtext("agnes", side=1)
}
}
\keyword{multivariate}
\keyword{cluster}

\name{biplot}
\title{Biplot of Multivariate Data}
\usage{
biplot(x, \dots)

biplot.default(x, y, var.axes = TRUE, col, cex = rep(par("cex"), 2),
               xlabs = NULL, ylabs = NULL, expand = 1,
               xlim  = NULL, ylim  = NULL, arrow.len = 0.1, \dots)
}
\alias{biplot}
\alias{biplot.default}
\arguments{
 \item{x}{The \code{biplot}, a fitted object. For \code{biplot.default},
   the first set of points (a two-column matrix), usually associated
   with observations.}
 \item{y}{The second set of points (a two-column matrix), usually associated
   with variables.}
 \item{var.axes}{If \code{TRUE} the second set of points have arrows
   representing them as (unscaled) axes.}
 \item{col}{A vector of length 2 giving the colours for the first and
   second set of points respectively (and the corresponding axes). If a
   single colour is specified it will be used for both sets.}
 \item{cex}{The character expansion factor used for labelling the
   points. The labels can be of different sizes for the two sets by
   supplying a vector of length two.}
 \item{xlabs}{A vector of character strings to label the first set of
   points: the default is to use the row dimname of \code{x}, or
   \code{1:n} is the dimname is \code{NULL}.}
 \item{ylabs}{A vector of character strings to label the second set of
   points: the default is to use the row dimname of \code{y}, or
   \code{1:n} is the dimname is \code{NULL}.}
 \item{expand}{An expansion factor to apply when plotting the second set
   of points relative to the first. This can be used to get the two sets
   on to a physically comparable scale.}
 \item{arrow.len}{The length of the arrow heads on the axes plotted in
   \code{var.axes} is true. The arrow head can be suppressed by
   \code{arrow.len = 0}.}
 \item{xlim, ylim, \dots}{graphical parameters.}
}
\description{
  Plot a biplot on the current graphics device.
}
\details{
  A biplot is plot which aims to represent both the observations and
  variables of a matrix of multivariate data on the same plot. There are
  many variations on biplots (see the references) and perhaps the most
  widely used one is implemented by \code{\link{biplot.princomp}}.
  The function \code{biplot.default} merely provides the
  underlying code to plot two sets of variables on the same figure.

  Graphical parameters can also be given to \code{biplot}.
}
\section{Side Effects}{
a plot is produced on the current graphics device.
}
\references{
  K. R. Gabriel (1971).  The biplot graphical display of matrices with
  application to principal component analysis. \emph{Biometrika}
  \bold{58}, 453--467.

  J.C. Gower and D. J. Hand (1996). \emph{Biplots}. Chapman & Hall.
}
\author{B.D. Ripley}
\seealso{\code{\link{biplot.princomp}}, also for examples.}
\keyword{hplot}
\keyword{multivariate}
\name{biplot.princomp}
\alias{biplot.princomp}
\title{
Biplot for Principal Components
}
\description{
  Produces a biplot (in the strict sense) from the output of
  \code{\link{princomp}}.
}
\usage{
\method{biplot}{princomp}(x, choices = 1:2, scale = 1, pc.biplot = FALSE, \dots)
}
\arguments{
  \item{x}{an object of class \code{"princomp"}.}
  \item{choices}{
    length 2 vector specifying the components to plot. Only the default
    is a biplot in the strict sense.
  }
  \item{scale}{
    The variables are scaled by \code{lambda ^ scale} and the
    observations are scaled by \code{lambda ^ (1-scale)} where
    \code{lambda} are the singular values as computed by
    \code{\link{princomp}}. Normally \code{0 <= scale <= 1}, and a warning 
    will be issued if the specified \code{scale} is outside this range.
  }
  \item{pc.biplot}{
    If true, use what Gabriel (1971) refers to as a "principal component
    biplot", with \code{lambda = 1} and observations scaled up by sqrt(n) and
    variables scaled down by sqrt(n).  Then inner products between
    variables approximate covariances and distances between observations
    approximate Mahalanobis distance.
  }
  \item{\dots}{optional arguments to be passed to
    \code{\link{biplot.default}}.}
}
\section{Side Effects}{
    a plot is produced on the current graphics device.
}
\details{
    This is a method for the generic function \code{biplot}.  There is
    considerable confusion over the precise definitions: those of the
    original paper, Gabriel (1971), are followed here.  Gabriel and
    Odoroff (1990) use the same definitions, but their plots actually
    correspond to \code{pc.biplot = TRUE}.
}
\references{
    Gabriel, K. R. (1971).
    The biplot graphical display of matrices with applications to
    principal component analysis.
    \emph{Biometrika}, \bold{58}, 453--467.

    Gabriel, K. R. and Odoroff, C. L. (1990).
    Biplots in biomedical research.
    \emph{Statistics in Medicine}, \bold{9}, 469--485.
}
\seealso{
    \code{\link{biplot}},
    \code{\link{princomp}}.
}
\examples{
data(USArrests)
biplot(princomp(USArrests))
}
\keyword{multivariate}
\keyword{hplot}
\name{cancor}
\title{Canonical Correlations}
\alias{cancor}
\usage{
cancor(x, y, xcenter = TRUE, ycenter = TRUE)
}
\arguments{
  \item{x}{numeric matrix (\eqn{n \times p_1}{n * p1}), containing the
    x coordinates.}
  \item{y}{numeric matrix (\eqn{n \times p_2}{n * p2}), containing the
    y coordinates.}
  \item{xcenter}{logical or numeric vector of length \eqn{p_1}{p1},
    describing any centering to be done on the x values before the
    analysis.  If \code{TRUE} (default), subtract the column means.
    If \code{FALSE}, do not adjust the columns.  Otherwise, a vector
    of values to be subtracted from the columns.} 
  \item{ycenter}{analogous to \code{xcenter}, but for the y values.}
}
\description{
  Compute the canonical correlations between two data matrices.
}
\details{
  The canonical correlation analysis seeks linear combinations of the
  \code{y} variables which are well explained by linear combinations
  of the \code{x} variables. The relationship is symmetric as
  `well explained' is measured by correlations.
}
\value{
  A list containing the following components:
  \item{cor}{correlations.}
  \item{xcoef}{estimated coefficients for the \code{x} variables.}
  \item{ycoef}{estimated coefficients for the \code{y} variables.}
  \item{xcenter}{the values used to adjust the \code{x} variables.}
  \item{ycenter}{the values used to adjust the \code{x} variables.}
}
\references{
  Hotelling H. (1936).
  Relations between two sets of variables.
  \emph{Biometrika}, \bold{28}, 321--327.
  
  Seber, G. A. F. (1984).
  \emph{Multivariate Observations}.
  New York: Wiley, p. 506f.
}
\seealso{
  \code{\link{qr}}, \code{\link{svd}}.
}
\examples{
data(LifeCycleSavings)
pop <- LifeCycleSavings[, 2:3]
oec <- LifeCycleSavings[, -(2:3)]
cancor(pop, oec)

x <- matrix(rnorm(150), 50, 3)
y <- matrix(rnorm(250), 50, 5)
(cxy <- cancor(x, y))
all(abs(cor(x \%*\% cxy$xcoef,
            y \%*\% cxy$ycoef)[,1:3] - diag(cxy $ cor)) < 1e-15)
all(abs(cor(x \%*\% cxy$xcoef) - diag(3)) < 1e-15)
all(abs(cor(y \%*\% cxy$ycoef) - diag(5)) < 1e-15)
}
\keyword{multivariate}
\name{cmdscale}
\title{Classical (Metric) Multidimensional Scaling}
\usage{
cmdscale(d, k = 2, eig = FALSE)
}
\alias{cmdscale}
\arguments{
  \item{d}{a distance structure such as that returned by \code{dist}
    or a full symmetric matrix containing the dissimilarities.}
  \item{k}{the dimension of the space which the data are to be
    represented in; must be in \eqn{\{1,2, .., n-1\}}.}
  \item{eig}{indicates whether eigenvalues should be returned.}
}
\description{
  Classical multidimensional scaling of a data matrix.
}
\details{
  Multidimensional scaling takes a set of dissimilarities
  and returns a set of points such that the distances between the points
  are approximately equal to the dissimilarities.

  The functions \code{isoMDS} and \code{sammon} in package
  \file{MASS} provide alternative ordination techniques.
}
\value{
  If \code{eig = FALSE}, a matrix with \code{k} columns whose rows give the
  coordinates of the points chosen to represent the dissimilarities.

  Otherwise, a list containing the following components.
  \item{points}{a matrix with \code{k} columns whose rows give the
    coordinates of the points chosen to represent the dissimilarities.}
  \item{eig}{the eigenvalues computed during the scaling process.}
}
\references{
  Cox, F.C. and Cox, M.A.A. (1994)
  \emph{Multidimensional Scaling}.
  Chapman and Hall.

  Mardia, K. V., J. T. Kent and J. M. Bibby (1979).  Chapter 14 of
  \emph{Multivariate Analysis}, London: Academic Press.

  Seber, G. A. F. (1984).
  \emph{Multivariate Observations}.
  New York: Wiley.

  Torgerson, W. S. (1958).
  \emph{Theory and Methods of Scaling}.
  New York: Wiley.
}
\note{
  The S version of this function provides for computing an additional
  ``fiddle'' factor suggested by Torgerson.  \R will provide this
  option from version 1.5.0 on.
}
\seealso{
  \code{\link{dist}}. Also
  \code{\link[MASS]{isoMDS}} and \code{\link[MASS]{sammon}}
  in package \file{MASS}.
}
\examples{
data(eurodist)
loc <- cmdscale(eurodist)
x <- loc[,1]
y <- -loc[,2]
plot(x, y, type="n", xlab="", ylab="", main="cmdscale(eurodist)")
text(x, y, names(eurodist), cex=0.8)

\testonly{
## failed in versions <= 1.4.0 :
cmdscale(eurodist, k = 1)
}
}
\keyword{multivariate}
\name{cutree}
\alias{cutree}
\title{Cut a tree into groups of data}
\description{
  Cuts a tree, e.g., as resulting from \code{\link{hclust}}, into several
  groups either by specifying the desired number of groups or the cut
  height.
}
\usage{
cutree(tree, k=NULL, h=NULL)
}
\arguments{
 \item{tree}{a tree as produced by \code{\link{hclust}}}
 \item{k}{an integer scalar or vector with the desired number of groups}
 \item{h}{numeric scalar or vector with heights where the tree should
   be cut.}
 At least one of \code{k} or \code{h} must be specified, \code{k}
 overrides \code{h} if both are given.
}
\value{
  \code{cutree} returns a vector with group memberships if \code{k} or
  \code{h} are scalar, otherwise a matrix with group meberships is returned
  where each column corresponds to the elements of \code{k} or \code{h},
  respectively (which are also used as column names).
}
\seealso{\code{\link{hclust}}}
\examples{
require(mva)
data(USArrests)

hc <- hclust(dist(USArrests))

cutree(hc, k=1:5)#k = 1 is trivial
cutree(hc, h=250)

## Compare the 2 and 3 grouping:
g24 <- cutree(hc, k = c(2,4))
table(g24[,"2"], g24[,"4"])
\testonly{
  ct <- cutree(hc, h = c(0, hc$height[c(1,49)], 1000))
  stopifnot(ct[,"0"]== 1:50,
     unique(ct[,2]) == 1:49,
            ct[,3]  == ct[,4],
            ct[,4]  == 1)
}
}
\keyword{multivariate}
\keyword{cluster}

\name{dendrogram}
\title{General Tree Structures}
\alias{as.dendrogram}
\alias{as.dendrogram.hclust}
\alias{plot.dendrogram}
\alias{plotNode}
\alias{plotNodeLimit}
\alias{cut.dendrogram}
\description{
  Class \code{"dendrogram"} provides general functions for handling
  tree-like structures.  It is intended as a replacement for similar
  functions in hierarchical clustering and classification/regression
  trees, such that all of these can use the same engine for plotting or
  cutting trees. Currently the code is in alpha stage and the API may
  change at any point in time.
}
\usage{
\method{plot}{dendrogram}(x, type=c("rectangle", "triangle"),
                center=FALSE, xlab="", ylab="", ...)
\method{cut}{dendrogram}(x, h, ...)
}
\arguments{
  \item{x}{Object of class \code{"dendrogram"}.}
  \item{type}{Type of plot.}
  \item{center}{If \code{TRUE}, nodes are plotted centered with respect to
    the leaves in the branch. Default is to plot them in the middle of all
    direct child nodes.}
  \item{h}{Height at which the tree is cutted.}
  \item{\dots, xlab, ylab}{graphical parameters, or arguments for
    other methods.}
}
\details{
  Warning: This documentation is preliminary.

  The dendrogram is directly represented as a nested list, where each list
  component corresponds to a branch of the tree. Hence, the first branch
  of tree \code{z} is \code{z[[1]]}, the second branch of the
  corresponding subtree is \code{z[[1]][[2]]} etc.. Each node of the tree
  carries some information needed for efficient plotting or cutting as
  attributes:
  \describe{
    \item{\code{members}}{number of leaves in the branch}
    \item{\code{height}}{Height at which the node is plotted}
    \item{\code{midpoint}}{Horizontal distance of the node from the left
      border of the branch}
    \item{\code{text}}{Text label of the node}
    \item{\code{edgetext}}{Text label for the edge leading to the node}
  }
  Terminal nodes (leaves of the tree) can have arbitrary value but must
  not be a list.

  \code{cut.dendrogram()} returns a list with components \code{$upper} and
  \code{$lower}, the first is a truncated version of the original tree,
  also of class \code{dendrogram},
  the latter a list with the branches obtained from cutting the tree,
  each a \code{dendrogram}.

  Objects of class \code{"hclust"} can be converted to class
  \code{"dendrogram"} using method \code{as.dendrogram}.

  \code{plotNode()} and \code{plotNodeLimit()} are helper functions.
}
\examples{
library(mva)
data(USArrests)
hc <- hclust(dist(USArrests), "ave")
str(dend1 <- as.dendrogram(hc))
plot(dend1)
dend2 <- cut(dend1, h=70)
plot(dend2$upper)
plot(dend2$lower[[3]])
}
%FIXME !! -- proper Keyword !!
\keyword{multivariate}
\name{dist}
\title{Distance Matrix Computation}
\usage{
dist(x, method = "euclidean", diag = FALSE, upper = FALSE)

print.dist(x, diag = NULL, upper = NULL, \dots)
as.matrix.dist(x)
as.dist(m, diag = FALSE, upper = FALSE)
}
\alias{dist}
\alias{print.dist}
\alias{format.dist}
\alias{as.matrix.dist}
\alias{names.dist}
\alias{names<-.dist}
\alias{as.dist}
\arguments{
  \item{x}{A matrix or (data frame).  Distances between the rows of
    \code{x} will be computed.}
  \item{method}{The distance measure to be used. This must be one of
    \code{"euclidean"}, \code{"maximum"}, \code{"manhattan"},
    \code{"canberra"} or \code{"binary"}.
    Any unambiguous substring can be given.}
  \item{diag}{A logical value indicating whether the diagonal of the
    distance matrix should be printed by \code{print.dist}.}
  \item{upper}{A logical value indicating whether the upper triangle of the
    distance matrix should be printed by \code{print.dist}.}
  \item{m}{A matrix of distances to be converted to a \code{"dist"}
    object (only the lower triangle is used, the rest is ignored).}
  \item{\dots}{further arguments, passed to the (next) \code{print} method.}
}
\description{
  This function computes and returns the distance matrix computed by
  using the specified distance measure to compute the distances between
  the rows of a data matrix.
}
\details{
  Available distance measures are (written for two vectors \eqn{x} and
  \eqn{y}):
  \describe{
    \item{\code{euclidean}:}{Usual square distance between the two
      vectors (2 norm).}

    \item{\code{maximum}:}{Maximum distance between two components of \eqn{x}
      and \eqn{y} (supremum norm)}

    \item{\code{manhattan}:}{Absolute distance between the two vectors
      (1 norm).}

    \item{\code{canberra}:}{\eqn{\sum_i |x_i - y_i| / |x_i + y_i|}{%
	sum(|x_i - y_i| / |x_i + y_i|)}.  Terms with zero numerator and
      denominator are omitted from the sum and treated as if the values
      were missing.
    }

    \item{\code{binary}:}{(aka \emph{asymmetric binary}): The vectors
      are regarded as binary bits, so non-zero elements are `on' and zero
      elements are `off'.  The distance is the \emph{proportion} of
      bits in which only one is on amongst those in which at least one is on.}
  }

  Missing values are allowed, and are excluded from all computations
  involving the rows within which they occur.  If some columns are
  excluded in calculating a Euclidean, Manhattan or Canberra distance,
  the sum is scaled up proportionally to the number of columns used.
  If all pairs are excluded when calculating a particular distance,
  the value is \code{NA}.

  The functions \code{as.matrix.dist()} and \code{as.dist()} can be used
  for conversion between objects of class \code{"dist"} and conventional
  distance matrices and vice versa.
}
\value{
  An object of class \code{"dist"}.

  The lower triangle of the distance matrix stored by columns in a
  single vector.  The vector has the attributes \code{"Size"},
  \code{"Diag"}, \code{"Upper"}, \code{"Labels"} and \code{"class"} equal
  to \code{"dist"}.
}
\references{
  Mardia, K. V., Kent, J. T. and Bibby, J. M. (1979)
  \emph{Multivariate Analysis.} London: Academic Press.
}
\seealso{
  \code{\link{hclust}}.
}
\examples{
x <- matrix(rnorm(100), nrow=5)
dist(x)
dist(x, diag = TRUE)
dist(x, upper = TRUE)
m <- as.matrix(dist(x))
d <- as.dist(m)
stopifnot(d == dist(x))
names(d) <- LETTERS[1:5]
print(d, digits = 3)

## example of binary and canberra distances.
x <- c(0, 0, 1, 1, 1, 1)
y <- c(1, 0, 1, 1, 0, 1)
dist(rbind(x,y), method="binary")
## answer 0.4 = 2/5
dist(rbind(x,y), method="canberra")
## answer 2 * (6/5)
}
\keyword{multivariate}
\keyword{cluster}
\name{factanal}
\alias{factanal}
\alias{factanal.fit.mle}
\title{Factor Analysis}
\description{
  Perform maximum-likelihood factor analysis on a covariance matrix or
  data matrix.
}
\usage{
factanal(x, factors, data = NULL, covmat = NULL, n.obs = NA,
         subset, na.action,
         start = NULL, scores = c("none", "regression", "Bartlett"),
         rotation = "varimax", control = NULL, ...)
}
\arguments{
  \item{x}{Either a formula or a numeric matrix or an object that can be
    coerced to a numeric matrix.}
  \item{factors}{The number of factors to be fitted.}
  \item{data}{A data frame.}
  \item{covmat}{A covariance matrix, or a covariance list as returned by
    \code{\link{cov.wt}}. Of course, correlation matrices are covariance
    matrices.}
  \item{n.obs}{The number of observations, used if \code{covmat} is a
    covariance matrix.}
  \item{subset}{A specification of the cases to be used, if \code{x} is
    used as a matrix or formula.}
  \item{na.action}{The \code{na.action} to be used if \code{x} is
    used as a formula.}
  \item{start}{\code{NULL} or a matrix of starting values, each column
    giving an initial set of uniquenesses.}
  \item{scores}{Type of scores to produce, if any.  The default is none,
    \code{"regression"} gives Thompson's scores, \code{"Bartlett"} given
    Bartlett's weighted least-squares scores. Partial matching allows
    these names to be abbreviated.}
  \item{rotation}{character. \code{"none"} or the name of a function
    to be used to rotate the factors: it will be called with first
    argument the loadings matrix, and should return a list with component
    \code{loadings} giving the rotated loadings, or just the rotated loadings.}
  \item{control}{A list of control values,
    \describe{
      \item{nstart}{The number of starting values to be tried if
	\code{start = NULL}. Default 1.}
      \item{trace}{logical. Output tracing information? Default \code{FALSE}.}
      \item{lower}{The lower bound for uniquenesses during
	optimization. Should be > 0. Default 0.005.}
      \item{opt}{A list of control values to be passed to
	\code{\link{optim}}'s \code{control} argument.}
      \item{rotate}{a list of additional arguments for the rotation function.}
    }
  }
  \item{\dots}{Components of \code{control} can also be supplied as
    named arguments to \code{factanal}.}
}
\details{
  The factor analysis model is
  \deqn{x = \Lambda f + e}{ x = Lambda f + e}
  for a \eqn{p}--element row-vector \eqn{x}, a \eqn{p \times k}{p x k}
  matrix of \emph{loadings}, a \eqn{k}--element vector of \emph{scores}
  and a \eqn{p}--element vector of errors.  None of the components
  other than \eqn{x} is observed, but the major restriction is that the
  scores be uncorrelated and of unit variance, and that the errors be
  independent with variances \eqn{\Phi}{Phi}, the
  \emph{uniquenesses}.  Thus factor analysis is in essence a model for
  the covariance matrix of \eqn{x},
  \deqn{\Sigma = \Lambda^\prime\Lambda + \Psi}{Sigma = Lambda'Lambda + Psi}
  There is still some indeterminacy in the model for it is unchanged
  if \eqn{\Lambda}{Lambda} is replaced by \eqn{G\Lambda}{G Lambda} for
  any orthogonal matrix \eqn{G}.  Such matrices \eqn{G} are known as
  \emph{rotations} (although the term is applied also to non-orthogonal
  invertible matrices).
  
  If \code{covmat} is supplied it is used.  Otherwise \code{x} is used if
  it is a matrix, or a formula \code{x} is used with \code{data} to
  construct a model matrix, and that is used to construct a covariance
  matrix.  (It makes no sense for
  the formula to have a response.)  Once a covariance matrix is found or
  calculated from \code{x}, it is converted to a correlation matrix for
  analysis.  The correlation matrix is returned as component
  \code{correlation} of the result.

  The fit is done by optimizing the log likelihood assuming multivariate
  normality over the uniquenesses.  (The maximizing loadings for given
  uniquenesses can be found analytically: Lawley & Maxwell (1971,
  p. 27).)  All the starting values supplied in \code{start} are tried
  in turn and the best fit obtained is used.  If \code{start = NULL}
  then the first fit is started at the value suggested by Jöreskog
  (1963) and given by Lawley & Maxwell (1971, p. 31), and then
  \code{control$nstart - 1} other values are tried, randomly selected
  as equal values of the uniquenesses.

  The uniquenesses are technically constrained to lie in \eqn{[0, 1]},
  but near-zero values are problematical, and the optimization is
  done with a lower bound of \code{control$lower}, default 0.005
  (Lawley & Maxwell, 1971, p. 32).

  Scores can only be produced if a data matrix is supplied and used.
  The first method is the regression method of Thomson (1951), the
  second the weighted least squares method of Bartlett (1937, 8).
  Both are estimates of the unobserved scores \eqn{f}.  Thomson's method
  regresses (in the population) the unknown \eqn{f} on \eqn{x} to yield
  \deqn{\hat f = \Lambda^\prime \Sigma^{-1} x}{hat f = Lambda' Sigma^-1 x}
  and then substitutes the sample estimates of the quantities on the
  right-hand side.  Bartlett's method minimizes the sum of squares of
  standardized errors over the choice of \eqn{f}, given (the fitted)
  \eqn{\Lambda}{Lambda}.

  If \code{x} is a formula then the standard NA-handling is applied to
  the scores (if requested): see \code{\link{napredict}}.
}
\value{
  An object of class \code{"factanal"} with components
  \item{loadings}{A matrix of loadings, one column for each factor.  The
    factors are ordered in decreasing order of sums of squares of
    loadings, and given the sign that will make the sum of the loadings
    positive.}
  \item{uniquenesses}{The uniquenesses computed.}
  \item{correlation}{The correlation matrix used.}
  \item{criteria}{The results of the optimization: the value of the
    negative log-likelihood and information on the iterations used.}
  \item{factors}{The argument \code{factors}.}
  \item{dof}{The number of degrees of freedom of the factor analysis model.}
  \item{method}{The method: always \code{"mle"}.}
  \item{scores}{If requested, a matrix of scores.}
  \item{n.obs}{The number of observations if available, or \code{NA}.}
  \item{call}{The matched call.}
  \item{na.action}{If relevant.}
}

\note{
  There are so many variations on factor analysis that it is hard to
  compare output from different programs.  Further, the optimization in
  maximum likelihood factor analysis is hard, and many other examples we
  compared had less good fits than produced by this function.  In
  particular, solutions which are Heywood cases (with one or more
  uniquenesses essentially zero) are much often common than most texts
  and some other programs would lead one to believe.
}

\references{
  Bartlett, M. S. (1937) The statistical conception of mental factors.
  \emph{British Journal of Psychology}, \bold{28}, 97--104.

  Bartlett, M. S. (1938) Methods of estimating mental
  factors. \emph{Nature}, \bold{141}, 609--610.
  
  Jöreskog, K. G. (1963) \emph{Statistical Estimation in Factor
    Analysis.}  Almqvist and Wicksell.
  
  Lawley, D. N. and Maxwell, A. E. (1971) \emph{Factor Analysis as a
    Statistical Method.} Second edition. Butterworths.

  Thomson, G. H. (1951) \emph{The Factorial Analysis of Human Ability.}
  London University Press.
}
\author{B. D. Ripley}

\seealso{
  \code{\link{print.loadings}},
  \code{\link{varimax}}, \code{\link{princomp}},
  \code{\link{ability.cov}}, \code{\link{Harman23.cor}},
  \code{\link{Harman74.cor}}
}

\examples{
# A little demonstration, v2 is just v1 with noise,
# and same for v4 vs. v3 and v6 vs. v5
# Last four cases are there to add noise
# and introduce a positive manifold (g factor)
v1 <- c(1,1,1,1,1,1,1,1,1,1,3,3,3,3,3,4,5,6)
v2 <- c(1,2,1,1,1,1,2,1,2,1,3,4,3,3,3,4,6,5)
v3 <- c(3,3,3,3,3,1,1,1,1,1,1,1,1,1,1,5,4,6)
v4 <- c(3,3,4,3,3,1,1,2,1,1,1,1,2,1,1,5,6,4)
v5 <- c(1,1,1,1,1,3,3,3,3,3,1,1,1,1,1,6,4,5)
v6 <- c(1,1,1,2,1,3,3,3,4,3,1,1,1,2,1,6,5,4)
m1 <- cbind(v1,v2,v3,v4,v5,v6)
cor(m1)
factanal(m1, factors=3) # varimax is the default
factanal(m1, factors=3, rotation="promax")
# The following shows the g factor as PC1
prcomp(m1)

## formula interface
factanal(~v1+v2+v3+v4+v5+v6, factors = 3,
         scores = "Bartlett")$scores

## a realistic example from Barthlomew (1987, pp. 61-65)
example(ability.cov)
}
\keyword{multivariate}
\name{hclust}
\title{Hierarchical Clustering}
\alias{hclust}
\alias{plot.hclust}
\alias{print.hclust}
\description{
  Performs a hierarchical cluster analysis on a set of dissimilarities.
}
\usage{
hclust(d, method = "complete", members=NULL)

\method{plot}{hclust}(x, labels = NULL, hang = 0.1,
            axes = TRUE, frame.plot = FALSE, ann = TRUE,
            main = "Cluster Dendrogram",
            sub = NULL, xlab = NULL, ylab = "Height", \dots)
}
\arguments{
  \item{d}{a dissimilarity structure as produced by \code{dist}.}

  \item{method}{the agglomeration method to be used. This should
    be (an unambiguous abbreviation of) one of
    \code{"ward"}, \code{"single"}, \code{"complete"},
    \code{"average"}, \code{"mcquitty"}, \code{"median"} or
    \code{"centroid"}.}

  \item{members}{\code{NULL} or a vector with length size of \code{d}.}

  \item{x}{an object of the type produced by \code{hclust}.}

  \item{hang}{The fraction of the plot height by which labels should hang
    below the rest of the plot.
    A negative value will cause the labels to hang down from 0.}

  \item{labels}{A character vector of labels for the leaves of the
    tree. By default the row names or row numbers of the original data are
    used. If \code{labels=FALSE} no labels at all are plotted.}

  \item{axes, frame.plot, ann}{logical flags as in \code{\link{plot.default}}.}
  \item{main, sub, xlab, ylab}{character strings for
    \code{\link{title}}.  \code{sub} and \code{xlab} have a non-NULL
    default when there's a \code{tree$call}.}
  \item{\dots}{Further graphical arguments.}
}
\value{
  An object of class \bold{hclust} which describes the
  tree produced by the clustering process.
  The object is a list with components:

  \item{merge}{an \eqn{n-1} by 2 matrix.
    Row \eqn{i} of \code{merge} describes the merging of clusters
    at step \eqn{i} of the clustering.
    If an element \eqn{j} in the row is negative,
    then observation \eqn{-j} was merged at this stage.
    If \eqn{j} is positive then the merge
    was with the cluster formed at the (earlier) stage \eqn{j}
    of the algorithm.
    Thus negative entries in \code{merge} indicate agglomerations
    of singletons, and positive entries indicate agglomerations
    of non-singletons.}

  \item{height}{a set of \eqn{n-1} non-decreasing real values.
    The clustering \emph{height}: that is, the value of
    the criterion associated with the clustering
    \code{method} for the particular agglomeration.}

  \item{order}{a vector giving the permutation of the original
    observations suitable for plotting, in the sense that a cluster
    plot using this ordering and matrix \code{merge} will not have
    crossings of the branches.}

  \item{labels}{labels for each of the objects being clustered.}

  \item{call}{the call which produced the result.}

  \item{method}{the cluster method that has been used.}

  \item{dist.method}{the distance that has been used to create \code{d}
    (only returned if the distance object has a \code{"method"}
    attribute).}
}
\details{
  This function performs a hierarchical cluster analysis
  using a set of dissimilarities for the \eqn{n} objects being
  clustered.  Initially, each object is assigned to its own
  cluster and then the algorithm proceeds iteratively,
  at each stage joining the two most similar clusters,
  continuing until there is just a single cluster.
  At each stage distances between clusters are recomputed
  by the Lance--Williams dissimilarity update formula
  according to the particular clustering method being used.

  A number of different clustering methods are provided.
  \emph{Ward's} minimum variance method aims at finding compact,
  spherical clusters.  The \emph{complete linkage} method finds
  similar clusters. The \emph{single linkage} method
  (which is closely related to the minimal spanning tree)
  adopts a `friends of friends' clustering strategy.
  The other methods can be regarded as aiming
  for clusters with characteristics somewhere between
  the single and complete link methods.

  If \code{members!=NULL}, then \code{d} is taken to be a
  dissimilarity matrix between clusters instead of dissimilarities
  between singletons and \code{members} gives the number of observations
  per cluster. This way the hierarchical cluster algorithm can be ``started
  in the middle of the dendrogram'', e.g., in order to reconstruct the
  part of the tree above a cut (see examples). Dissimilarities between
  clusters can be efficiently computed (i.e., without \code{hclust}
  itself) only for a limited number of distance/linkage combinations,
  the simplest one being squared Euclidean distance and centroid
  linkage. In this case the dissimilarities between the clusters are
  the squared Euclidean distances between cluster means.

  In hierarchical cluster displays, a decision is needed at each merge to
  specify which subtree should go on the left and which on the right.
  Since, for \eqn{n} observations there are \eqn{n-1} merges,
  there are \eqn{2^{(n-1)}} possible orderings for the leaves
  in a cluster tree, or dendrogram.
  The algorithm used in \code{hclust} is to order the subtree so that
  the tighter cluster is on the left (the last, i.e. most recent,
  merge of the left subtree is at a lower value than the last
  merge of the right subtree).
  Single observations are the tightest clusters possible,
  and merges involving two observations place them in order by their
  observation sequence number.
}
\references{
  Everitt, B. (1974).
  \emph{Cluster Analysis}.
  London: Heinemann Educ. Books.

  Hartigan, J. A. (1975).
  \emph{Clustering  Algorithms}.
  New York: Wiley.

  Sneath, P. H. A. and R. R. Sokal (1973).
  \emph{Numerical Taxonomy}.
  San Francisco: Freeman.

  Anderberg, M. R. (1973).
  \emph{Cluster Analysis for Applications}.
  Academic Press: New York.

  Gordon, A. D. (1981).
  \emph{Classification}.
  London: Chapman and Hall.

  Murtagh, F. (1985).
  ``Multidimensional Clustering Algorithms'', in
  \emph{COMPSTAT Lectures 4}.
  Wuerzburg: Physica-Verlag
  (for algorithmic details of algorithms used).
}
\author{
  The \code{hclust} function is based on Fortran code
  contributed to STATLIB by F. Murtagh.
}
\seealso{
  \code{\link{kmeans}}.
}
\examples{
library(mva)
data(USArrests)
hc <- hclust(dist(USArrests), "ave")
plot(hc)
plot(hc, hang=-1)

## Do the same with centroid clustering and squared Euclidean distance,
## cut the tree into ten clusters and reconstruct the upper part of the
## tree from the cluster centers.
hc <- hclust(dist(USArrests)^2, "cen")
memb <- cutree(hc, k=10)
cent <- NULL
for(k in 1:10){
  cent <- rbind(cent, apply(USArrests[memb==k,,drop=FALSE], 2, mean))
}
hc1 <- hclust(dist(cent)^2, method="cen", members=table(memb))
opar <- par(mfrow=c(1,2))
plot(hc,  labels=FALSE, hang=-1, main= "Original Tree")
plot(hc1, labels=FALSE, hang=-1, main= "Re-start from 10 clusters")
par(opar)
}
\keyword{multivariate}
\keyword{cluster}
\name{identify.hclust}
\alias{identify.hclust}
\title{Identify Clusters in a Dendrogram}
\description{
  \code{identify.hclust} reads the position of the graphics pointer when the
  (first) mouse button is pressed.  It then cuts the tree at the
  vertical position of the pointer and highlights the cluster containing
  the horizontal position of the pointer. Optionally a function is
  applied to the index of data points contained in the cluster.
}
\usage{
\method{identify}{hclust}(x, FUN=NULL, N=20, MAXCLUSTER=20, DEV.FUN=NULL, \dots)
}
\arguments{
  \item{x}{an object of the type produced by \code{hclust}.}
  \item{FUN}{(optional) function to be applied to the index numbers of
    the data points in a cluster (see Details below).}
  \item{N}{the maximum number of clusters to be identified.}
  \item{MAXCLUSTER}{The maximum number of clusters that can be produced
    by a cut (limits the effective vertical range of the pointer). }
  \item{DEV.FUN}{(optional) integer scalar. If specified, the
    corresponding graphics device is amde active before \code{FUN} is
    applied.}
  \item{\dots}{further arguments to \code{FUN}.}
}
\details{
  By default clusters can be identified using the mouse and an
  \code{\link{invisible}} list of indices of the respective data points
  is returned. 

  If \code{FUN} is not \code{NULL}, then the index vector of data points
  is passed to this function as first argument, see the examples
  below. If active graphics device for \code{FUN} can be specified using
  \code{DEV.FUN}.
  
  The identification process is terminated by pressing any mouse
  button other than the first, or by clicking outside the graphics
  window.
}
\value{
  Either a list of data point index vectors or a list of return values
  of \code{FUN}.
}
\seealso{
  \code{\link{hclust}},
  \code{\link{rect.hclust}}
}
\examples{
\dontrun{
library(mva)
data(USArrests)
hca <- hclust(dist(USArrests))
plot(hca)
x <- identify.hclust(hca)
x

data(iris)
hci <- hclust(dist(iris[,1:4]))
plot(hci)
identify.hclust(hci, function(k) print(table(iris[k,5])))

x11()
dev.set(2)
plot(hci)
identify.hclust(hci, function(k) barplot(table(iris[k,5])), DEV.FUN=3)
}
}
\keyword{cluster}
\keyword{iplot}
\name{kmeans}
\alias{kmeans}
\title{
K-Means Clustering
}
\description{
  Perform k-means clustering on a data matrix.
}
\usage{
kmeans(x, centers, iter.max = 10)
}
\arguments{
\item{x}{
  A numeric matrix of data, or an object that can be coerced to such a
  matrix (such as a numeric vector or a data frame with all numeric columns).
}
\item{centers}{
  Either the number of clusters or a set of initial cluster centers.
  If the first, a random set of rows in \code{x} are chosen as the initial
  centers.
}
\item{iter.max}{
  The maximum number of iterations allowed.
}}
\details{
  The data given by \code{x} is clustered by the k-means algorithm.
  When this terminates, all cluster centres are at the mean of
  their Voronoi sets (the set of data points which are nearest to
  the cluster centre).

  The algorithm of Hartigan and Wong (1979) is used.
}
\value{
  A list with components:

  \item{cluster}{
    A vector of integers indicating the cluster to which each point is
    allocated.
  }
  \item{centers}{A matrix of cluster centres.}
  \item{withinss}{The within-cluster sum of squares for each cluster.}
  \item{size}{The number of points in each cluster.}
}
\references{
  Hartigan, J.A. and Wong, M.A. (1979).
  A K-means clustering algorithm.
  \emph{Applied Statistics} \bold{28}, 100--108.
}
\examples{
# a 2-dimensional example
x <- rbind(matrix(rnorm(100, sd = 0.3), ncol = 2),
           matrix(rnorm(100, mean = 1, sd = 0.3), ncol = 2))
cl <- kmeans(x, 2, 20)
plot(x, col = cl$cluster)
points(cl$centers, col = 1:2, pch = 8)
}
\keyword{multivariate}
\keyword{cluster}

\name{loadings}
\alias{loadings}
\alias{print.loadings}
\alias{print.factanal}
\title{Print Loadings in Factor Analysis}
\description{
  Extract or print loadings in factor analysis (or principal
  components analysis).
}
\usage{
loadings(x)
print.loadings(x, digits = 3, cutoff = 0.1, sort = FALSE, ...)
print.factanal(x, digits = 3, ...)
}
\arguments{
  \item{x}{an object of class \code{"factanal"} or \code{"princomp"}
    or the \code{loadings} component of such an object.}
  \item{digits}{number of decimal places to use in printing uniquenesses
    and loadings.}
  \item{cutoff}{loadings smaller than this (in absolute value) are suppressed.}
  \item{sort}{logical. If true, the variables are sorted by their
    importance on each factor.  Each variable with any loading larger
    than 0.5 (in modulus) is assigned to the factor with the largest
    loading, and the variables are printed in the order of the factor
    they are assigned to, then those unassigned.}
  \item{\dots}{further arguments for other methods, such as
    \code{cutoff} and \code{sort} for \code{print.factanal}.}
}
\author{B. D. Ripley}

\seealso{
  \code{\link{factanal}}, \code{\link{princomp}}
}

\keyword{multivariate}
\keyword{print}
\name{prcomp}
\alias{prcomp}
\alias{plot.prcomp}
\alias{print.prcomp}
\alias{summary.prcomp}
\alias{print.summary.prcomp}
\title{Principal Components Analysis}
\description{
  Performs a principal components analysis on the given data matrix
  and returns the results as an object of class \code{prcomp}.}
\usage{
prcomp(x, retx = TRUE, center = TRUE, scale. = FALSE, tol = NULL)
}
\arguments{
  \item{x}{a matrix (or data frame) which provides the data for the
    principal components analysis.}
  \item{retx}{a logical value indicating whether the rotated variables
    should be returned.}
  \item{center}{a logical value indicating whether the variables
    should be shifted to be zero centered. Alternately, a vector of
    length equal the number of columns of \code{x} can be supplied.
    The value is passed to \code{scale}.}
  \item{scale.}{a logical value indicating whether the variables should
    be scaled to have unit variance before the analysis takes
    place. The default is \code{FALSE} for consistency with S, but
    in general scaling is advisable. Alternately, a vector of length
    equal the number of columns of \code{x} can be supplied.  The
    value is passed to \code{scale}.}
  \item{tol}{a value indicating the magnitude below which components
    should be omitted. (Components are omitted if their
    standard deviations are less than or equal to \code{tol} times the
    standard deviation of the first component.)
    With the default null setting, no components
    are omitted.  Other settings for tol could be \code{tol = 0} or
    \code{tol = sqrt(.Machine$double.eps)}, which would omit
    essentially constant components.} 
}
\value{
  \code{prcomp} returns an list with class \code{"prcomp"}
  containing the following components:
  \item{sdev}{the standard deviations of the principal components
    (i.e., the square roots of the eigenvalues of the
    covariance/correlation matrix, though the calculation
    is actually done with the singular values of the data matrix).}
  \item{rotation}{the matrix of variable loadings (i.e., a matrix
    whose columns contain the eigenvectors).  The function
    \code{princomp} returns this in the element \code{loadings}.}
  \item{x}{if \code{retx} is true the value of the rotated data (the
    data multiplied by the \code{rotation} matrix) is returned.}
}
\details{
  The calculation is done by a singular value decomposition of the
  (centered and scaled) data matrix, not by using \code{eigen} on the
  covariance matrix.  This
  is generally the preferred method for numerical accuracy.  The
  \code{print} method for the these objects prints the results in a nice
  format and the \code{plot} method produces a scree plot.
}
\references{
  Mardia, K. V., J. T. Kent, and J. M. Bibby (1979)
  \emph{Multivariate Analysis}, London: Academic Press.

  Venables, W. N. and B. D. Ripley (1997, 9)
  \emph{Modern Applied Statistics with S-PLUS}, Springer-Verlag.
}
\seealso{
  \code{\link{princomp}}, \code{\link{cor}}, \code{\link{cov}},
  \code{\link{svd}}, \code{\link{eigen}}.
}
\examples{
## the variances of the variables in the
## USArrests data vary by orders of magnitude, so scaling is appropriate
data(USArrests)
prcomp(USArrests)  # inappropriate
prcomp(USArrests, scale = TRUE)
plot(prcomp(USArrests))
summary(prcomp(USArrests, scale = TRUE))
}
\keyword{multivariate}
\name{princomp}
\alias{princomp}
\alias{princomp.formula}
\alias{princomp.default}
\alias{plot.princomp}
\alias{print.princomp}
\alias{predict.princomp}
\title{Principal Components Analysis}
\usage{
\method{princomp}{formula}(x, data = NULL, subset, na.action, ...)
\method{princomp}{default}(x, cor = FALSE, scores = TRUE, covmat = NULL,
         subset = rep(TRUE, nrow(as.matrix(x))), ...)
}
\arguments{
  \item{x}{a formula or matrix (or data frame) which provides the data for the
    principal components analysis.}
  \item{data}{an optional data frame containing the variables in the
    formula \code{x}. By default the variables are taken from
    \code{environment(x)}.}
  \item{subset}{an optional vector used to select rows (observations) of the
    data matrix \code{x}.}
  \item{na.action}{a function which indicates what should happen
    when the data contain \code{NA}s.  The default is set by
    the \code{na.action} setting of \code{\link{options}}, and is
    \code{\link{na.fail}} if that is unset. The ``factory-fresh''
    default is \code{\link{na.omit}}.}
  \item{cor}{a logical value indicating whether the calculation should
    use the correlation matrix or the covariance matrix.}
  \item{scores}{a logical value indicating whether the score on each
    principal component should be calculated.}
  \item{covmat}{a covariance matrix, or a covariance list as returned by
    \code{\link{cov.wt}}, \code{\link{cov.mve}} or \code{\link{cov.mcd}}.
    If supplied, this is used rather than the covariance matrix of
    \code{x}.}
  \item{\dots}{arguments passed to or from other methods. If \code{x} is
    a formula one might specify \code{cor} or \code{scores}.}
}
\description{
  \code{princomp} performs a principal components analysis on the given
  data matrix and returns the results as an object of class
  \code{princomp}.
}
\value{
  \code{princomp} returns a list with class \code{"princomp"}
  containing the following components:
  \item{sdev}{the standard deviations of the principal components.}
  \item{loadings}{the matrix of variable loadings (i.e., a matrix
    whose columns contain the eigenvectors).  This is of class
    \code{"loadings"}: see \code{\link{loadings}} for its \code{print}
    method.}
  \item{center}{the means that were subtracted.}
  \item{scale}{the scalings applied to each variable.}
  \item{n.obs}{the number of observations.}
  \item{scores}{if \code{scores = TRUE}, the scores of the supplied
    data on the principal components.}
  \item{call}{the matched call.}
  \item{na.action}{If relevant.}
}
\details{
  \code{princomp} is a generic function with \code{"formula"} and
  \code{"default"} methods.

  The calculation is done using \code{\link{eigen}} on the correlation or
  covariance matrix, as determined by \code{\link{cor}}.  This is done for
  compatibility with the S-PLUS result.  A preferred method of
  calculation is to use svd on \code{x}, as is done in \code{prcomp}.

  Note that the default calculation uses divisor \code{N} for the
  covariance matrix.

  The \code{\link{print}} method for the these objects prints the
  results in a nice format and the \code{\link{plot}} method produces
  a scree plot (\code{\link{screeplot}}).  There is also a
  \code{\link{biplot}} method.

  If \code{x} is a formula then the standard NA-handling is applied to
  the scores (if requested): see \code{\link{napredict}}.
}
\references{
  Mardia, K. V., J. T. Kent and J. M. Bibby (1979).
  \emph{Multivariate Analysis}, London: Academic Press.

  Venables, W. N. and B. D. Ripley (1997, 9).
  \emph{Modern Applied Statistics with S-PLUS}, Springer-Verlag.
}
\seealso{
  \code{\link{summary.princomp}}, \code{\link{screeplot}},
  \code{\link{biplot.princomp}},
  \code{\link{prcomp}}, \code{\link{cor}}, \code{\link{cov}},
  \code{\link{eigen}}.
}
\examples{
## The variances of the variables in the
## USArrests data vary by orders of magnitude, so scaling is appropriate
data(USArrests)
(pc.cr <- princomp(USArrests))  # inappropriate
princomp(USArrests, cor = TRUE) # =^= prcomp(USArrests, scale=TRUE)
## Similar, but different:
## The standard deviations differ by a factor of sqrt(49/50)

summary(pc.cr <- princomp(USArrests, cor = TRUE))
loadings(pc.cr)  ## note that blank entries are small but not zero
plot(pc.cr) # shows a screeplot.
biplot(pc.cr)

## Formula interface
princomp(~ ., data = USArrests, cor = TRUE)
# NA-handling
USArrests[1, 2] <- NA
pc.cr <- princomp(~ ., data = USArrests, na.action=na.exclude, cor = TRUE)
pc.cr$scores
}
\keyword{multivariate}
\name{rect.hclust}
\alias{rect.hclust}
\title{Draw Rectangles Around Hierarchical Clusters}
\description{
  Draws rectangles around the branches of a dendrogram highlighting the
  corresponding clusters. First the dendrogram is cut at a certain
  level, then a rectangle is drawn around selected branches.
}
\usage{
rect.hclust(tree, k = NULL, which = NULL, x = NULL, h = NULL,
            border = 2, cluster = NULL)
}
\arguments{
 \item{tree}{an object of the type produced by \code{hclust}.}
 \item{k, h}{Scalar. Cut the dendrogram such that either exactly
   \code{k} clusters are produced or by cutting at height \code{h}.}
 \item{which, x}{A vector selecting the clusters around which a
   rectangle should be drawn. \code{which} seleccts clusters by number
   (from left to right in the tree), \code{x} selects clusters
   containing the respective horizontal coordinates. Default is
   \code{which = 1:k}.}
 \item{border}{Vector with border colors for the rectangles.}
 \item{cluster}{Optional vector with cluster memberships as returned by
   \code{cutree(hclust.obj, k = k)}, can be specified for efficiency if
   already computed.}
}
\value{
  (Invisibly) returns a list where each element contains a vector of
  data points contained in the respective cluster.}
\seealso{
  \code{\link{hclust}}, \code{\link{identify.hclust}}.
}
\examples{
library(mva)
data(USArrests)
hca <- hclust(dist(USArrests))
plot(hca)
rect.hclust(hca, k=3, border="red")
x <- rect.hclust(hca, h=50, which=c(2,7), border=3:4)
x
}
\keyword{aplot}
\keyword{cluster}

\name{screeplot}
\alias{screeplot}
\title{Screeplot of PCA Results}
\usage{
screeplot(x, npcs = min(10, length(x$sdev)),
          type = c("barplot", "lines"), main = deparse(substitute(x)), \dots)
}
\arguments{
  \item{x}{an object of class \code{"princomp"}, as
    from \code{\link{princomp}()}.}
  \item{npcs}{the number of principal components to be plotted.}
  \item{type}{the type of plot.}
  \item{main, \dots}{graphics parameters.}
}
\description{
  \code{screeplot} plots the variances against the number of the
  principal component. This is also the \code{plot} method for class
  \code{"princomp"}.
}
\references{
  Mardia, K. V., J. T. Kent and J. M. Bibby (1979).
  \emph{Multivariate Analysis}, London: Academic Press.

  Venables, W. N. and B. D. Ripley (1997, 9).
  \emph{Modern Applied Statistics with S-PLUS}, Springer-Verlag.
}
\seealso{
  \code{\link{princomp}}.
}
\examples{
## The variances of the variables in the
## USArrests data vary by orders of magnitude, so scaling is appropriate
data(USArrests)
(pc.cr <- princomp(USArrests, cor = TRUE))  # inappropriate
screeplot(pc.cr)

data(Harman74.cor)
fit <- princomp(covmat=Harman74.cor)
screeplot(fit)
screeplot(fit, npcs=24, type="lines")
}
\keyword{multivariate}
\name{summary.princomp}
\alias{summary.princomp}
\title{Summary method for Principal Components Analysis}
\usage{
\method{summary}{princomp}(object, loadings = FALSE, cutoff = 0.1,
        digits = 3, \dots) 

}
\arguments{
  \item{object}{an object of class \code{"princomp"}, as
    from \code{princomp()}.}
  \item{loadings}{logical. Should loadings be included?}
  \item{cutoff}{numeric. Loadings below this cutoff in absolute value
    are shown as blank in the output.}
  \item{digits}{the number of significant digits to be used in listing
    loadings.}
  \item{\dots}{arguments to be passed to or from other methods.}
}
\description{
  The \code{\link{summary}} method for class \code{"princomp"}.
}
\value{
  \code{object}, invisibly.
}
\seealso{
  \code{\link{princomp}}
}
\examples{
data(USArrests)
summary(pc.cr <- princomp(USArrests, cor=TRUE))
summary(princomp(USArrests, cor=TRUE),
        loadings = TRUE, cutoff = 0.2, digits = 2)
}
\keyword{multivariate}
\name{varimax}
\alias{promax}
\alias{varimax}
\title{Rotation Methods for Factor Analysis}
\description{
  These functions `rotate' loading matrices in factor analysis.
}
\usage{
varimax(x, normalize = TRUE, eps = 1e-5)
promax(x, m = 4)
}
\arguments{
  \item{x}{A loadings matrix, with \eqn{p} rows and \eqn{k < p} columns}
  \item{m}{The power used the target for \code{promax}.  Values of 2 to
    4 are recommended.}
  \item{normalize}{logical. Should Kaiser normalization be performed?
    If so the rows of \code{x} are re-scaled to unit length before
    rotation, and scaled back afterwards.}
  \item{eps}{The tolerance for stopping: the relative change in the sum
    of singular values.}
}
\details{
  These seek a `rotation' of the factors \code{x \%*\% T} that aims to
  clarify the structure of the loadings matrix.  The matrix \code{T}
  is a rotation (possibly with reflection) for \code{varimax}, but a
  general linear transformation for \code{promax}, with the variance of
  the factors being preserved.
}
\value{
  A list with components
  \item{loadings}{The `rotated' loadings matrix, \code{x \%*\% rotmat}.}
  \item{rotmat}{The `rotation matrix.}
}
\references{
  Hendrickson, A. E. and White, P. O. (1964) Promax: a quick method for
  rotation to orthogonal oblique structure. \emph{British Journal of
    Statistical Psychology}, \bold{17}, 65--70.

  Horst, P. (1965) \emph{Factor Analysis of Data Matrices.} Holt,
  Rinehart and Winston.  Chapter 10.

  Kaiser, H. F. (1958) The varimax criterion for analytic rotation in
  factor analysis. \emph{Psychometrika} \bold{23}, 187--200.

  Lawley, D. N. and Maxwell, A. E. (1971) \emph{Factor Analysis as a
    Statistical Method}. Second edition. Butterworths.
}
\author{B. D. Ripley}
\seealso{\code{\link{factanal}}, \code{\link{Harman74.cor}}.}

\examples{
data(swiss)
## varimax with normalize = T is the default
fa <- factanal( ~., 2, data = swiss)
varimax(fa$loadings, normalize = FALSE)
promax(fa$loadings)
}
\keyword{multivariate}
