\name{Harman23.cor}
\docType{data}
\alias{Harman23.cor}
\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}
\eof
\name{Harman74.cor}
\docType{data}
\alias{Harman74.cor}
\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}
\eof
\name{ability.cov}
\docType{data}
\alias{ability.cov}
\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}
\eof
\name{as.hclust}
\alias{as.hclust}
\alias{as.hclust.default}
\alias{as.hclust.twins}
\title{Convert Objects to Class hclust}
\usage{
as.hclust(x, \dots)
%as.hclust.default(x, \dots)
%as.hclust.twins(x, \dots)
}
\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 \pkg{cluster}.  The default method
  throws an error unless passed an \code{"hclust"} object.
}
\value{
  An object of class \code{"hclust"}.
}
\seealso{
  \code{\link{hclust}}, \code{\link[cluster]{diana}},
  \code{\link[cluster]{agnes}}
}
\examples{
x <- matrix(rnorm(30), ncol=3)
hc <- hclust(dist(x), method="complete")

if(require(cluster)) {# is a required package
  ag <- agnes(x, method="complete")
  hcag <- as.hclust(ag)
  ## The dendrograms order slightly differently:
  op <- par(mfrow=c(1,2))
  plot(hc) ;  mtext("hclust", side=1)
  plot(hcag); mtext("agnes",  side=1)
}
}
\keyword{multivariate}
\keyword{cluster}
\eof
\name{biplot}
\alias{biplot}
\alias{biplot.default}
\title{Biplot of Multivariate Data}
\usage{
biplot(x, \dots)

\method{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,
       main = NULL, sub = NULL, xlab = NULL, ylab = NULL, \dots)
}
\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.  If
    missing the default colour is looked for in the
    \code{\link{palette}}: if there it and the next colour as used,
    otherwise the first two colours of the paletter are used.}
  \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 tweak the
    scaling of the two sets 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}{Limits for the x and y axes in the units of the
    first set of variables.}
  \item{main, sub, xlab, ylab, \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.
}
\seealso{\code{\link{biplot.princomp}}, also for examples.}
\keyword{hplot}
\keyword{multivariate}
\eof
\name{biplot.princomp}
\alias{biplot.princomp}
\alias{biplot.prcomp}
\title{
Biplot for Principal Components
}
\description{
  Produces a biplot (in the strict sense) from the output of
  \code{\link{princomp}} or \code{\link{prcomp}}
}
\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}
\eof
\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
  \sQuote{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{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  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}
\eof
\name{cmdscale}
\alias{cmdscale}
\title{Classical (Metric) Multidimensional Scaling}
\usage{
cmdscale(d, k = 2, eig = FALSE, add = FALSE, x.ret = FALSE)
}
\description{
  Classical multidimensional scaling of a data matrix.
  Also known as \emph{principal coordinates analysis} (Gower, 1966).
}
\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,\ldots,n-1\}}.}
  \item{eig}{indicates whether eigenvalues should be returned.}
  \item{add}{logical indicating if an additive constant \eqn{c*} should
    be computed, and added to the non-diagonal dissimilarites such that
    all \eqn{n-1} eigenvalues are non-negative.}
  \item{x.ret}{indicates whether the doubly centered symmetric distance
    matrix should be returned.}
}
\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 \pkg{MASS}
  provide alternative ordination techniques.

  When \code{add = TRUE}, an additive constant \eqn{c*} is computed, and
  the dissimilarities \eqn{d_{ij} + c*}{d[i,j] + c*} are used instead of
  the original \eqn{d_{ij}}{d[i,j]}'s.

  Whereas S (Becker \emph{et al.}, 1988) computes this constant using
  an approximation suggested by Torgerson, \R uses the analytical
  solution of Cailliez (1983), see also Cox and Cox (1994).
}
\value{
  If \code{eig = FALSE} and \code{x.ret = FALSE} (default), 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 \eqn{n-1} eigenvalues computed during the scaling process if
    \code{eig} is true.}
  \item{x}{the doubly centered distance matrix if \code{x.ret} is true.}
  \item{GOF}{a numeric vector of length 2, equal to say
    \eqn{(g_1,g_2)}{(g.1,g.2)}, where
    \eqn{g_i = (\sum_{j=1}^k \lambda_j)/ (\sum_{j=1}^n T_i(\lambda_j))}{%
         g.i = (sum{j=1..k} lambda[j]) / (sum{j=1..n} T.i(lambda[j]))}, where
       \eqn{\lambda_j}{lambda[j]} are the eigenvalues (sorted
       decreasingly),
       \eqn{T_1(v) = \left| v \right|}{T.1(v) = abs(v)}, and
       \eqn{T_2(v) = max( v, 0 )}{T.2(v) = max(v, 0)}.
     }
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Cailliez, F. (1983)
  The analytical solution of the additive constant problem.
  \emph{Psychometrika} \bold{48}, 343--349.

  Cox, T. F. and Cox, M. A. A. (1994)
  \emph{Multidimensional Scaling}.
  Chapman and Hall.

  Gower, J. C. (1966)  
  Some distance properties of latent root and vector 
  methods used in multivariate analysis.  
  \emph{Biometrika} \bold{53}, 325--328.

  Mardia, K. V., Kent, J. T. and Bibby, J. M. (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.
}
\seealso{
  \code{\link{dist}}.
  Also \code{\link[MASS]{isoMDS}} and \code{\link[MASS]{sammon}}
  in package \pkg{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)

cmdsE <- cmdscale(eurodist, k=20, add = TRUE, eig = TRUE, x.ret = TRUE)
str(cmdsE)
}
\keyword{multivariate}
\eof
\name{cophenetic}
\alias{cophenetic}
\title{Cophenetic Distances for a Hierarchical Clustering}
\description{
  Computes the cophenetic distances for a hierarchical clustering.
}
\usage{
cophenetic(x)
}
\arguments{
  \item{x}{an object of class \code{\link[mva]{hclust}} or with a method
    for \code{\link[mva]{as.hclust}()} such as \code{\link[cluster]{agnes}}.}
}
\details{
  The cophenetic distance between two observations that have been
  clustered is defined to be the intergroup dissimilarity at which the
  two observations are first combined into a single cluster.
  Note that this distance has many ties and restrictions.

  It can be argued that a dendrogram is an appropriate summary of some
  data if the correlation between the original distances and the
  cophenetic distances is high.  Otherwise, it should simply be viewed as
  the description of the output of the clustering algorithm.
}
\value{
  An object of class \code{dist}.
}
\references{
  Sneath, P.H.A. and Sokal, R.R (1973)
  \emph{Numerical Taxonomy: The Principles and Practice of Numerical
    Classification}, p. 278 ff;
  Freeman, San Francisco.
}
\author{Robert Gentleman}

\seealso{\code{\link{dist}}, \code{\link{hclust}}}

\examples{
 data(USArrests)
 library(mva)
 d1 <- dist(USArrests)
 hc <- hclust(d1, "ave")
 d2 <- cophenetic(hc)
 cor(d1,d2) # 0.7659

## Example from Sneath & Sokal, Fig. 5-29, p.279
d0 <- c(1,3.8,4.4,5.1, 4,4.2,5, 2.6,5.3, 5.4)
attributes(d0) <- list(Size = 5, diag=TRUE)
class(d0) <- "dist"
names(d0) <- letters[1:5]
d0
str(upgma <- hclust(d0, method = "average"))
plot(upgma, hang = -1)
#
(d.coph <- cophenetic(upgma))
cor(d0, d.coph) # 0.9911
}
\keyword{cluster}
\keyword{multivariate}

\eof
\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(s) of groups or the cut
  height(s).
}
\usage{
cutree(tree, k = NULL, h = NULL)
}
\arguments{
 \item{tree}{a tree as produced by \code{\link{hclust}}. \code{cutree()}
   only expects a list with components \code{merge}, \code{height}, and
   \code{labels}, of appropriate content each.}
 \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.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\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}}, \code{\link{dendrogram}} for cutting trees themselves.
}
\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"])
}
\keyword{multivariate}
\keyword{cluster}

\eof
\name{dendrogram}
\title{General Tree Structures}
\alias{dendrogram}% the class
\alias{as.dendrogram}
%\alias{as.dendrogram.hclust}
\alias{cut.dendrogram}
\alias{[[.dendrogram}
\alias{print.dendrogram}
\alias{rev.dendrogram}
\alias{str.dendrogram}
\alias{plot.dendrogram}
%\alias{plotNode}
%\alias{plotNodeLimit}
%\alias{isLeaf}
\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.

  The code is still in testing stage and the API may
  change in the future.
}
\usage{
as.dendrogram(object, \dots)

\method{plot}{dendrogram}(x, type = c("rectangle", "triangle"),
         center = FALSE, edge.root = !is.null(attr(x,"edgetext")),
         nodePar = NULL, edgePar = list(), xlab = "", ylab = "",
         horiz = FALSE, frame.plot = FALSE, \dots)

\method{cut}{dendrogram}(x, h, \dots)

\method{print}{dendrogram}(x, digits, \dots)

\method{rev}{dendrogram}(x)

\method{str}{dendrogram}(object, max.level = 0, digits.d = 3,
    give.attr = FALSE, wid = getOption("width"),
    nest.lev = 0, indent.str = "", \dots)
}
\arguments{
  \item{object}{any \R object that can be made into one of class
    \code{"dendrogram"}.}
  \item{x}{object of class \code{"dendrogram"}.}
  \item{type}{type of plot.}
  \item{center}{logical; if \code{TRUE}, nodes are plotted centered with
    respect to the leaves in the branch.  Otherwise (default), plot them
    in the middle of all direct child nodes.}
  \item{edge.root}{logical; if true, draw an edge to the root node.}
  \item{nodePar}{a \code{list} of plotting parameters to use for the
    nodes (see \code{\link{points}}) or \code{NULL} by default which
    does not draw symbols at the nodes.  The list may contain components
    named \code{pch}, \code{cex}, \code{col}, and/or \code{bg} each of
    which can have length two for specifying separate attributes for
    \emph{inner} nodes and \emph{leaves}.}
  \item{edgePar}{a \code{list} of plotting parameters to use for the
    edge (see \code{\link{lines}}).  The list may contain components
    named \code{col}, \code{lty} and/or \code{lwd}.}
  \item{horiz}{logical indicating if the dendrogram should be draw
    \emph{horizontally} or not.}
  \item{frame.plot}{logical indicating if a box around the plot should
    be drawn, see \code{\link{plot.default}}.}
  \item{h}{height at which the tree is cut.}
  \item{\dots, xlab, ylab}{graphical parameters, or arguments for
    other methods.}
  \item{digits}{integer specifiying the precision for printing, see
    \code{\link{print.default}}.}
  \item{max.level, digits.d, give.attr, wid, nest.lev, indent.str}{%
    arguments to \code{str}, see \code{\link{str.default}()}.  Note that
    the default `give.attr = FALSE' still shows \code{height} and
    \code{members} attributes for each node.}
}
\details{
  Warning: This documentation is preliminary.

  The dendrogram is directly represented as a nested list where each
  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}}{total number of leaves in the branch}
    \item{\code{height}}{numeric non-negative height at which the node
      is plotted.}
    \item{\code{midpoint}}{numeric horizontal distance of the node from
      the left border of the branch.  This is needed at least for
    \code{plot(*, center=FALSE)}.}
    \item{\code{label}}{character; the label of the node}
    \item{\code{edgetext}}{character; the label for the edge leading to
      the node}
    \item{\code{nodePar}}{a named list of length one vectors specifying
      node-specific attributes for \code{\link{points}} plotting, see
      the \code{nodePar} argument above.}
    \item{\code{edgePar}}{a named list of length one vectors specifying
      attributes for \code{\link{segments}} plotting of the edge leading
      to the node, see the \code{edgePar} argument above.}
    \item{\code{leaf}}{logical, if \code{TRUE}, the node is a leaf of
      the tree.}%  This will often be a \code{\link{character}} which can
    %      be used for plotting instead of the \code{text} attribute.}
  }

  \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}.

  There are \code{\link{[[}}, \code{\link{print}}, and \code{\link{str}}
  methods for \code{"dendrogram"} objects where the first one
  (extraction) ensures that selecting sub-branches keeps the class.

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

  \code{isLeaf()}, \code{plotNode()} and \code{plotNodeLimit()} are helper
  functions.
}
\note{
  When using \code{type = "triangle"}, \code{center = TRUE} often looks
  better.
}
\examples{
library(mva)
data(USArrests)
hc <- hclust(dist(USArrests), "ave")
(dend1 <- as.dendrogram(hc)) # "print()" method
str(dend1) # "str()" method

op <- par(mfrow= c(2,2), mar = c(3,3,1,1))
plot(dend1)
## "triangle" type and show inner nodes:
plot(dend1, nodePar=list(pch = c(1,NA),cex=0.8), type = "t", center=TRUE)
plot(dend1, edgePar=list(col = 1:2, lty = 2:3), edge.root = TRUE)
plot(dend1, nodePar=list(pch = 2:1,cex=.4*2:1, col = 2:3), horiz = TRUE)

dend2 <- cut(dend1, h=70)
plot(dend2$upper)
## leafs are wrong horizontally:%% FIXME ?!?
plot(dend2$upper, nodePar=list(pch = c(1,7), col = 2:1))
##  dend2$lower is *NOT* a dendrogram, but a list of .. :
plot(dend2$lower[[3]], nodePar=list(col=4), horiz = TRUE, type = "tr")
## "inner" and "leaf" edges in different type & color :
plot(dend2$lower[[2]], nodePar=list(col=1),# non empty list
     edgePar = list(lty=1:2, col=2:1), edge.root=TRUE)
par(op)
}
\keyword{multivariate}
\keyword{tree}% FIXME: want as.dendrogram.tree() etc!
\keyword{hplot}% only for plot.()
\eof
\name{dist}
\title{Distance Matrix Computation}
\usage{
dist(x, method = "euclidean", diag = FALSE, upper = FALSE)

as.dist(m, diag = FALSE, upper = FALSE)

\method{print}{dist}(x, diag = NULL, upper = NULL, \dots)

\method{as.matrix}{dist}(x)
}
\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 numeric matrix, data frame or \code{"dist"} object.}
  \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}{logical value indicating whether the diagonal of the
    distance matrix should be printed by \code{print.dist}.}
  \item{upper}{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 \sQuote{on}
      and zero elements are \sQuote{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.
  Further, when \code{Inf} values are involved, all pairs of values are
  excluded when their contribution to the distance gave \code{NaN} or
  \code{NA}.\cr
  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
  vector, say \code{do}. If \code{n} is the number of
  observations, i.e., \code{n <- attr(do, "Size")}, then
  for \eqn{i < j <= n}, the dissimilarity between (row) i and j is
  \code{do[n*(i-1) - i*(i-1)/2 + j-i]}.
  The length of the vector is \eqn{n*(n-1)/2}, i.e., of order \eqn{n^2}.

  The object has the following attributes (besides \code{"class"} equal
  to \code{"dist"}):
  \item{Size}{integer, the number of observations in the dataset.}
  \item{Labels}{optionally, contains the labels, if any, of the
    observations of the dataset.}
  \item{Diag, Upper}{logicals corresponding to the arguments \code{diag}
    and \code{upper} above, specifying how the object should be printed.}
  \item{call}{optionally, the \code{\link{call}} used to create the
    object.}
  \item{methods}{optionally, the distance method used; resulting form
    \code{\link{dist}()}, the (\code{\link{match.arg}()}ed) \code{method}
    argument.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Mardia, K. V., Kent, J. T. and Bibby, J. M. (1979)
  \emph{Multivariate Analysis.} London: Academic Press.
}
\seealso{
  \code{\link[cluster]{daisy}} in the \pkg{cluster} package with more
  possibilities in the case of \emph{mixed} (contiuous / categorical)
  variables.
  \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)

## Examples involving "Inf" :

## 1)
x[6] <- Inf
(m2 <- rbind(x,y))
dist(m2, method="binary")# warning, answer 0.5 = 2/4
## These all give "Inf":
stopifnot(Inf == dist(m2, method= "euclidean"),
          Inf == dist(m2, method= "maximum"),
          Inf == dist(m2, method= "manhattan"))
##  "Inf" is same as very large number:
x1 <- x; x1[6] <- 1e100
stopifnot(dist(cbind(x ,y), method="canberra") ==
    print(dist(cbind(x1,y), method="canberra")))

## 2)
y[6] <- Inf #-> 6-th pair is excluded
dist(rbind(x,y), method="binary")# warning; 0.5
dist(rbind(x,y), method="canberra")#  3
dist(rbind(x,y), method="maximum")  # 1
dist(rbind(x,y), method="manhattan")# 2.4
}
\keyword{multivariate}
\keyword{cluster}
\eof
\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, \dots)
}
\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.}
  \item{STATISTIC, PVAL}{The significance-test statistic and P value, if
    if can be computed.}
}

\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.
}

\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}
\eof
\name{hclust}
\title{Hierarchical Clustering}
\alias{hclust}
\alias{plot.hclust}
\alias{plclust}
\alias{print.hclust}
\description{
  Hierarchical cluster analysis on a set of dissimilarities and
  methods for analyzing it.
}
\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)

plclust(tree, hang = 0.1, unit = FALSE, level = FALSE, hmin = 0,
        square = TRUE, labels = NULL, plot. = TRUE,
        axes = TRUE, frame.plot = FALSE, ann = TRUE,
        main = "", sub = NULL, xlab = NULL, ylab = "Height")
}
\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}. See the Details section.}

  \item{x,tree}{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.}

  \item{unit}{logical.  If true, the splits are plotted at
    equally-spaced heights rather than at the height in the object.}

  \item{hmin}{numeric.  All heights less than \code{hmin} are regarded
    as being \code{hmin}: this can be used to suppress detail at the
    bottom of the tree.}
  \item{level, square, plot.}{as yet unimplemented arguments of
    \code{plclust} for S-PLUS compatibility.}
}
\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).}

  There is a \code{\link{print}} and a \code{\link{plot}} method for
  \code{hclust} objects.
  The \code{plclust()} function is basically the same as the plot method,
  \code{plot.hclust}, primarily for back compatibility with S-plus. Its
  extra arguments are not yet implemented.
}
\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 \sQuote{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
  \dQuote{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{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole. (S version.)

  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. (1999).
  \emph{Classification}. Second Edition.
  London: Chapman and Hall / CRC

  Murtagh, F. (1985).
  \dQuote{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{cutree}}, \code{\link{dendrogram}}, \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, colMeans(USArrests[memb == k, , drop = FALSE]))
}
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}
\eof
\name{heatmap}
\alias{heatmap}
\title{ Draw a Heat Map }
\description{
  A heat map is a false color image (basically
  \code{\link{image}(t(x))}) with a dendrogram added to the left side
  and to the top.  Typically, reordering of the rows and columns
  according to some set of values (row or column means) within the
  restrictions imposed by the dendrogram is carried out.
}
\usage{
heatmap(x, Rowv=NULL, Colv=if(symm)"Rowv" else NULL,
	distfun = dist, hclustfun = hclust, add.expr,
	symm = FALSE, revC = identical(Colv, "Rowv"),
	scale=c("row", "column", "none"), na.rm = TRUE,
	margins = c(5, 5), ColSideColors, RowSideColors,
	cexRow = 0.2 + 1/log10(nr), cexCol = 0.2 + 1/log10(nc),
	labRow = NULL, labCol = NULL, main = NULL, xlab = NULL, ylab = NULL,
	\dots)
}
\arguments{
  \item{x}{numeric matrix of the values to be plotted. }
  \item{Rowv}{determines if and how the \emph{row} dendrogram should be
    reordered.	Either a \code{\link{dendrogram}} or a vector of values
    used to reorder the row dendrogram or \code{\link{FALSE}} to
    suppress reordering or by default, \code{\link{NULL}}, see
    \emph{Details} below.}
  \item{Colv}{determines if and how the \emph{column} dendrogram should be
    reordered.	Has the options as the \code{Rowv} argument above and
    \emph{additionally} when \code{x} is a square matrix, \code{Colv =
      "Rowv"} means that columns should be treated identically to the rows.}
  \item{distfun}{function used to compute the distance (dissimilarity)
    between both rows and columns.  Defaults to \code{\link{dist}}.}
  \item{hclustfun}{function used to compute the hierarchical clustering
    when \code{Rowv} or \code{Colv} are not dendrograms.  Defaults to
    \code{\link{hclust}}.}
  \item{add.expr}{expression that will be evaluated after the call to
    \code{image}.  Can be used to add components to the plot.}
  \item{symm}{logical indicating if \code{x} should be treated
    \bold{symm}etrically; can only be true when \code{x} is a square matrix.}
  \item{revC}{logical indicating if the column order should be
    \code{\link{rev}}ersed for plotting, such that e.g., for the
    symmetric case, the symmetry axis is as usual.}
  \item{scale}{character indicating if the values should be centered and
    scaled in either the row direction or the column direction, or
    none.  The default is \code{"row"} if \code{symm} false, and
    \code{"none"} otherwise.}
  \item{na.rm}{logical indicating whether \code{NA}'s should be removed.}
  \item{margins}{numeric vector of length 2 containing the margins
    (see \code{\link{par}(mar= *)}) for column and row names, respectively.}
  \item{ColSideColors}{(optional) character vector of length \code{ncol(x)}
    containing the color names for a horizontal side bar that may be used to
    annotate the columns of \code{x}.}
  \item{RowSideColors}{(optional) character vector of length \code{nrow(x)}
    containing the color names for a vertical side bar that may be used to
    annotate the rows of \code{x}.}
  \item{cexRow, cexCol}{positive numbers, used as \code{cex.axis} in
    for the row or column axis labeling.  The defaults currently only
    use number of rows or columns, respectively.}
  \item{labRow, labCol}{character vectors with row and column labels to
    use; these default to \code{rownames(x)} or \code{colnames(x)},
    respectively.}
  \item{main, xlab, ylab}{main, x- and y-axis titles; defaults to none.}
  \item{\dots}{additional arguments passed on to \code{\link{image}},
    e.g., \code{col} specifying the colors.} %
}
\details{
  If either \code{Rowv} or \code{Colv} are dendrograms they are honored
  (and not reordered).	Otherwise, dendrograms are computed as
  \code{dd <- as.dendrogram(hclustfun(distfun(X)))} where \code{X} is
  either \code{x} or \code{t(x)}.\cr

  If either is a vector (of \dQuote{weights}) then the appropriate
  dendrogram is reordered according to the supplied values subject to
  the constraints imposed by the dendrogram, by \code{\link{reorder}(dd,
    Rowv)}, in the row case.
  %%
  If either is missing, as by default, then the ordering of the
  corresponding dendrogram is by the mean value of the rows/columns,
  i.e., in the case of rows, \code{Rowv <- rowMeans(x, na.rm=na.rm)}.
  %%
  If either is \code{\link{NULL}}, \emph{no reordering} will be done for
  the corresponding side.

  By default (\code{scale = "row"}) the rows are scaled to have mean
  zero and standard deviation one.  There is some empirical evidence
  from genomic plotting that this is useful.

  The default colors are not pretty.  Consider using enhancements such
  as the \pkg{RColorBrewer} package,
  \url{http://cran.r-project.org/src/contrib/PACKAGES.html#RColorBrewer}.
}
\note{
  The original rows and columns are reordered \emph{in any case} to
  match the dendrogram, e.g., the rows by
  \code{\link{order.dendrogram}(Rowv)} where \code{Rowv} is the
  (possibly \code{\link{reorder}()}ed) row dendrogram.

  \code{heatmap()} uses \code{\link{layout}} and draws the
  \code{\link{image}} in the lower right corner of a 2x2 layout.
  Consequentially, it can \bold{not} be used in a multi column/row
  layout, i.e., when \code{\link{par}(mfrow= *)} or \code{(mfcol= *)}
  has been called.
}
\value{
  Invisibly, a list with components
  \item{rowInd}{\bold{r}ow index permutation vector as returned by
    \code{\link{order.dendrogram}}.}
  \item{colInd}{\bold{c}olumn index permutation vector.}
}
\author{Andy Liaw, original; R. Gentleman, M. Maechler, W. Huber, revisions.}

\seealso{\code{\link{image}}, \code{\link{hclust}}}

\examples{
 data(mtcars)
 x  <- as.matrix(mtcars)
 rc <- rainbow(nrow(x), start=0, end=.3)
 cc <- rainbow(ncol(x), start=0, end=.3)
 hv <- heatmap(x, col = cm.colors(256), scale="column",
	       RowSideColors = rc, ColSideColors = cc, margin=c(5,10),
	       xlab = "specification variables", ylab= "Car Models",
	       main = "heatmap(<Mtcars data>, ..., scale = \"column\")")
 str(hv) # the two re-ordering index vectors

%% want example using the `add.exp' argument!

 data(attitude)
 round(Ca <- cor(attitude), 2)
 symnum(Ca) # simple graphic
 heatmap(Ca,		 symm = TRUE, margin=c(6,6))# with reorder()
 heatmap(Ca, Rowv=FALSE, symm = TRUE, margin=c(6,6))# _NO_ reorder()

 ## For variable clustering, rather use distance based on cor():
 data(USJudgeRatings)
 symnum( cU <- cor(USJudgeRatings) )

 hU <- heatmap(cU, Rowv = FALSE, symm = TRUE, col = topo.colors(16),
              distfun = function(c) as.dist(1 - c))
 ## The Correlation matrix with same reordering:
 round(100 * cU[hU[[1]], hU[[2]]])
}
\keyword{hplot}
\eof
\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 made 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.  The 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, see also \code{\link{identify}}.
}
\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{
%-- in the future -- when example() will
%   show comments, and always have a pager and ... :
% ## Open a default device; if it's an interactive one, continue example:
% get(devNam <- getOption("device"))()
% if (dev.interactive()) {
\dontrun{
  library(mva)
  data(USArrests)
  hca <- hclust(dist(USArrests))
  plot(hca)
  (x <- identify(hca)) ##  Terminate with 2nd mouse button !!

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

  # open a new device (one for dendrogram, one for bars):
  get(getOption("device"))()# << make that narrow (& small) and *beside* 1st one
  nD <- dev.cur()           # to be for the barplot
  dev.set(dev.prev())# old one for dendrogram
  plot(hci)
  ## select subtrees in dendrogram and "see" the species distribution:
  identify.(hci, function(k) barplot(table(iris[k,5]),col=2:4), DEV.FUN = nD)
}
% dev.off()
}
\keyword{cluster}
\keyword{iplot}
\eof
\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}
\eof
\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)

\method{print}{loadings}(x, digits = 3, cutoff = 0.1, sort = FALSE, \dots)

\method{print}{factanal}(x, digits = 3, \dots)
}
\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}.}
}

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

\keyword{multivariate}
\keyword{print}
\eof
\name{order.dendrogram}
\alias{order.dendrogram}
\title{ Get the ordering of the leaves in a dendrogram }
\description{
  This function returns the order (index) for the leaves in a
  dendrogram. These indices can then be used to access the appropriate
  components of any additional data.
}
\usage{
order.dendrogram(x)
}
\arguments{
  \item{x}{A dendrogram. }
}
\details{
  The indices for the leaves in left to right order are retrieved.
}
\value{
  A vector with length equal to the number of leaves in the dendrogram
  is returned. Each element is the index into the original data (from
  which the dendrogram was computed)
}
\author{R. Gentleman}

\seealso{\code{\link{reorder}} }

\examples{
  set.seed(123)
  x<-rnorm(10)
  hc <- hclust(dist(x))
  hc$order
  dd <- as.dendrogram(hc)
  order.dendrogram(dd)
}
\keyword{manip }
\eof
\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 numeric or complex 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.

  If the input has more variables than units then \code{\link{La.svd}}
  is used, and the results may differ in sign from versions prior to 1.7.0.
}
\note{
  The signs of the columns of the rotation matrix are arbitrary, and
  so may differ between different programs for PCA, and even between
  different builds of \R.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  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}
\eof
\name{princomp}
\alias{princomp}
\alias{princomp.formula}
\alias{princomp.default}
\alias{plot.princomp}
\alias{print.princomp}
\alias{predict.princomp}
\title{Principal Components Analysis}
\usage{
princomp(x, \dots)

\method{princomp}{formula}(formula, data = NULL, subset, na.action, \dots)

\method{princomp}{default}(x, cor = FALSE, scores = TRUE, covmat = NULL,
         subset = rep(TRUE, nrow(as.matrix(x))), \dots)
}
\arguments{
  \item{formula}{a formula with no response variable.}
  \item{data}{an optional data frame containing the variables in the
    formula \code{formula}. By default the variables are taken from
    \code{environment(formula)}.}
  \item{x}{a matrix or data frame which provides the data for the
    principal components analysis.}
  \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 \dQuote{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
  numeric 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 \code{\link{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}}.

  \code{princomp} only handles so-called Q-mode PCA, that is feature
  extraction of variables. If a data matrix is supplied (possibly via a
  formula) it is required that there are at least as many units as
  variables.  For R-mode PCA use \code{\link{prcomp}}.
}
\note{
  The signs of the columns of the loadings and scores are arbitrary, and
  so may differ between different programs for PCA, and even between
  different builds of \R.
}
\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 (2002).
  \emph{Modern Applied Statistics with S}, 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(~ Murder + Assault + UrbanPop,
                  data = USArrests, na.action=na.exclude, cor = TRUE)
pc.cr$scores
}
\keyword{multivariate}
\eof
\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}
\eof
\name{reorder}
\alias{reorder}
\alias{reorder.dendrogram}
\title{ Reorder a dendrogram }
\description{
  There are many different orderings of a dendrogram that are consistent
  with the structure imposed.  This function takes a dendrogram and a
  vector of values and reorders the dendrogram in the order of the
  supplied vector, maintaining the constraints on the dendrogram.
}
\usage{
reorder(x, \dots)

\method{reorder}{dendrogram}(x, wts, \dots)
}
\arguments{
  \item{x}{The object to be reordered}
  \item{wts}{The weights for reordering.}
  \item{\dots}{additional arguments }
}
\details{
  Using the weights the leaves of the dendrogram are reordered so as to
  be in an order as consistent as possible with the weights.
}
\value{
  From \code{reorder.dendrogram} a dendrogram.
}
\author{R. Gentleman}
\seealso{\code{\link{heatmap}}, \code{\link{cophenetic}} }

\examples{
  set.seed(123)
  x <- rnorm(10)
  hc <- hclust(dist(x))
  dd <- as.dendrogram(hc)
  dd.reorder <- reorder(dd, 10:1)

  op <- par(mfcol = 1:2)
  plot(dd, main = "random dendrogram `dd'")
  plot(dd.reorder, main = "reorder(dd, 10:1)")
  par(op)
}
\keyword{manip}
\eof
\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 (2002).
  \emph{Modern Applied Statistics with S}, 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}
\eof
\name{summary.princomp}
\alias{summary.princomp}
\alias{print.summary.princomp}
\title{Summary method for Principal Components Analysis}
\usage{
\method{summary}{princomp}(object, loadings = FALSE, cutoff = 0.1, \dots)

\method{print}{summary.princomp}(x, digits = 3, loadings = x$print.loadings,
      cutoff = x$cutoff, \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{x}{an object of class "summary.princomp".}
  \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} with additional components \code{cutoff} and
  \code{print.loadings}.
}
\seealso{
  \code{\link{princomp}}
}
\examples{
data(USArrests)
summary(pc.cr <- princomp(USArrests, cor=TRUE))
print(summary(princomp(USArrests, cor=TRUE),
              loadings = TRUE, cutoff = 0.2), digits = 2)
}
\keyword{multivariate}
\eof
\name{varimax}
\alias{promax}
\alias{varimax}
\title{Rotation Methods for Factor Analysis}
\description{
  These functions \sQuote{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 \sQuote{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 \sQuote{rotated} loadings matrix,
    \code{x \%*\% rotmat}.}
  \item{rotmat}{The \sQuote{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.
}
\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}
\eof
