%% From package:nlme  AIC.Rd,v 1.4 2000/07/03 18:22:45 bates
%% with additional "k = 2" argument (MM)
\name{AIC}
\alias{AIC}
\alias{AIC.default}
\alias{AIC.logLik}
\title{Akaike's An Information Criterion}
\description{
  Generic function calculating the Akaike information criterion for
  one or several fitted model objects for which a log-likelihood value
  can be obtained, according to the formula
  \eqn{-2 \mbox{log-likelihood} + k n_{par}}{-2*log-likelihood + k*npar},
  where \eqn{n_{par}}{npar} represents the number of parameters in the
  fitted model, and \eqn{k = 2} for the usual AIC, or \eqn{k = \log(n)}
  (\eqn{n} the number of observations) for the so-called BIC or SBC
  (Schwarz's Bayesian criterion).
}
\usage{
AIC(object, \dots, k = 2)
}
\arguments{
  \item{object}{a fitted model object, for which there exists a
    \code{logLik} method to extract the corresponding log-likelihood, or
    an object inheriting from class \code{logLik}.}
  \item{\dots}{optionally more fitted model objects.}
  \item{k}{numeric, the \dQuote{penalty} per parameter to be used; the
    default \code{k = 2} is the classical AIC.}
}
\details{
  The default method for \code{AIC}, \code{AIC.default()} entirely
  relies on the existence of a \code{\link{logLik}} method
  computing the log-likelihood for the given class.

  When comparing fitted objects, the smaller the AIC, the better the fit.
}
\value{
  If just one object is provided, returns a numeric value
  with the corresponding AIC (or BIC, or \dots, depending on \code{k});
  if more than one object are provided, returns a \code{data.frame} with
  rows corresponding to the objects and columns representing the number
  of parameters in the model (\code{df}) and the AIC.
}
\references{
  Sakamoto, Y., Ishiguro, M., and Kitagawa G. (1986).
  \emph{Akaike Information Criterion Statistics}.
  D. Reidel Publishing Company.
}
\author{Jose Pinheiro and Douglas Bates}
\seealso{
  \code{\link{extractAIC}}, \code{\link{logLik}}.
}
\examples{
data(swiss)
lm1 <- lm(Fertility ~ . , data = swiss)
AIC(lm1)
stopifnot(all.equal(AIC(lm1),
                    AIC(logLik(lm1))))
## a version of BIC or Schwarz' BC :
AIC(lm1, k = log(nrow(swiss)))
}
\keyword{models}
\eof
\name{Arithmetic}
\title{Arithmetic Operators}
\usage{
x + y
x - y
x * y
x / y
x ^ y
x \%\% y
x \%/\% y
}
\alias{+}
\alias{-}
\alias{*}
\alias{/}
\alias{^}
\alias{\%\%}
\alias{\%/\%}
\alias{Arithmetic}
\description{
These binary operators perform arithmetic on vector objects.
}
\value{
They return numeric vectors containing the result of the element
by element operations.  The elements of shorter vectors are recycled
as necessary (with a \code{\link{warning}} when they are recycled only
\emph{fractionally}).  The operators are \code{+} for addition,
\code{-} for subtraction \code{*} for multiplication, \code{/} for
division and \code{^} for exponentiation.

\code{\%\%} indicates \code{x mod y} and \code{\%/\%} indicates integer
division.  It is guaranteed that \code{x  ==  (x \%\% y)  +  y * ( x \%/\% y )}
unless \code{y == 0} where the result is \code{\link{NA}} or
\code{\link{NaN}} (depending on the \code{\link{typeof}} of the arguments).
}
\details{
    \code{1 ^ y} and \code{y ^ 0} are \code{1}, \emph{always}.
    \code{x ^ y} should also give the proper \dQuote{limit} result when
    either argument is infinite (i.e., \code{+- \link{Inf}}).

    Objects such as arrays or time-series can be operated on this
    way provided they are conformable.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{sqrt}} for miscellaneous and \code{\link{Special}} for special
  mathematical functions.

  \code{\link{Syntax}} for operator precedence.
}
\examples{
x <- -1:12
x + 1
2 * x + 3
x \%\% 2 #-- is periodic
x \%/\% 5
}
\keyword{arith}
\eof
\name{AsIs}
\alias{I}
\alias{AsIs}
\alias{print.AsIs}
\alias{[.AsIs}
\title{Inhibit Interpretation/Conversion of Objects}
\description{
  Change the class of an object to indicate that it should be treated
  \dQuote{as is}.
}
\usage{
I(x)
}
\arguments{
  \item{x}{an object}
}
\details{
  Function \code{I} has two main uses.
  \itemize{
    \item In function \code{\link{data.frame}}.  Protecting an object by
    enclosing it in \code{I()} in a call to data.frame inhibits the
    conversion of character vectors to factors.  \code{I} can also be
    used to protect objects which are to be added to a data frame, or
    converted to a data frame \emph{via} \code{\link{as.data.frame}}.

    It achieves this by prepending the class \code{"AsIs"} to the object's
    classes.  Class \code{"AsIs"} has a few of its own methods, including
    for \code{[}, \code{as.data.frame}, \code{print} and \code{format}.

    \item In function \code{\link{formula}}.  There it is used to
    inhibit the interpretation of  operators such as \code{"+"},
    \code{"-"}, \code{"*"} and \code{"^"} as formula operators, so they
    are used as arithmetical operators.  This is interpreted as a symbol
    by \code{terms.formula}.
  }
}
\value{
  A copy of the object with class \code{"AsIs"} prepended to the class(es).
}
\references{
  Chambers, J. M. (1992)
  \emph{Linear models.}
  Chapter 4 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{data.frame}}, \code{\link{formula}}
}
\keyword{models}
\eof
\name{Bessel}
\title{Bessel Functions}
\alias{bessel}
\alias{Bessel}
\alias{besselI}
\alias{besselJ}
\alias{besselK}
\alias{besselY}
\alias{gammaCody}
\usage{
besselI(x, nu, expon.scaled = FALSE)
besselK(x, nu, expon.scaled = FALSE)
besselJ(x, nu)
besselY(x, nu)
gammaCody(x)
}
\description{
  Bessel Functions of integer and fractional order, of first
  and second kind, \eqn{J_{\nu}}{J(nu)} and \eqn{Y_{\nu}}{Y(nu)}, and
  Modified Bessel functions (of first and third kind),
  \eqn{I_{\nu}}{I(nu)} and \eqn{K_{\nu}}{K(nu)}. 

  \code{gammaCody} is the \eqn{(\Gamma)} function as from the Specfun
  package and originally used in the Bessel code.
}
\arguments{
  \item{x}{numeric, \eqn{\ge 0}{>= 0}.}

  \item{nu}{numeric; The \emph{order} (maybe fractional!) of the
    corresponding Bessel function.}

  \item{expon.scaled}{logical; if \code{TRUE}, the results are
    exponentially scaled in order to avoid overflow
    (\eqn{I_{\nu}}{I(nu)}) or underflow (\eqn{K_{\nu}}{K(nu)}),
    respectively.}
}
\value{
  Numeric vector of the same length of \code{x} with the (scaled, if
  \code{expon.scale=TRUE}) values of the corresponding Bessel function.
}
\details{
  The underlying C code stems from \emph{Netlib}
  (\url{http://www.netlib.org/specfun/r[ijky]besl}).

  If \code{expon.scaled = TRUE}, \eqn{e^{-x} I_{\nu}(x)}{exp(-x) I(x;nu)},
  or \eqn{e^{x} K_{\nu}(x)}{exp(x) K(x;nu)} are returned.

  \code{gammaCody} may be somewhat faster but less precise and/or robust
  than \R's standard \code{\link{gamma}}.  It is here for experimental
  purpose mainly, and \emph{may be defunct very soon}.

  For \eqn{\nu < 0}{nu < 0}, formulae 9.1.2 and 9.6.2 from the
  reference below are applied (which is probably suboptimal), unless for
  \code{besselK} which is symmetric in \code{nu}.  
}
\references{
  Abramowitz, M. and Stegun, I. A. (1972)
  \emph{Handbook of Mathematical Functions.} Dover, New York;
  Chapter 9: Bessel Functions of Integer Order.
}
\seealso{
  Other special mathematical functions, as the
  \code{\link{gamma}}, \eqn{\Gamma(x)}, and \code{\link{beta}},
  \eqn{B(x)}.
}
\author{
  Original Fortran code:
  W. J. Cody, Argonne National Laboratory \cr
  Translation to C and adaption to \R:
  Martin Maechler \email{maechler@stat.math.ethz.ch.}
}
\examples{
nus <- c(0:5,10,20)

x <- seq(0,4, len= 501)
plot(x,x, ylim = c(0,6), ylab="",type='n', main = "Bessel Functions  I_nu(x)")
for(nu in nus) lines(x,besselI(x,nu=nu), col = nu+2)
legend(0,6, leg=paste("nu=",nus), col = nus+2, lwd=1)

x <- seq(0,40,len=801); yl <- c(-.8,.8)
plot(x,x, ylim = yl, ylab="",type='n', main = "Bessel Functions  J_nu(x)")
for(nu in nus) lines(x,besselJ(x,nu=nu), col = nu+2)
legend(32,-.18, leg=paste("nu=",nus), col = nus+2, lwd=1)

## Negative nu's :
xx <- 2:7
nu <- seq(-10,9, len = 2001)
op <- par(lab = c(16,5,7))
matplot(nu, t(outer(xx,nu, besselI)), type = 'l', ylim = c(-50,200),
        main = expression(paste("Bessel ",I[nu](x)," for fixed ", x,
                                ",  as ",f(nu))),
        xlab = expression(nu))
abline(v=0, col = "light gray", lty = 3)
legend(5,200, leg = paste("x=",xx), col=seq(xx), lty=seq(xx))
par(op)

x0 <- 2^(-20:10)
plot(x0,x0^-8, log='xy', ylab="",type='n',
     main = "Bessel Functions  J_nu(x)  near 0\n log - log  scale")
for(nu in sort(c(nus,nus+.5))) lines(x0,besselJ(x0,nu=nu), col = nu+2)
legend(3,1e50, leg=paste("nu=", paste(nus,nus+.5, sep=",")), col=nus+2, lwd=1)

plot(x0,x0^-8, log='xy', ylab="",type='n',
     main = "Bessel Functions  K_nu(x)  near 0\n log - log  scale")
for(nu in sort(c(nus,nus+.5))) lines(x0,besselK(x0,nu=nu), col = nu+2)
legend(3,1e50, leg=paste("nu=", paste(nus,nus+.5, sep=",")), col=nus+2, lwd=1)

x <- x[x > 0]
plot(x,x, ylim=c(1e-18,1e11),log="y", ylab="",type='n',
     main = "Bessel Functions  K_nu(x)")
for(nu in nus) lines(x,besselK(x,nu=nu), col = nu+2)
legend(0,1e-5, leg=paste("nu=",nus), col = nus+2, lwd=1)

yl <- c(-1.6, .6)
plot(x,x, ylim = yl, ylab="",type='n', main = "Bessel Functions  Y_nu(x)")
for(nu in nus){xx <- x[x > .6*nu]; lines(xx,besselY(xx,nu=nu), col = nu+2)}
legend(25,-.5, leg=paste("nu=",nus), col = nus+2, lwd=1)
}
\keyword{math}

\eof
\name{Beta}
\alias{Beta}
\alias{dbeta}
\alias{pbeta}
\alias{qbeta}
\alias{rbeta}
\title{The Beta Distribution}
\description{
  Density, distribution function, quantile function and random
  generation for the Beta distribution with parameters \code{shape1} and
  \code{shape2} (and optional non-centrality parameter \code{ncp}).
}
\usage{
dbeta(x, shape1, shape2, ncp=0, log = FALSE)
pbeta(q, shape1, shape2, ncp=0, lower.tail = TRUE, log.p = FALSE)
qbeta(p, shape1, shape2,        lower.tail = TRUE, log.p = FALSE)
rbeta(n, shape1, shape2)
}
\arguments{
  \item{x, q}{vector of quantiles.}
  \item{p}{vector of probabilities.}
  \item{n}{number of observations. If \code{length(n) > 1}, the length
    is taken to be the number required.}
  \item{shape1, shape2}{positive parameters of the Beta distribution.}
  \item{ncp}{non-centrality parameter.}
  \item{log, log.p}{logical; if TRUE, probabilities p are given as log(p).}
  \item{lower.tail}{logical; if TRUE (default), probabilities are
    \eqn{P[X \le x]}{P[X <= x]}, otherwise, \eqn{P[X > x]}{P[X > x]}.}
}
\value{
  \code{dbeta} gives the density, \code{pbeta} the distribution
  function, \code{qbeta} the quantile function, and \code{rbeta}
  generates random deviates.
}
\details{
  The Beta distribution with parameters \code{shape1} \eqn{= a} and
  \code{shape2} \eqn{= b} has density
  \deqn{f(x)=\frac{\Gamma(a+b)}{\Gamma(a)\Gamma(b)}{x}^{a} {(1-x)}^{b}%
  }{Gamma(a+b)/(Gamma(a)Gamma(b))x^(a-1)(1-x)^(b-1)}
  for \eqn{a > 0}, \eqn{b > 0} and \eqn{0 < x < 1}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{beta}} for the Beta function, and \code{\link{dgamma}} for
  the Gamma distribution.
}
\examples{
x <- seq(0, 1, length=21)
dbeta(x, 1, 1)
pbeta(x, 1, 1)
}
\keyword{distribution}
\eof
\name{Binomial}
\alias{Binomial}
\alias{dbinom}
\alias{pbinom}
\alias{qbinom}
\alias{rbinom}
\title{The Binomial Distribution}
\description{
  Density, distribution function, quantile function and random
  generation for the binomial distribution with parameters \code{size}
  and \code{prob}.
}
\usage{
dbinom(x, size, prob, log = FALSE)
pbinom(q, size, prob, lower.tail = TRUE, log.p = FALSE)
qbinom(p, size, prob, lower.tail = TRUE, log.p = FALSE)
rbinom(n, size, prob)
}
\arguments{
  \item{x, q}{vector of quantiles.}
  \item{p}{vector of probabilities.}
  \item{n}{number of observations. If \code{length(n) > 1}, the length
    is taken to be the number required.}
  \item{size}{number of trials.}
  \item{prob}{probability of success on each trial.}
  \item{log, log.p}{logical; if TRUE, probabilities p are given as log(p).}
  \item{lower.tail}{logical; if TRUE (default), probabilities are
    \eqn{P[X \le x]}{P[X <= x]}, otherwise, \eqn{P[X > x]}{P[X > x]}.}
}
\value{
  \code{dbinom} gives the density, \code{pbinom} gives the distribution
  function, \code{qbinom} gives the quantile function and \code{rbinom}
  generates random deviates.

  If \code{size} is not an integer, \code{NaN} is returned.
}
\details{
  The binomial distribution with \code{size} \eqn{= n} and
  \code{prob} \eqn{= p} has density
  \deqn{p(x) = {n \choose x} {p}^{x} {(1-p)}^{n-x}}{
    p(x) = choose(n,x) p^x (1-p)^(n-x)}
  for \eqn{x = 0, \ldots, n}.

  If an element of \code{x} is not integer, the result of \code{dbinom}
  is zero, with a warning.
  \eqn{p(x)} is computed using Loader's algorithm, see the reference below.

  The quantile is defined as the smallest value \eqn{x} such that
  \eqn{F(x) \ge p}, where \eqn{F} is the distribution function.
}
\seealso{
  \code{\link{dnbinom}} for the negative binomial, and
  \code{\link{dpois}} for the Poisson distribution.
}
\references{
  Catherine Loader (2000). \emph{Fast and Accurate Computation of
    Binomial Probabilities}; manuscript available from
  \url{http://cm.bell-labs.com/cm/ms/departments/sia/catherine/dbinom}
}
\examples{
# Compute P(45 < X < 55) for X Binomial(100,0.5)
sum(dbinom(46:54, 100, 0.5))

## Using "log = TRUE" for an extended range :
n <- 2000
k <- seq(0, n, by = 20)
plot (k, dbinom(k, n, pi/10, log=TRUE), type='l', ylab="log density",
      main = "dbinom(*, log=TRUE) is better than  log(dbinom(*))")
lines(k, log(dbinom(k, n, pi/10)), col='red', lwd=2)
## extreme points are omitted since dbinom gives 0.
mtext("dbinom(k, log=TRUE)", adj=0)
mtext("extended range", adj=0, line = -1, font=4)
mtext("log(dbinom(k))", col="red", adj=1)
}
\keyword{distribution}
\eof
\name{Cauchy}
\alias{Cauchy}
\alias{dcauchy}
\alias{pcauchy}
\alias{qcauchy}
\alias{rcauchy}
\title{The Cauchy Distribution}
\description{
  Density, distribution function, quantile function and random
  generation for the Cauchy distribution with location parameter
  \code{location} and scale parameter \code{scale}.
}
\usage{
dcauchy(x, location = 0, scale = 1, log = FALSE)
pcauchy(q, location = 0, scale = 1, lower.tail = TRUE, log.p = FALSE)
qcauchy(p, location = 0, scale = 1, lower.tail = TRUE, log.p = FALSE)
rcauchy(n, location = 0, scale = 1)
}
\arguments{
  \item{x, q}{vector of quantiles.}
  \item{p}{vector of probabilities.}
  \item{n}{number of observations. If \code{length(n) > 1}, the length
    is taken to be the number required.}
  \item{location, scale}{location and scale parameters.}
  \item{log, log.p}{logical; if TRUE, probabilities p are given as log(p).}
  \item{lower.tail}{logical; if TRUE (default), probabilities are
    \eqn{P[X \le x]}{P[X <= x]}, otherwise, \eqn{P[X > x]}{P[X > x]}.}
}
\value{
  \code{dcauchy}, \code{pcauchy}, and \code{qcauchy} are respectively
  the density, distribution function and quantile function of the Cauchy
  distribution.  \code{rcauchy} generates random deviates from the
  Cauchy.
}
\details{
  If \code{location} or \code{scale} are not specified, they assume
  the default values of \code{0} and \code{1} respectively.

  The Cauchy distribution with location \eqn{l} and scale \eqn{s} has
  density
  \deqn{f(x) = \frac{1}{\pi s}
    \left( 1 + \left(\frac{x - l}{s}\right)^2 \right)^{-1}%
  }{f(x) = 1 / (pi s (1 + ((x-l)/s)^2))}
  for all \eqn{x}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{dt}} for the t distribution which generalizes
  \code{dcauchy(*, l = 0, s = 1)}.
}
\examples{
dcauchy(-1:4)
}
\keyword{distribution}
\eof
\name{Chisquare}
\alias{Chisquare}
\alias{dchisq}
\alias{pchisq}
\alias{qchisq}
\alias{rchisq}
\title{The (non-central) Chi-Squared Distribution}
\description{
  Density, distribution function, quantile function and random
  generation for the chi-squared (\eqn{\chi^2}{chi^2}) distribution with
  \code{df} degrees of freedom and optional non-centrality parameter
  \code{ncp}.
}
\usage{
dchisq(x, df, ncp=0, log = FALSE)
pchisq(q, df, ncp=0, lower.tail = TRUE, log.p = FALSE)
qchisq(p, df, ncp=0, lower.tail = TRUE, log.p = FALSE)
rchisq(n, df, ncp=0)
}
\arguments{
  \item{x, q}{vector of quantiles.}
  \item{p}{vector of probabilities.}
  \item{n}{number of observations. If \code{length(n) > 1}, the length
    is taken to be the number required.}
  \item{df}{degrees of freedom (non-negative, but can be non-integer).}
  \item{ncp}{non-centrality parameter (non-negative).  Note that
    \code{ncp} values larger than about 1417 are not allowed currently
    for \code{pchisq} and \code{qchisq}.}
  \item{log, log.p}{logical; if TRUE, probabilities p are given as log(p).}
  \item{lower.tail}{logical; if TRUE (default), probabilities are
    \eqn{P[X \le x]}{P[X <= x]}, otherwise, \eqn{P[X > x]}{P[X > x]}.}
}
\value{
  \code{dchisq} gives the density, \code{pchisq} gives the distribution
  function, \code{qchisq} gives the quantile function, and \code{rchisq}
  generates random deviates.
}
\details{
  The chi-squared distribution with \code{df}\eqn{= n} degrees of
  freedom has density
  \deqn{f_n(x) = \frac{1}{{2}^{n/2} \Gamma (n/2)} {x}^{n/2-1} {e}^{-x/2}}{%
    f_n(x) = 1 / (2^(n/2) Gamma(n/2))  x^(n/2-1) e^(-x/2)}
  for \eqn{x > 0}.  The mean and variance are \eqn{n} and \eqn{2n}.

  The non-central chi-squared distribution with \code{df}\eqn{= n}
  degrees of freedom and non-centrality parameter \code{ncp}
  \eqn{= \lambda} has density
  \deqn{
    f(x) = e^{-\lambda / 2}
      \sum_{r=0}^\infty \frac{(\lambda/2)^r}{r!}\, f_{n + 2r}(x)}{%
    f(x) = exp(-lambda/2) SUM_{r=0}^infty ((lambda/2)^r / r!) dchisq(x, df + 2r)
  }
  for \eqn{x \ge 0}.  For integer \eqn{n}, this is the distribution of
  the sum of squares of \eqn{n} normals each with variance one,
  \eqn{\lambda} being the sum of squares of the normal means.
  Note that the degrees of freedom \code{df}\eqn{= n}, can be
  non-integer, and for non-centrality \eqn{\lambda > 0}, even \eqn{n = 0};
  see the reference, chapter 29.

}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Johnson, Kotz and Balakrishnan (1995). \emph{Continuous Univariate
    Distributions}, Vol \bold{2}; Wiley NY;
}
\seealso{
  \code{\link{dgamma}} for the Gamma distribution which generalizes the
  chi-squared one.
}
\examples{
dchisq(1, df=1:3)
pchisq(1, df= 3)
pchisq(1, df= 3, ncp = 0:4)# includes the above

x <- 1:10
## Chi-squared(df = 2) is a special exponential distribution
all.equal(dchisq(x, df=2), dexp(x, 1/2))
all.equal(pchisq(x, df=2), pexp(x, 1/2))

## non-central RNG -- df=0 is ok for ncp > 0:  Z0 has point mass at 0!
Z0 <- rchisq(100, df = 0, ncp = 2.)
stem(Z0)

\dontrun{## visual testing
## do P-P plots for 1000 points at various degrees of freedom
L <- 1.2; n <- 1000; pp <- ppoints(n)
op <- par(mfrow = c(3,3), mar= c(3,3,1,1)+.1, mgp= c(1.5,.6,0),
          oma = c(0,0,3,0))
for(df in 2^(4*rnorm(9))) {
  plot(pp, sort(pchisq(rr <- rchisq(n,df=df, ncp=L), df=df, ncp=L)),
       ylab="pchisq(rchisq(.),.)", pch=".")
  mtext(paste("df = ",formatC(df, digits = 4)), line= -2, adj=0.05)
  abline(0,1,col=2)
}
mtext(expression("P-P plots : Noncentral  "*
                 chi^2 *"(n=1000, df=X, ncp= 1.2)"),
      cex = 1.5, font = 2, outer=TRUE)
par(op)}
}
\keyword{distribution}
\eof
\name{Comparison}
\alias{<}
\alias{<=}
\alias{==}
\alias{!=}
\alias{>=}
\alias{>}
\alias{Comparison}
\title{Relational Operators}
\description{
  Binary operators which allow the comparison of values in vectors.
}
\usage{
x < y
x > y
x <= y
x >= y
x == y
x != y
}
\details{
  Comparison of strings in character vectors is lexicographic within the
  strings using the collating sequence of the locale in use: see
  \code{\link{locales}}.  The collating sequence of locales such as
  \samp{en\_US} is normally different from \samp{C} (which should use
  ASCII) and can be surprising.
}
\value{
  A vector of logicals indicating the result of the element by element
  comparison.  The elements of shorter vectors are recycled as
  necessary.

  Objects such as arrays or time-series can be compared this way
  provided they are conformable.
}
\note{
  Don't use \code{==} and \code{!=} for tests, such as in \code{if}
  expressions, where you must get a single \code{TRUE} or
  \code{FALSE}.  Unless you are absolutely sure that nothing unusual
  can happen, you should use the \code{\link{identical}} function
  instead.

  For numerical values, remember \code{==} and \code{!=} do not allow
  for the finite representation of fractions, nor for rounding error.
  Using \code{\link{all.equal}} with \code{identical} is almost
  always preferable.  See the examples.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{Syntax}} for operator precedence.
}
\examples{
x <- rnorm(20)
x < 1
x[x > 0]

x1 <- 0.5 - 0.3
x2 <- 0.3 - 0.1
x1 == x2                           # FALSE on most machines
identical(all.equal(x1, x2), TRUE) # TRUE everywhere
}
\keyword{logic}
\eof
\name{Constants}
\alias{LETTERS}
\alias{letters}
\alias{month.abb}
\alias{month.name}
\alias{pi}
\title{Built-in Constants}
\description{Constants built into \R.}
\usage{
LETTERS
letters
month.abb
month.name
pi
}
\details{
  \R has a limited number of built-in constants (there is also a rather
  larger library of data sets which can be loaded with the function
  \code{\link{data}}).

  The following constants are available:
  \itemize{
    \item \code{LETTERS}: the 26 upper-case letters of the Roman
    alphabet;
    \item \code{letters}: the 26 lower-case letters of the Roman
    alphabet;
    \item \code{month.abb}: the three-letter abbreviations for the
    English month names;
    \item \code{month.name}: the English names for the months of the
    year;
    \item \code{pi}: the ratio of the circumference of a circle to its
    diameter.
  }
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{data}}.
}
\examples{
# John Machin (1705) computed 100 decimals of pi :
pi - 4*(4*atan(1/5) - atan(1/239))
}
\keyword{sysdata}
\eof
\name{Control}
\alias{Control}
\alias{if}
\alias{else}
\alias{for}
\alias{while}
\alias{repeat}
\alias{break}
\alias{next}
\title{Control Flow}
\usage{
if(cond) expr
if(cond) cons.expr  else  alt.expr
for(var in seq) expr
while(cond) expr
repeat expr
break
next
}
\description{
  These are the basic control-flow constructs of the \R language.  They
  function in much the same way as control statements in any algol-like
  language.
}
\details{
  Note that \code{expr} and \code{cons.expr}, etc, in the Usage section
  above means an \emph{expression} in a formal sense.  This is either a
  simple expression or a so called \emph{compound expression}, usually
  of the form \code{\{ expr1 ; expr2 \}}.

  Note that it is a common mistake to forget putting braces (\code{\{ .. \}})
  around your statements, e.g., after \code{if(..)} or \code{for(....)}.
  For that reason, one (somewhat extreme) attitude of defensive programming
  uses braces always, e.g., for \code{if} clauses.

  The index \code{seq} in a \code{for} loop is evaluated at the start of
  the loop; changing it subsequently does not affect the loop.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{Syntax}} for the basic \R syntax and operators,
  \code{\link{Paren}} for parentheses and braces; further,
  \code{\link{ifelse}}, \code{\link{switch}}.
}
\examples{
for(i in 1:5) print(1:i)
for(n in c(2,5,10,20,50)) {
   x <- rnorm(n)
   cat(n,":", sum(x^2),"\n")
}
}
\keyword{programming}
\keyword{iteration}
\keyword{logic}
\eof
\name{DateTimeClasses}
% implementation mostly in ../R/datetime.R
\alias{DateTimeClasses}
\alias{POSIXct}
\alias{POSIXlt}
\alias{POSIXt}
\alias{print.POSIXct}
\alias{print.POSIXlt}
\alias{summary.POSIXct}
\alias{summary.POSIXlt}
\alias{+.POSIXt}
\alias{-.POSIXt}
\alias{Ops.POSIXt}
\alias{Math.POSIXt}
\alias{Summary.POSIXct}
\alias{Math.POSIXlt}
\alias{Summary.POSIXlt}
\alias{[.POSIXct}
\alias{[<-.POSIXct}
\alias{[[.POSIXct}
\alias{[.POSIXlt}
\alias{[<-.POSIXlt}
\alias{as.data.frame.POSIXct}
\alias{as.data.frame.POSIXlt}
\alias{.leap.seconds}
\alias{is.na.POSIXlt}
\alias{all.equal.POSIXct}
\alias{c.POSIXct}
\alias{c.POSIXlt}
\alias{as.matrix.POSIXlt}
\alias{mean.POSIXct}
\alias{mean.POSIXlt}
\alias{str.POSIXt}

\title{Date-Time Classes}
\description{
  Description of the classes \code{"POSIXlt"} and \code{"POSIXct"}
  representing calendar dates and times (to the nearest second). 
}
\usage{
\method{print}{POSIXct}(x, \dots)

\method{summary}{POSIXct}(object, digits = 15, \dots)

time + number
time - number
time1 lop time2
}
\arguments{
  \item{x, object}{An object to be printed or summarized from one of the
    date-time classes.}
  \item{digits}{Number of significant digits for the computations:
    should be high enough to represent the least important time unit
    exactly.}
  \item{\dots}{Further arguments to be passed from or to other methods.}
  \item{time, time1, time2}{date-time objects.}
  \item{number}{a numeric object.}
  \item{lop}{One of \code{==}, \code{!=}, \code{<}, \code{<=}, \code{>}
    or \code{>=}.}
}
\details{
  There are two basic classes of date/times.  Class \code{"POSIXct"}
  represents the (signed) number of seconds since the beginning of 1970
  as a numeric vector.  Class \code{"POSIXlt"} is a named list of
  vectors representing
  \describe{
    \item{\code{sec}}{0--61: seconds}
    \item{\code{min}}{0--59: minutes}
    \item{\code{hour}}{0--23: hours}
    \item{\code{mday}}{1--31: day of the month}
    \item{\code{mon}}{0--11: months after the first of the year.}
    \item{\code{year}}{Years since 1900.}
    \item{\code{wday}}{0--6 day of the week, starting on Sunday.}
    \item{\code{yday}}{0--365: day of the year.}
    \item{\code{isdst}}{Daylight savings time flag. Positive if in
      force, zero if not, negative if unknown.}
  }
  The classes correspond to the ANSI C constructs of \dQuote{calendar
    time} (the \code{time\_t} data type) and \dQuote{local time} (or
  broken-down time, the \code{struct tm} data type), from which they
  also inherit their names.

  \code{"POSIXct"} is more convenient for including in data frames, and
  \code{"POSIXlt"} is closer to human-readable forms.
  A virtual class \code{"POSIXt"} inherits from both of the classes: it
  is used to allow operations such as subtraction to mix the two classes.

  Logical comparisons and limited arithmetic are available for both classes.
  One can add or subtract a number of seconds or a
  \code{\link{difftime}} object from a date-time object,
  but not add two date-time objects.  Subtraction of two date-time objects
  is equivalent to using \code{\link{difftime}}.  Be aware
  that \code{"POSIXlt"} objects will be interpreted as being in the
  current timezone for these operations, unless a timezone has been
  specified.

  \code{"POSIXlt"} objects will often have an attribute \code{"tzone"},
  a character vector of length 3 giving the timezone name from the
  \env{TZ} environment variable and the names of the base timezone
  and the alternate (daylight-saving) timezone.  Sometimes this may
  just be of length one, giving the timezone name.

  Unfortunately, the conversion is complicated by the operation of time
  zones and leap seconds (22 days have been 86401 seconds long so far:
  the times of the extra seconds are in the object \code{.leap.seconds}).
  The details of this are entrusted to the OS services where possible.
  This will usually cover the period 1970--2037, and on Unix machines
  back to 1902 (when time zones were in their infancy).  Outside those
  ranges we use our own C code.  This uses the offset from GMT in use
  in the timezone in 2000, and uses the alternate (daylight-saving)
  timezone only if \code{isdst} is positive.

  It seems that some systems use leap seconds but most do not. This is
  detected and corrected for at build time, so all \code{"POSIXct"}
  times used by \R do not include leap seconds.  (Conceivably this could
  be wrong if the system has changed since build time, just possibly by
  changing locales.)

  Using \code{\link{c}} on \code{"POSIXlt"} objects converts them to the
  current time zone.

}
\seealso{
  \code{\link{as.POSIXct}} and \code{\link{as.POSIXlt}} for conversion
  between the classes.

  \code{\link{strptime}} for conversion to and from character
  representations.

  \code{\link{Sys.time}} for clock time as a \code{"POSIXct"} object.

  \code{\link{difftime}} for time intervals.

  \code{\link{cut.POSIXt}}, \code{\link{seq.POSIXt}},
  \code{\link{round.POSIXt}} and \code{\link{trunc.POSIXt}} for methods
  for these classes.

  \code{\link{weekdays.POSIXt}} for convenience extraction functions.
}
\section{Warning}{
  Some Unix-like systems (especially Linux ones) do not have \code{"TZ"}
  set, yet have internal code that expects it (as does POSIX).  We have
  tried to work around this, but if you get unexpected results try
  setting \code{"TZ"}.
}
\examples{
(z <- Sys.time())             # the current date, as class "POSIXct"

Sys.time() - 3600             # an hour ago

as.POSIXlt(Sys.time(), "GMT") # the current time in GMT
format(.leap.seconds)         # all 22 leapseconds in your timezone
}
\keyword{utilities}
\keyword{chron}
\eof
\name{Defunct}
\title{Defunct Functions}
\alias{Defunct}
\alias{.Defunct}
%------ PLEASE: put \alias{.} here for  EACH !
\alias{Version}
\alias{provide}
\alias{.Provided}
\alias{category}
\alias{dnchisq}
\alias{pnchisq}
\alias{qnchisq}
\alias{rnchisq}
\alias{print.anova.glm}
\alias{print.anova.lm}
\alias{print.tabular}
\alias{print.plot}
\alias{save.plot}
\alias{system.test}
\alias{dotplot}
\alias{stripplot}
\alias{getenv}
\alias{read.table.url}
\alias{scan.url}
\alias{source.url}
\alias{httpclient}
\alias{parse.dcf}
\alias{.Alias}
\alias{reshapeLong}
\alias{reshapeWide}
\alias{piechart}
\alias{print.ordered}
\alias{.Dyn.libs}
\alias{.lib.loc}
\alias{machine}
\alias{Platform}
\alias{Machine}
\alias{restart}
\alias{printNoClass}
\alias{plot.mts}
%
\description{
  The functions or variables listed here are no longer part of \R as
  they are not needed (any more).
}
\usage{
.Defunct()

%--- oldfun(.)
Version()
provide(package)
% Removed in 1.2.0
.Provided
category(\dots)
dnchisq(.)
pnchisq(.)
qnchisq(.)
rnchisq(.)
print.anova.glm(.)
print.anova.lm(.)
print.tabular(.)
print.plot(.)
save.plot(.)
system.test(.)
% </Removed 1.2.0>
% Removed in 1.3.0
dotplot(\dots)
stripplot(\dots)
getenv(\dots)
% </Removed 1.3.0>
% Removed in 1.4.0
read.table.url(url, method,\dots)
scan.url(url, file = tempfile(), method, \dots)
source.url(url, file = tempfile(), method, \dots)
httpclient(url, port=80, error.is.fatal=TRUE, check.MIME.type=TRUE,
           file=tempfile(), drop.ctrl.z=TRUE)
parse.dcf(text = NULL, file = "", fields = NULL, versionfix = FALSE)
% </Removed 1.4.0>
% Removed in 1.5.0
.Alias(expr)
reshapeWide(x, i = reshape.i, j = reshape.j, val = reshape.v,
            jnames = levels(j))
reshapeLong(x,jvars,  ilev = row.names(x),
            jlev = names(x)[jvars], iname = "reshape.i",
            jname = "reshape.j", vname = "reshape.v")
% </Removed 1.5.0>
% Removed in 1.6.0
piechart(x, labels = names(x), edges = 200, radius = 0.8,
         density = NULL, angle = 45, col = NULL, main = NULL, \dots)
print.ordered(.)
.Dyn.libs
.lib.loc
% </Removed 1.6.0>
% Removed in 1.7.0
machine()
Machine()
Platform()
restart()
% </Removed 1.7.0>
% Removed in 1.8.0
printNoClass(x, digits = NULL, quote = TRUE, na.print = NULL,
             print.gap = NULL, right = FALSE, \dots)
% plot.mts can't have such an object, though
plot.mts(x, plot.type = c("multiple", "single"), panel = lines,
         log = "", col = par("col"),  bg = NA, pch = par("pch"),
         cex = par("cex"), lty = par("lty"), lwd = par("lwd"),
         ann = par("ann"),  xlab = "Time", type = "l", main=NULL,
         oma=c(6, 0, 5, 0), \dots)
% </Removed 1.8.0>
}
\details{
  \code{.Defunct} is the function to which defunct functions are set.
  
  \code{category} has been an old-S function before there were factors;
  should be replaced by \code{\link{factor}} throughout!

  The \code{*chisq()} functions now take an optional non-centrality
  argument, so the \code{*nchisq()} functions are no longer needed.

  The new function \code{dev.print()} should now be used for saving
  plots to a file or printing them.

  \code{provide} and its object \code{.Provided} have been removed.
  They were never used for their intended purpose, to allow one
  package to subsume another.

  \code{dotplot} and \code{stripplot} have been renamed to
  \code{\link{dotchart}} and \code{\link{stripchart}}, respectively.

  \code{getenv} has been replaced by \code{\link{Sys.getenv}}.


  \code{*.url} are replaced by calling \code{read.table}, \code{scan} or
  \code{source} on a \code{\link{url}} connection.

  \code{httpclient} was used by the deprecated \code{"socket"} method
  of \code{\link{download.file}}.

  \code{parse.dcf} has been replaced by \code{read.dcf}, which is much
  faster, but has a slightly different interface.

  \code{.Alias} provided an unreliable way to create duplicate
  references to the same object. There is no direct replacement. Where
  multiple references to a single object are required for semantic
  reasons consider using environments or external pointers. There are
  some notes on \url{http://developer.r-project.org}.

  \code{reshape*}, which were experimental, are replaced by
  \code{\link{reshape}}. This has a different syntax and allows multiple
  time-varying variables.

  \code{piechart} is the old name for \code{pie}, but clashed with usage
  in Trellis.

  \code{.Dyn.libs} and \code{.lib.loc} were internal variables used for
  storing and manipulating the information about packages with dynloaded
  shared libs, and the known \R library trees.  These are now dynamic
  variables which one can get or set using \code{\link{.dynLibs}} and
  \code{\link{.libPaths}}, respectively.

  \code{Machine()} and \code{Platform()} were functions returning the
  variables \code{\link{.Machine}} and \code{\link{.Platform}}
  respectively.

  \code{restart()} should be replaced by \code{try()}, in preparation
  for an exception-based implementation.  If you use \code{restart()} in
  a way that cannot be replaced with \code{try()} then ask for help
  on \code{r-devel}.

  \code{printNoClass} was in package \pkg{methods} and calls directly the
  internal function \code{print.default}.

  \code{plot.mts} has been removed, as \code{\link{plot.ts}} now has the
  same functionality.
}
\seealso{\code{\link{Deprecated}}}
\keyword{documentation}
\keyword{utilities}
\keyword{internal}
\eof
\name{Deprecated}
%------ NOTE:  ../R/Deprecated.R   must be synchronized with this!
\title{Deprecated Functions}
\alias{Deprecated}
\alias{.Deprecated}
\alias{tkfilefind}
\alias{print.coefmat}
\alias{codes}
\alias{codes.factor}
\alias{codes.ordered}
\alias{codes<-}
\alias{anovalist.lm}
\alias{lm.fit.null}
\alias{lm.wfit.null}
\alias{glm.fit.null}
\alias{print.atomic}
%------ PLEASE: put \alias{.} here for EACH !
\description{
  These functions are provided for compatibility with older versions of
  \R only, and may be defunct as soon as of the next release.
}
\usage{
.Deprecated(new)

% Deprecated in 1.8.0
print.coefmat(x, digits=max(3, getOption("digits") - 2),
              signif.stars = getOption("show.signif.stars"),
              dig.tst = max(1, min(5, digits - 1)),
              cs.ind = 1:k, tst.ind = k + 1, zap.ind = integer(0),
              P.values = NULL,
              has.Pvalue = nc >= 4 && substr(colnames(x)[nc],1,3) == "Pr(",
              eps.Pvalue = .Machine$double.eps,
              na.print = "", \dots)

codes(x, \dots)
codes(x, \dots) <- value

anovalist.lm(object, \dots, test = NULL)
lm.fit.null(x, y, method = "qr", tol = 1e-07, \dots)
lm.wfit.null(x, y, w, method = "qr", tol = 1e-07, \dots)
glm.fit.null(x, y, weights = rep(1, nobs), start = NULL,
             etastart = NULL, mustart = NULL, offset = rep(0, nobs),
             family = gaussian(), control = glm.control(),
             intercept = FALSE)
print.atomic(x, quote = TRUE, \dots)
% </Deprecated 1.8.0>
}
\details{
  \code{.Deprecated("<new name>")} is called from deprecated
  functions. The original help page for these functions is often
  available at \code{help("oldName-deprecated")} (note the quotes).

  \code{tkfilefind} is a demo in package \pkg{tcltk} displaying a
  widget for selecting files but the same functionality is available in
  a better form in the \code{tkgetOpenFile} and \code{tkgetSaveFile}
  functions. The demo is reported not even to work with recent versions
  of Tcl and Tk libraries.

  \code{print.coefmat} is an older name for \code{\link{printCoefmat}}
  with a different default for \code{na.print}.

  \code{codes} was almost always used inappropriately.  To get the
  internal coding of a factor, use \code{unclass}, \code{as.vector} or
  \code{as.integer}.  For \emph{ordered} factors, \code{codes} was
  equivalent to these, but for \emph{unordered} factors it assumed an
  an alphabetical ordering of the levels in the locale in use.

  \code{anovalist.lm} was replaced by \code{\link{anova.lmlist}} in
  \R 1.2.0.

  \code{lm.fit.null} and \code{lm.wfit.null} are superseded by
  \code{lm.fit} and \code{lm.wfit} which handle null models now.
  Similarly, \code{glm.fit.null} is superseded by \code{glm.fit}.

  \code{print.atomic} differs from \code{print.default} only in its
  argument sequence.  It is not a method for \code{print}.
}
\seealso{
  \code{\link{Defunct}},
}
\keyword{documentation}
\keyword{utilities}
\eof
\name{Devices}
\title{List of Graphical Devices}
\usage{
#ifdef unix
X11(\dots)
#endif
#ifdef windows
windows(\dots)
#endif
%% FIXME:
#ifdef aqua
quartz(\dots)
#endif
postscript(\dots)
pdf(\dots)
pictex(\dots)
#ifdef unix
png(\dots)
jpeg(\dots)
GTK(\dots)
GNOME(\dots)
#endif
#ifdef windows
win.metafile(\dots)
win.print(\dots)
png(\dots)
jpeg(\dots)
bmp(\dots)
#endif
xfig(\dots)
bitmap(\dots)

dev.interactive()
}
\alias{Devices}
\alias{device}
\alias{dev.interactive}
\description{The following graphics devices are currently available:
  \itemize{
    \item \code{\link{postscript}} Writes PostScript graphics commands to
    a file
    \item \code{\link{pdf}} Write PDF graphics commands to a file
    \item \code{\link{pictex}} Writes LaTeX/PicTeX graphics commands to a
    file
#ifdef windows
    \item \code{\link{windows}} The graphics driver for Windows (on screen,
    to printer and to Windows metafile).
    \item \code{\link{png}} PNG bitmap device
    \item \code{\link{jpeg}} JPEG bitmap device
    \item \code{\link{bmp}} BMP bitmap device
#endif
    \item \code{\link{xfig}} Device for XFIG graphics file format
    \item \code{\link{bitmap}} bitmap pseudo-device via
    \code{GhostScript} (if available).
  }
#ifdef unix
  The following devices will be available if \R was compiled to use them
  and started with the appropriate \option{--gui} argument:
  \itemize{
    \item \code{\link{X11}} The graphics driver for the X11 Window
    system
    \item \code{\link{png}} PNG bitmap device
    \item \code{\link{jpeg}} JPEG bitmap device
    \item \code{\link{GTK}}, \code{\link{GNOME}} Graphics drivers for
    the GNOME GUI.
%% <FIXME>  quartz() also with corresponding --gui aqua ?
#ifdef aqua
%%     ^^^^ not yet available
    \item \code{\link{quartz}} The graphics driver for the Mac OSX
    native aqua system.
#endif
%% </FIXME>
  }
  None of these are available under \code{\link[base:BATCH]{R CMD BATCH}}.
#endif
}
\value{
  \code{dev.interactive()} returns a logical, \code{TRUE} iff an
  interactive (screen) device is in use.
}
\details{
  If no device is open, using a high-level graphics function will cause
  a device to be opened.  Which device is given by
  \code{\link{options}("device")} which is initially set as the most
  appropriate for each platform: a screen device in interactive use and
  \code{\link{postscript}} otherwise.
}
\seealso{
  The individual help files for further information on any of the
  devices listed here;

  \code{\link{dev.cur}}, \code{\link{dev.print}},
  \code{\link{graphics.off}}, \code{\link{image}},
  \code{\link{dev2bitmap}}.
#ifdef unix

  \code{\link{capabilities}} to see if \code{\link{X11}}, \code{\link{jpeg}}
  and \code{\link{png}} are available.
%% FIXME: aqua / quartz ?
#endif
}
\examples{\dontrun{
## open the default screen device on this platform if no device is
## open
if(dev.cur() == 1) get(getOption("device"))()
}}
\keyword{device}
\eof
\name{Exponential}
\alias{Exponential}
\alias{dexp}
\alias{pexp}
\alias{qexp}
\alias{rexp}
\title{The Exponential Distribution}
\description{
  Density, distribution function, quantile function and random
  generation for the exponential distribution with rate \code{rate}
  (i.e., mean \code{1/rate}).
}
\usage{
dexp(x, rate = 1, log = FALSE)
pexp(q, rate = 1, lower.tail = TRUE, log.p = FALSE)
qexp(p, rate = 1, lower.tail = TRUE, log.p = FALSE)
rexp(n, rate = 1)
}
\arguments{
  \item{x, q}{vector of quantiles.}
  \item{p}{vector of probabilities.}
  \item{n}{number of observations. If \code{length(n) > 1}, the length
    is taken to be the number required.}
  \item{rate}{vector of rates.}
  \item{log, log.p}{logical; if TRUE, probabilities p are given as log(p).}
  \item{lower.tail}{logical; if TRUE (default), probabilities are
    \eqn{P[X \le x]}{P[X <= x]}, otherwise, \eqn{P[X > x]}{P[X > x]}.}
}
\value{
  \code{dexp} gives the density,
  \code{pexp} gives the distribution function,
  \code{qexp} gives the quantile function, and
  \code{rexp} generates random deviates.
}
\details{
  If \code{rate} is not specified, it assumes the default value of
  \code{1}.

  The exponential distribution with rate \eqn{\lambda} has density
  \deqn{
    f(x) = \lambda {e}^{- \lambda x}}{
    f(x) = lambda e^(- lambda x)}
  for \eqn{x \ge 0}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{exp}} for the exponential function,
  \code{\link{dgamma}} for the gamma distribution and
  \code{\link{dweibull}} for the Weibull distribution, both of which
  generalize the exponential.
}
\note{
  The cumulative hazard \eqn{H(t) = - \log(1 - F(t))}{H(t) = - log(1 - F(t))}
  is \code{-pexp(t, r, lower = FALSE, log = TRUE)}.
}
\examples{
dexp(1) - exp(-1) #-> 0
}
\keyword{distribution}
\eof
\name{Extract}
\title{Extract or Replace Parts of an Object}
\alias{Extract}
\alias{Subscript}
\alias{[}
\alias{[[}
\alias{$}
\alias{[<-}
\alias{[[<-}
\alias{$<-}
%- methods not documented elsewhere
\alias{[.formula}
\alias{[.ts}
\alias{.subset}
\alias{.subset2}
\description{
  Operators act on vectors, arrays and lists to extract or
  replace subsets.
}
\usage{
x[i]
x[i, j, \dots , drop=TRUE]
x[[i]]
x[[i, j, \dots]]
x$name

.subset(x, \dots)
.subset2(x, \dots)
}
\arguments{
  \item{x}{object from which to extract elements or in which to replace
    elements.}
  \item{i, j, \dots, name}{elements to extract or replace. \code{i, j} are
    \code{numeric} or \code{character} or empty whereas \code{name} must be
    character or an (unquoted) name.  Numeric values are coerced to
    integer as by \code{\link{as.integer}}.
    
    For \code{[}-indexing only: \code{i, j, \dots} can be
    logical vectors, indicating elements/slices to select. Such vectors
    are recycled if necessary to match the corresponding extent. When
    indexing arrays, \code{i} can be a (single) matrix with as many
    columns as there are dimensions of \code{x}; the result is then a
    vector with elements corresponding to the sets of indices in each
    row of \code{i}.}
  \item{drop}{For matrices, and arrays.  If \code{TRUE} the
    result is coerced to the lowest possible dimension (see examples
    below). This only works for extracting elements, not for the
    replacement forms.}
}
\details{
  These operators are generic.  You can write methods to handle subsetting
  of specific classes of objects, see \link{InternalMethods} as well as
  \code{\link{[.data.frame}} and \code{\link{[.factor}}.  The
  descriptions here apply only to the default methods.

  The most important distinction between \code{[}, \code{[[} and
  \code{$} is that the \code{[} can select more than one element whereas
  the other two select a single element.  \code{$} does not allow
  computed indices, whereas \code{[[} does.  \code{x$name} is equivalent
  to \code{x[["name"]]} if \code{x} is recursive
  (see \code{\link{is.recursive}}) and \code{NULL} otherwise.
  
  The \code{[[} operator requires all relevant subscripts to be supplied.
  With the \code{[} operator an empty index (a comma separated blank)
  indicates that all entries in that dimension are selected.

  If one of these expressions appears on the left side of an assignment
  then that part of \code{x} is set to the value of the right hand side
  of the assignment.

  Indexing by factors is allowed and is equivalent to indexing by the
  numeric codes (see \code{\link{factor}}) and not by the character
  values which are printed (for which use \code{[as.character(i)]}).

  When operating on a list, the \code{[[} operator gives the specified
  element of the list while the \code{[} operator returns a list with
  the specified element(s) in it.

  As from \R 1.7.0 \code{[[} can be applied recursively to lists, so
  that if the single index \code{i} is a vector of length \code{p},
  \code{alist[[i]]} is equivalent to \code{alist[[i1]]\dots[[ip]]}
  providing all but the final indexing results in a list.

  The operators \code{$} and \code{$<-} do not evaluate their second
  argument.  It is translated to a string and that string is used to
  locate the correct component of the first argument.

  When \code{$<-} is applied to a \code{NULL} \code{x}, it coerces
  \code{x} to \code{list()}.  This is what happens with \code{[[<-} is
  \code{y} is of length greater than one: if \code{y} has length 1 or 0,
  \code{x} is coerced to a zero-length vector of the type of \code{value}, 

  The functions \code{.subset} and \code{.subset2} are essentially
  equivalent to the \code{[} and \code{[[} operators, except that
  methods dispatch does not take place.  This is to avoid expensive
  unclassing when applying the default method to an object.  They
  should not normally be invoked by end users.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{list}}, \code{\link{array}}, \code{\link{matrix}}.

  \code{\link{[.data.frame}} and \code{\link{[.factor}} for the
  behaviour when applied to data.frame and factors.

  \code{\link{Syntax}} for operator precedence, and the
  \emph{R Language} reference manual about indexing details.
  %% Fixme: Link (to html in 'help.start()', pdf from 'ref manual',
  %% 'info' from ESS, see \url{http://cran.R-project.org/manuals.html}.
}
\examples{
x <- 1:12; m <- matrix(1:6,nr=2); li <- list(pi=pi, e = exp(1))
x[10]                 # the tenth element of x
m[1,]                 # the first row of matrix m
m[1, , drop = FALSE]  # is a 1-row matrix
m[,c(TRUE,FALSE,TRUE)]# logical indexing
m[cbind(c(1,2,1),3:1)]# matrix index
li[[1]]               # the first element of list li
y <- list(1,2,a=4,5)
y[c(3,4)]             # a list containing elements 3 and 4 of y
y$a                   # the element of y named a

## non-integer indices are truncated:
(i <- 3.999999999) # "4" is printed
(1:5)[i]  # 3

## recursive indexing into lists
z <- list( a=list( b=9, c='hello'), d=1:5)
unlist(z)
z[[c(1, 2)]]
z[[c(1, 2, 1)]]  # both "hello"
z[[c("a", "b")]] <- "new"
unlist(z)
}
\keyword{array}
\keyword{list}
\eof
\name{Extract.data.frame}
\alias{[.data.frame}
\alias{[[.data.frame}
\alias{[<-.data.frame}
\alias{[[<-.data.frame}
\alias{$<-.data.frame}
\title{Extract or Replace Parts of a Data Frame}
\description{
  Extract or replace subsets of data frames.
}
\usage{
x[i]
x[i] <- value
x[i, j, drop = TRUE]
x[i, j] <- value

x[[i]]
x[[i]] <- value
x[[i, j]]
x[[i, j]] <- value

x$name
x$name <- value
}
\arguments{
  \item{x}{data frame.}
  \item{i, j}{elements to extract or replace. \code{i, j} are
    \code{numeric} or \code{character} or, for \code{[} only, empty.
    Numeric values are coerced to integer as if by \code{\link{as.integer}}.
    For replacement by \code{[}, a logical matrix is allowed.
  }

  \item{drop}{logical.  If \code{TRUE} the result is coerced to the
    lowest possible dimension: however, see the Warning below.}

  \item{value}{A suitable replacement value: it will be repeated a whole
    number of times if necessary and it may be coerced: see the
    Coercion section.  If \code{NULL}, deletes the column if a single
    column is selected.}

  \item{name}{name or literal character string.}
}
\details{
  Data frames can be indexed in several modes.  When \code{[} and
  \code{[[} are used with a single index, they index the data frame
  as if it were a list.  In this usage a \code{drop} argument is
  ignored, with a warning.  Using \code{$} is equivalent to using
  \code{[[} with a single index.

  When \code{[} and \code{[[} are used with two indices they act
  like indexing a matrix:  \code{[[} can only be used to select one element.

  If \code{[} returns a data frame it will have unique (and non-missing)
  row names, if necessary transforming the row names using
  \code{\link{make.unique}}.  Similarly, column names
  will be transformed (if columns are selected more than once).

  When \code{drop =TRUE}, this is applied to the subsetting of any
  matrices contained in the data frame as well as to the data frame itself.

  The replacement methods can be used to add whole column(s) by specifying
  non-existent column(s), in which case the column(s) are added at the
  right-hand edge of the data frame and numerical indices must be
  contiguous to existing indices.  On the other hand, rows can be added
  at any row after the current last row, and the columns will be
  in-filled with missing values.

  For \code{[} the replacement value can be a list: each element of the
  list is used to replace (part of) one column, recycling the list as
  necessary.  If the columns specified by number are created, the names
  (if any) of the corresponding list elements are used to name the
  columns.  If the replacment is not selecting rows, list values can
  contain \code{NULL} elements which will cause the corresponding
  columns to be deleted.

  Matrixing indexing using \code{[} is not recommended, and barely
  supported.  For extraction, \code{x} is first coerced to a matrix.
  For replacement a logical matrix (only) can be used to select the
  elements to be replaced in the same ways as for a matrix.
  Missing values in the matrix are treated as false, unlike S which
  does not replace them but uses up the corresponding values in \code{value}.
}
\section{Coercion}{
  The story over when replacement values are coerced is a complicated
  one, and one that has changed during \R's development.  This section
  is a guide only.

  When \code{[} and \code{[[} are used to add or replace a whole column,
  no coercion takes place but \code{value} will be
  replicated (by calling the generic function \code{\link{rep}}) to the
  right length if an exact number of repeats can be used.

  When \code{[} is used with a logical matrix, each value is coerced to
  the type of the column in which it is to be placed.

  When  \code{[} and \code{[[} are used with two indices, the
  column will be coerced as necessary to accommodate the value.
}
\section{Warning}{
  Although the default for \code{drop} is \code{TRUE}, the default
  behaviour  when only one \emph{row} is left is equivalent to
  specifying \code{drop = FALSE}.  To drop from a data frame to a list,
  \code{drop = FALSE} has to specified explicitly.
}
\value{
  For \code{[} a data frame, list or a single column (the latter two
  only when dimensions have been dropped).  If matrix indexing is used for
  extraction a matrix results.

  For \code{[[} a column of the data frame (extraction with one index)
  or a length-one vector (extraction with two indices).

  For \code{[<-}, \code{[[<-} and \code{$<-}, a data frame.
}
\seealso{
  \code{\link{subset}} which is often easier for extraction,
  \code{\link{data.frame}}, \code{\link{Extract}}.
}
\examples{
data(swiss)
sw <- swiss[1:5, 1:4]  # select a manageable subset

sw[1:3]      # select columns
sw[, 1:3]    # same
sw[4:5, 1:3] # select rows and columns
sw[1]        # a one-column data frame
sw[, 1, drop = FALSE]  # the same
sw[, 1]      # a (unamed) vector
sw[[1]]      # the same

sw[1,]       # a one-row data frame
sw[1,, drop=TRUE]  # a list

swiss[ c(1, 1:2), ]   # duplicate row, unique row names are created

sw[sw <= 6] <- 6  # logical matrix indexing
sw

## adding a column
sw["new1"] <- LETTERS[1:5]   # adds a character column
sw[["new2"]] <- letters[1:5] # ditto
sw[, "new3"] <- LETTERS[1:5] # ditto
                             # but this got converted to a factor in 1.7.x
sw$new4 <- 1:5
sapply(sw, class)
sw$new4 <- NULL              # delete the column
sw
sw[6:8] <- list(letters[10:14], NULL, aa=1:5) # delete col7, update 6, append
sw

## matrices in a data frame
A <- data.frame(x=1:3, y=I(matrix(4:6)), z=I(matrix(letters[1:9],3,3)))
A[1:3, "y"] # a matrix, was a vector prior to 1.8.0
A[1:3, "z"] # a matrix
A[, "y"]    # a matrix
}
\keyword{array}
\eof
\name{Extract.factor}
\title{Extract or Replace Parts of a Factor}
\alias{[.factor}
\alias{[<-.factor}
\description{
  Extract or replace subsets of factors.
}
\usage{
x[i, drop = FALSE]

x[i] <- value
}
\arguments{
  \item{x}{a factor}
  \item{i}{a specification of indices -- see \code{\link{Extract}}.}
  \item{drop}{logical.  If true, unused levels are dropped.}
  \item{value}{character: a set of levels.  Factor values are coerced to
    character.}
}
\value{
  A factor with the same set of levels as \code{x} unless \code{drop=TRUE}.
}
\details{
  When unused levels are dropped the ordering of the remaining levels is
  preserved.
  
  If \code{value} is not in \code{levels(x)}, a missing value is
  assigned with a warning.
  
  Any \code{\link{contrasts}} assigned to the factor are preserved
  unless \code{drop=TRUE}.
}
\seealso{
  \code{\link{factor}}, \code{\link{Extract}}.
}
\examples{
## following example(factor)
(ff <- factor(substring("statistics", 1:10, 1:10), levels=letters))
ff[, drop=TRUE]
factor(letters[7:10])[2:3, drop = TRUE]
}
\keyword{category}
\eof
\name{Extremes}
\alias{max}
\alias{min}
\alias{pmax}
\alias{pmin}
\title{Maxima and Minima}
\description{
  Returns the (parallel) maxima and minima of the input values.
}
\usage{
max(\dots, na.rm=FALSE)
min(\dots, na.rm=FALSE)

pmax(\dots, na.rm=FALSE)
pmin(\dots, na.rm=FALSE)
}
\arguments{
  \item{\dots}{numeric arguments.}
  \item{na.rm}{a logical indicating whether missing values should be
    removed.}
}
\value{
  \code{max} and \code{min} return the maximum or minimum of all the
  values present in their arguments, as \code{\link{integer}} if all are
  \code{integer}, % and at least one is nonempty
  or as \code{\link{double}} otherwise.

  The minimum and maximum of an empty set are \code{+Inf} and \code{-Inf}
  (in this order!) which ensures \emph{transitivity}, e.g.,
  \code{min(x1, min(x2)) == min(x1,x2)}.
  In \R versions before 1.5, \code{min(integer(0)) == .Machine$integer.max},
  and analogously for \code{max}, preserving argument \emph{type},
  whereas from \R version 1.5.0, \code{max(x) == -Inf} and
  \code{min(x) == +Inf} whenever \code{length(x) == 0} (after removing
  missing values if requested).

  If \code{na.rm} is \code{FALSE} an \code{NA} value in any of the
  arguments will cause a value of \code{NA} to be returned, otherwise
  \code{NA} values are ignored.

  \code{pmax} and \code{pmin} take several vectors (or matrices) as arguments and
  return a single vector giving the parallel maxima (or minima) of the
  vectors.  The first element of the result is the maximum (minimum) of
  the first elements of all the arguments, the second element of the
  result is the maximum (minimum) of the second elements of all the
  arguments and so on.  Shorter vectors are recycled if necessary.  If
  \code{na.rm} is \code{FALSE}, \code{NA} values in the input vectors
  will produce \code{NA} values in the output.  If \code{na.rm} is
  \code{TRUE}, \code{NA} values are ignored.
  \code{\link{attributes}} (such as \code{\link{names}} or
  \code{\link{dim}}) are transferred from the first argument (if applicable).
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{range}} (\emph{both} min and max) and
  \code{\link{which.min}} (\code{which.max}) for the \emph{arg min},
  i.e., the location where an extreme value occurs.
}
\examples{
min(5:1,pi)
pmin(5:1, pi)
x <- sort(rnorm(100));  cH <- 1.35
pmin(cH, quantile(x)) # no names
pmin(quantile(x), cH) # has names
plot(x, pmin(cH, pmax(-cH, x)), type='b', main= "Huber's function")
}
\keyword{univar}
\keyword{arith}
\eof
\name{FDist}
\alias{FDist}
\alias{df}
\alias{pf}
\alias{qf}
\alias{rf}
\title{The F Distribution}
\description{
  Density, distribution function, quantile function and random
  generation for the F distribution with \code{df1} and \code{df2}
  degrees of freedom (and optional non-centrality parameter
  \code{ncp}).
}
\usage{
df(x, df1, df2, log = FALSE)
pf(q, df1, df2, ncp=0, lower.tail = TRUE, log.p = FALSE)
qf(p, df1, df2,        lower.tail = TRUE, log.p = FALSE)
rf(n, df1, df2)
}
\arguments{
  \item{x, q}{vector of quantiles.}
  \item{p}{vector of probabilities.}
  \item{n}{number of observations. If \code{length(n) > 1}, the length
    is taken to be the number required.}
  \item{df1, df2}{degrees of freedom.}
  \item{ncp}{non-centrality parameter.}
  \item{log, log.p}{logical; if TRUE, probabilities p are given as log(p).}
  \item{lower.tail}{logical; if TRUE (default), probabilities are
    \eqn{P[X \le x]}{P[X <= x]}, otherwise, \eqn{P[X > x]}{P[X > x]}.}
}
\value{
  \code{df} gives the density,
  \code{pf} gives the distribution function
  \code{qf} gives the quantile function, and
  \code{rf} generates random deviates.
}
\details{
  The F distribution with \code{df1 =} \eqn{n_1}{n1} and \code{df2 =}
  \eqn{n_2}{n2} degrees of freedom has density
  \deqn{
    f(x) = \frac{\Gamma(n_1/2 + n_2/2)}{\Gamma(n_1/2)\Gamma(n_2/2)}
    \left(\frac{n_1}{n_2}\right)^{n_1/2} x^{n_1/2 -1}
    \left(1 + \frac{n_1 x}{n_2}\right)^{-(n_1 + n_2) / 2}%
  }{f(x) = Gamma((n1 + n2)/2) / (Gamma(n1/2) Gamma(n2/2))
    (n1/n2)^(n1/2) x^(n1/2 - 1)
    (1 + (n1/n2) x)^-(n1 + n2)/2}
  for \eqn{x > 0}.

  It is the distribution of the ratio of the mean squares of
  \eqn{n_1}{n1} and \eqn{n_2}{n2} independent standard normals, and hence
  of the ratio of two independent chi-squared variates each divided by its
  degrees of freedom.  Since the ratio of a normal and the root
  mean-square of \eqn{m} independent normals has a Student's \eqn{t_m}
  distribution, the square of a \eqn{t_m} variate has a F distribution on
  1 and \eqn{m} degrees of freedom.

  The non-central F distribution is again the ratio of mean squares of
  independent normals of unit variance, but those in the numerator are
  allowed to have non-zero means and \code{ncp} is the sum of squares of
  the means.  See \code{\link{Chisquare}} for further details on
  non-central distributions.  
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{dchisq}} for chi-squared and \code{\link{dt}} for Student's
  t distributions.
}
\examples{
## the density of the square of a t_m is 2*dt(x, m)/(2*x)
# check this is the same as the density of F_{1,m}
x <- seq(0.001, 5, len=100)
all.equal(df(x^2, 1, 5), dt(x, 5)/x)

## Identity:  qf(2*p - 1, 1, df)) == qt(p, df)^2)  for  p >= 1/2
p <- seq(1/2, .99, length=50); df <- 10
rel.err <- function(x,y) ifelse(x==y,0, abs(x-y)/mean(abs(c(x,y))))
quantile(rel.err(qf(2*p - 1, df1=1, df2=df), qt(p, df)^2), .90)# ~= 7e-9
}
\keyword{distribution}
\eof
\name{Foreign}
\alias{Foreign}
\alias{.C}
\alias{.Fortran}
\alias{.External}
\alias{.Call}
\alias{.External.graphics}
\alias{.Call.graphics}
\title{Foreign Function Interface}
\description{
  Functions to make calls to compiled code that has been loaded into \R.
}
\usage{
                .C(name, \dots, NAOK = FALSE, DUP = TRUE, PACKAGE)
          .Fortran(name, \dots, NAOK = FALSE, DUP = TRUE, PACKAGE)
         .External(name, \dots, PACKAGE)
             .Call(name, \dots, PACKAGE)
.External.graphics(name, \dots, PACKAGE)
    .Call.graphics(name, \dots, PACKAGE)
}
\arguments{
  \item{name}{a character string giving the name of a C function or
    Fortran subroutine.}
  \item{\dots}{arguments to be passed to the foreign function.}
  \item{NAOK}{if \code{TRUE} then any \code{\link{NA}} or
    \code{\link{NaN}} or \code{\link{Inf}} values in the arguments are
    passed on to the foreign function.  If \code{FALSE}, the presence of
    \code{NA} or \code{NaN} or \code{Inf} values is regarded as an error.}
  \item{DUP}{if \code{TRUE} then arguments are \dQuote{duplicated} before
    their address is passed to C or Fortran.}
  \item{PACKAGE}{if supplied, confine the search for the \code{name} to
    the DLL given by this argument (plus the conventional extension,
    \code{.so}, \code{.sl}, \code{.dll}, \dots).  This is intended to
    add safety for packages, which can ensure by using this argument
    that no other package can override their external symbols.  Use
    \code{PACKAGE="base"} for symbols linked in to \R.}
}
\value{
  The functions \code{.C} and \code{.Fortran} return a list similar to
  the \code{\dots} list of arguments passed in, but reflecting any
  changes made by the C or Fortran code.

  \code{.External}, \code{.Call}, \code{.External.graphics},
  and \code{.Call.graphics} return an \R object.

  These calls are typically made in conjunction with
  \code{\link{dyn.load}} which links DLLs to \R.

  The \code{.graphics} versions of \code{.Call} and \code{.External}
  are used when calling code which makes low-level graphics calls.
  They take additional steps to ensure that the device driver display
  lists are updated correctly.
}
\details{
  The functions \code{.C} and \code{.Fortran} can be used to make calls
  to C and Fortran code.

  \code{.External} and \code{.External.graphics} can be used to call
  compiled code that uses \R objects in the same way as internal
  \R functions.

  \code{.Call} and \code{.Call.graphics} can be used call compiled code
  which makes use of internal \R objects.  The arguments are passed to
  the C code as a sequence of \R objects.  It is included to provide
  compatibility with S version 4.

  For details about how to write code to use with \code{.Call} and
  \code{.External}, see the chapter on \dQuote{System and foreign language
  interfaces} in \dQuote{Writing \R Extensions} in the \file{doc/manual}
  subdirectory of the \R source tree.

#ifdef windows
  For Windows-specific details on producing the external code, see the
  file \file{readme.packages}.
#endif
}
%%-- This note based on BDR's understanding, edited TSL
\section{Argument types}{
  The mapping of the types of \R arguments to C or Fortran arguments
  in \code{.C} or \code{.Fortran} is

  \tabular{lll}{
    \R \tab     C \tab     Fortran\cr
    integer \tab int * \tab integer\cr
    numeric \tab double * \tab double precision\cr
    -- or -- \tab float * \tab real\cr
    complex \tab Rcomplex * \tab double complex\cr
    logical \tab int * \tab integer \cr
    character \tab char ** \tab [see below]\cr
    list \tab SEXP *\tab not allowed\cr
    other \tab SEXP\tab not allowed\cr
  }

  Numeric vectors in \R will be passed as type \code{double *} to C (and
  as \code{double precision} to Fortran) unless (i) \code{.C} or
  \code{.Fortran} is used, (ii) \code{DUP} is false and (iii) the
  argument has attribute \code{Csingle} set to \code{TRUE} (use
  \code{\link{as.single}} or \code{\link{single}}).  This mechanism is
  only intended to be used to facilitate the interfacing of existing C
  and Fortran code.

  The C type \code{Rcomplex} is defined in \file{Complex.h} as a
  \code{typedef struct {double r; double i;}}.  Fortran type
  \code{double complex} is an extension to the Fortran standard, and the
  availability of a mapping of \code{complex} to Fortran may be compiler
  dependent.

  \emph{Note:} The C types corresponding to \code{integer} and
  \code{logical} are \code{int}, not \code{long} as in S.

  The first character string of a character vector is passed as a C
  character array to Fortran: that string may be usable as
  \code{character*255} if its true length is passed separately.  Only up
  to 255 characters of the string are passed back.  (How well this works,
  or even if it works at all, depends on the C and Fortran compilers
  and the platform.)

  Missing (\code{NA}) string values are passed to \code{.C} as the string
  "NA". As the C \code{char} type can represent all possible bit patterns
  there appears to be no way to distinguish missing strings from the
  string \code{"NA"}. If this distinction is important use \code{.Call}.

  Functions, expressions, environments and other language elements are
  passed as the internal \R pointer type \code{SEXP}.  This type is
  defined in \file{Rinternals.h} or the arguments can be declared as
  generic pointers, \code{void *}. Lists are passed as C arrays of
  \code{SEXP} and can be declared as \code{void *} or \code{SEXP *}.
  Note that you cannot assign values to the elements of the list within
  the C routine. Assigning values to elements of the array corresponding
  to the list bypasses R's memory management/garbage collection and will
  cause problems.  Essentially, the array corresponding to the list is read-only.
  If you need to return S objects created within the C routine,  use the
  \code{.Call} interface.


  \R functions can be invoked using \code{call_S} or \code{call_R} and
  can be passed lists or the simple types as arguments.
}
%%-- This note by Thomas Lumley, (minimally edited by MM,
%%      edited by BDR for 1.2.0's non-moving garbage collector):
\note{\emph{\code{DUP=FALSE} is dangerous.}

  There are two dangers with using \code{DUP=FALSE}.

  The first is that if you pass a local variable to
  \code{.C}/\code{.Fortran} with \code{DUP=FALSE}, your compiled code
  can alter the local variable and not just the copy in the return list.
  Worse, if you pass a local variable that is a formal parameter of
  the calling function, you may be able to change not only the local
  variable but the variable one level up.  This will be very hard to trace.

  The second is that lists are passed as a single \R \code{SEXP} with
  \code{DUP=FALSE}, not as an array of \code{SEXP}. This means the
  accessor macros in \file{Rinternals.h} are needed to get at the list
  elements and the lists cannot be passed to
  \code{call_S}/\code{call_R}.  New code using \R objects should be
  written using \code{.Call} or \code{.External}, so this is now only a
  minor issue.

  (Prior to \R version 1.2.0 there has a third danger, that objects
  could be moved in memory by the garbage collector. The current garbage
  collector never moves objects.)

  It is safe and useful to set \code{DUP=FALSE} if you do not change any
  of the variables that might be affected, e.g.,

  \code{.C("Cfunction", input=x, output=numeric(10))}.

  In this case the output variable did not exist before the call so it
  cannot cause trouble. If the input variable is not changed in the C
  code of \code{Cfunction} you are safe.

  Neither \code{.Call} nor \code{.External} copy their arguments.  You
  should treat arguments you receive through these interfaces as
  read-only.
}

\section{Header files for external code}{
    Writing code for use with \code{.External} and \code{.Call} will
    use internal \R structures. If possible use just those defined in
    \file{Rinternals.h} and/or the macros in \file{Rdefines.h},
    as other header files are not installed and are even more
    likely to be changed.
}

\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole. (\code{.C} and \code{.Fortran}.)

  Chambers, J. M. (1998)
  \emph{Programming with Data. A Guide to the S Language}.
  Springer. (\code{.Call}.)
}
\seealso{\code{\link{dyn.load}}.}
\keyword{programming}
\eof
\name{Formaldehyde}
\docType{data}
\alias{Formaldehyde}
\title{Determination of Formaldehyde}
\description{
  These data are from a chemical experiment to prepare a standard curve
  for the determination of formaldehyde by the addition of chromatropic
  acid and concentrated sulpuric acid and the reading of the resulting
  purple color on a spectophotometer.
}
\usage{data(Formaldehyde)}
\format{
  A data frame with 6 observations on 2 variables.
  \tabular{rlll}{
    [,1] \tab carb\tab numeric \tab Carbohydrate (ml) \cr
    [,2] \tab optden \tab numeric \tab Optical Density
  }
}
\source{
  Bennett, N. A. and N. L. Franklin (1954)
  \emph{Statistical Analysis in Chemistry and the Chemical Industry}.
  New York: Wiley.
}
\references{
  McNeil, D. R. (1977) \emph{Interactive Data Analysis.}
  New York: Wiley.
}
\examples{
data(Formaldehyde)
plot(optden ~ carb, data = Formaldehyde,
     xlab = "Carbohydrate (ml)", ylab = "Optical Density",
     main = "Formaldehyde data", col = 4, las = 1)
abline(fm1 <- lm(optden ~ carb, data = Formaldehyde))
summary(fm1)
opar <- par(mfrow = c(2,2), oma = c(0, 0, 1.1, 0))
plot(fm1)
par(opar)
}
\keyword{datasets}
\eof
\name{GammaDist}
\alias{GammaDist}
\alias{dgamma}
\alias{pgamma}
\alias{qgamma}
\alias{rgamma}
\title{The Gamma Distribution}
\description{
  Density, distribution function, quantile function and random
  generation for the Gamma distribution with parameters \code{shape} and
  \code{scale}.
}
\usage{
dgamma(x, shape, rate = 1, scale = 1/rate, log = FALSE)
pgamma(q, shape, rate = 1, scale = 1/rate, lower.tail = TRUE, log.p = FALSE)
qgamma(p, shape, rate = 1, scale = 1/rate, lower.tail = TRUE, log.p = FALSE)
rgamma(n, shape, rate = 1, scale = 1/rate)
}
\arguments{
  \item{x, q}{vector of quantiles.}
  \item{p}{vector of probabilities.}
  \item{n}{number of observations. If \code{length(n) > 1}, the length
    is taken to be the number required.}
  \item{rate}{an alternative way to specify the scale.}
  \item{shape, scale}{shape and scale parameters.}
  \item{log, log.p}{logical; if TRUE, probabilities p are given as log(p).}
  \item{lower.tail}{logical; if TRUE (default), probabilities are
    \eqn{P[X \le x]}{P[X <= x]}, otherwise, \eqn{P[X > x]}{P[X > x]}.}
}
\value{
  \code{dgamma} gives the density,
  \code{pgamma} gives the distribution function
  \code{qgamma} gives the quantile function, and
  \code{rgamma} generates random deviates.
}
\details{
  If \code{scale} is omitted, it assumes the default value of \code{1}.

  The Gamma distribution with parameters \code{shape} \eqn{=\alpha}{= a}
  and \code{scale} \eqn{=\sigma}{= s} has density
  \deqn{
    f(x)= \frac{1}{{\sigma}^{\alpha}\Gamma(\alpha)} {x}^{\alpha-1} e^{-x/\sigma}%
  }{f(x)= 1/(s^a Gamma(a)) x^(a-1) e^-(x/s)}
  for \eqn{x > 0}, \eqn{\alpha > 0}{a > 0} and \eqn{\sigma > 0}{s > 0}.
  The mean and variance are
  \eqn{E(X) = \alpha\sigma}{E(X) = a*s} and
  \eqn{Var(X) = \alpha\sigma^2}{Var(X) = a*s^2}.
}
\note{
  The S parametrization is via \code{shape} and \code{rate}: S has no
  \code{scale} parameter.  Prior to 1.4.0 \R only had \code{scale}.
  
  The cumulative hazard \eqn{H(t) = - \log(1 - F(t))}{H(t) = - log(1 - F(t))}
  is \code{-pgamma(t, ..., lower = FALSE, log = TRUE)}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{gamma}} for the Gamma function, \code{\link{dbeta}} for
  the Beta distribution and \code{\link{dchisq}} for the chi-squared
  distribution which is a special case of the Gamma distribution.
}
\examples{
-log(dgamma(1:4, shape=1))
p <- (1:9)/10
pgamma(qgamma(p,shape=2), shape=2)
1 - 1/exp(qgamma(p, shape=1))
}
\keyword{distribution}
\eof
\name{Geometric}
\alias{Geometric}
\alias{dgeom}
\alias{pgeom}
\alias{qgeom}
\alias{rgeom}
\title{The Geometric Distribution}
\description{
  Density, distribution function, quantile function and random
  generation for the geometric distribution with parameter \code{prob}.
}
\usage{
dgeom(x, prob, log = FALSE)
pgeom(q, prob, lower.tail = TRUE, log.p = FALSE)
qgeom(p, prob, lower.tail = TRUE, log.p = FALSE)
rgeom(n, prob)
}
\arguments{
  \item{x, q}{vector of quantiles representing the number of failures in
    a sequence of Bernoulli trials before success occurs.}
  \item{p}{vector of probabilities.}
  \item{n}{number of observations. If \code{length(n) > 1}, the length
    is taken to be the number required.}
  \item{prob}{probability of success in each trial.}
  \item{log, log.p}{logical; if TRUE, probabilities p are given as log(p).}
  \item{lower.tail}{logical; if TRUE (default), probabilities are
    \eqn{P[X \le x]}{P[X <= x]}, otherwise, \eqn{P[X > x]}{P[X > x]}.}
}
\value{
  \code{dgeom} gives the density,
  \code{pgeom} gives the distribution function,
  \code{qgeom} gives the quantile function, and
  \code{rgeom} generates random deviates.
}
\details{
  The geometric distribution with \code{prob} \eqn{= p} has density
  \deqn{p(x) = p {(1-p)}^{x}}{p(x) = p (1-p)^x}
  for \eqn{x = 0, 1, 2, \ldots}{x = 0, 1, 2, ...}

  If an element of \code{x} is not integer, the result of \code{pgeom}
  is zero, with a warning.

  The quantile is defined as the smallest value \eqn{x} such that
  \eqn{F(x) \ge p}, where \eqn{F} is the distribution function.
}
\seealso{
  \code{\link{dnbinom}} for the negative binomial which generalizes
  the geometric distribution.
}
\examples{
qgeom((1:9)/10, prob = .2)
Ni <- rgeom(20, prob = 1/4); table(factor(Ni, 0:max(Ni)))
}
\keyword{distribution}
\eof
\name{HairEyeColor}
\docType{data}
\alias{HairEyeColor}
\title{Hair and Eye Color of Statistics Students}
\description{
  Distribution of hair and eye color and sex in 592 statistics students.
}
\usage{data(HairEyeColor)}
\format{
  A 3-dimensional array resulting from cross-tabulating 592 observations
  on 3 variables.  The variables and their levels are as follows:

  \tabular{rll}{
    No \tab Name \tab Levels \cr
    1 \tab Hair \tab Black, Brown, Red, Blond \cr
    2 \tab Eye \tab Brown, Blue, Hazel, Green \cr
    3 \tab Sex \tab Male, Female
  }
}
\details{
  This data set is useful for illustrating various techniques for the
  analysis of contingency tables, such as the standard chi-squared test
  or, more generally, log-linear modelling, and graphical methods such
  as mosaic plots, sieve diagrams or association plots.
}
\references{
  Snee, R. D. (1974),
  Graphical display of two-way contingency tables.
  \emph{The American Statistician}, \bold{28}, 9--12.

  Friendly, M. (1992),
  Graphical methods for categorical data.
  \emph{SAS User Group International Conference Proceedings}, \bold{17},
  190--200.
  \url{http://www.math.yorku.ca/SCS/sugi/sugi17-paper.html}

  Friendly, M. (1992),
  Mosaic displays for loglinear models.
  \emph{Proceedings of the Statistical Graphics Section},
  American Statistical Association, pp. 61--68.
  \url{http://www.math.yorku.ca/SCS/Papers/asa92.html}
}
\seealso{
  \code{\link[ctest]{chisq.test}},
  \code{\link{loglin}},
  \code{\link{mosaicplot}}
}
\examples{
data(HairEyeColor)
## Full mosaic
mosaicplot(HairEyeColor)
## Aggregate over sex:
x <- apply(HairEyeColor, c(1, 2), sum)
x
mosaicplot(x, main = "Relation between hair and eye color")
}
\keyword{datasets}
\eof
%% NB: Microsoft Help Compiler often crashes on this file
%% Do not alter unless you have checked on Windows!
\name{Hershey}
\alias{Hershey}
\title{Hershey Vector Fonts in R}
\usage{
Hershey
}
\description{
  If the \code{vfont} argument to one of the text-drawing functions
  (\code{\link{text}}, \code{\link{mtext}}, \code{\link{title}},
  \code{\link{axis}}, and \code{\link{contour}}) is a character vector
  of length 2, Hershey vector fonts are used to render the text.

  These fonts have two advantages:\cr
  \enumerate{
    \item vector fonts describe each
    character in terms of a set of points;  \R renders the character by
    joining up the points with straight lines.  This intimate knowledge of
    the outline of each character means that \R can arbitrarily transform
    the characters, which can mean that the vector fonts look better
    for rotated and 3d text.
    \item this implementation was adapted from the GNU libplot library
    which provides support for non-ASCII and non-English fonts.  This means
    that it is possible, for example, to produce weird plotting symbols and
    Japanese characters.
  }

  Drawback:\cr
  You cannot use mathematical expressions (\code{\link{plotmath}}) with
  Hershey fonts.
}
\details{
  The Hershey characters are organised into a set of fonts, which are
  specified by a typeface (e.g., \code{serif} or \code{sans serif})
  and a fontindex or \dQuote{style} (e.g., \code{plain} or \code{italic}).
  The first element of \code{vfont} specifies the typeface and the second
  element specifies the fontindex.  The first table
  produced by \code{demo(Hershey)} shows the character \code{a} produced
  by each of the different fonts.

  The available \code{typeface} and \code{fontindex} values are
  available as list components of the variable \code{Hershey}.
  The allowed pairs for \code{(typeface, fontindex)} are:
%% This is checked (via max{#}) in FixupVFont() ../../../main/plot.c
%% The basic "table" really is in  ../../../modules/vfonts/g_fontdb.c

  \tabular{ll}{
    serif \tab plain \cr
    serif \tab italic \cr
    serif \tab bold \cr
    serif \tab bold italic \cr
    serif \tab cyrillic \cr
    serif \tab oblique cyrillic \cr
    serif \tab EUC \cr
    sans serif \tab plain \cr
    sans serif \tab italic \cr
    sans serif \tab bold \cr
    sans serif \tab bold italic \cr
    script \tab plain \cr
    script \tab italic \cr
    script \tab bold \cr
    gothic english \tab plain \cr
    gothic german \tab plain \cr
    gothic italian \tab plain \cr
    serif symbol \tab plain \cr
    serif symbol \tab italic \cr
    serif symbol \tab bold \cr
    serif symbol \tab bold italic \cr
    sans serif symbol \tab plain \cr
    sans serif symbol \tab italic \cr
  }
  and the indices of these are available as \code{Hershey$allowed}.

  \describe{
    \item{Escape sequences:}{The string to be drawn can include escape
      sequences, which all begin with a \code{\\}.   When \R encounters a
      \code{\\}, rather than drawing the \code{\\}, it treats the
      subsequent character(s) as a coded description of what to draw.

      One useful escape sequence (in the current context) is of the
      form: \code{\\123}.  The three digits following the \code{\\} specify an
      octal code for a character.  For example, the octal code for \code{p} is
      160 so the strings \code{"p"} and \code{"\\160"} are equivalent. This is
      useful for producing characters when there is not an appropriate key on
      your keyboard.

      The other useful escape sequences all begin with \code{\\\\}.  These are
      described below.
      Remember that backslashes have to be doubled in \R character
      strings, so they need to be entered with \emph{four} backslashes.
    }

    \item{Symbols:}{an entire string of Greek symbols can be produced by
      selecting the Serif Symbol or Sans Serif Symbol typeface.  To allow
      Greek symbols to be embedded in a string which uses a non-symbol
      typeface, there are a set of symbol escape sequences of the form
      \code{\\\\ab}. For example, the escape sequence \code{\\\\*a} produces a
      Greek alpha. The second table in \code{demo(Hershey)} shows all of the
      symbol escape sequences and the symbols that they produce.
    }

    \item{ISO Latin-1:}{further escape sequences of the form \code{\\\\ab} are
      provided for producing ISO Latin-1 characters (for example, if
      you only have a US keyboard).  Another option is to use the appropriate
      octal code.  The (non-ASCII) ISO Latin-1 characters are in the range
      241\dots377.  For example, \code{\\366} produces the character \code{o}
      with an umlaut.  The third table in \code{demo(Hershey)} shows all
      of the ISO Latin-1 escape sequences.
    }

    \item{Special Characters:}{a set of characters are provided which
      do not fall into any standard font.  These can only be accessed by
      escape sequence.  For example, \code{\\\\LI} produces the zodiac sign for
      Libra, and \code{\\\\JU} produces the astronomical sign for Jupiter.
      The fourth table in \code{demo(Hershey)} shows all of the
      special character escape sequences.
    }

    \item{Cyrillic Characters:}{cyrillic characters are implemented
      according to the K018-R encoding.  On a US keyboard, these can be
      produced using the Serif typeface and Cyrillic (or Oblique Cyrillic)
      fontindex and specifying an octal code in the range 300 to 337 for
      lower case characters or 340 to 377 for upper case characters.
      The fifth table in \code{demo(Hershey)} shows the octal codes for
      the available cyrillic characters.
    }

    \item{Japanese Characters:}{83 Hiragana, 86 Katakana, and 603 Kanji
      characters are implemented according to the EUC (Extended Unix Code)
      encoding. Each character is identified by a unique hexadecimal code.
      The Hiragana characters
      are in the range 0x2421 to 0x2473, Katakana are in the range 0x2521 to
      0x2576, and Kanji are (scattered about) in the range 0x3021 to 0x6d55.

      When using the Serif typeface and EUC
      fontindex, these characters can be produced by a \emph{pair} of octal
      codes.  Given the hexadecimal code (e.g., 0x2421), take the first two
      digits and add 0x80 and do the same to the second two digits (e.g.,
      0x21 and 0x24 become 0xa4 and 0xa1), then convert both to octal (e.g.,
      0xa4 and 0xa1 become 244 and 241).  For example, the first Hiragana
      character is produced by \code{\\244\\241}.

      It is also possible to use the hexadecimal code directly.  This works
      for all non-EUC fonts by specifying an escape sequence of the form
      \code{\\\\#J1234}.  For example, the first Hiragana character is produced
      by \code{\\\\#J2421}.

      The Kanji characters may be specified in a third way, using the
      so-called "Nelson Index", by specifying an escape sequence of the form
      \code{\\\\#N1234}.  For example, the Kanji for \dQuote{one} is
      produced by \code{\\\\#N0001}.
    
      \code{demo(Japanese)} shows the available Japanese characters.
    }
      
    \item{Raw Hershey Glyphs:}{all of the characters in the Hershey fonts
      are stored in a large array.  Some characters are not accessible in
      any of the Hershey fonts.  These characters can only be accessed via
      an escape sequence of the form \code{\\\\#H1234}.  For example, the
      fleur-de-lys is produced by \code{\\\\#H0746}.  The sixth and seventh
      tables of \code{demo(Hershey)} shows all of the available raw
      glyphs.
    }
  }
}
\references{
  \url{http://www.gnu.org/software/plotutils/plotutils.html}
}
\seealso{
  \code{demo(Hershey)}, \code{\link{text}}, \code{\link{contour}}.

  \code{\link{Japanese}} for the Japanese characters in the Hershey fonts.
}
\examples{
str(Hershey)

## for tables of examples, see demo(Hershey)
}
\keyword{aplot}
\eof
\name{Hyperbolic}
\title{Hyperbolic Functions}
\usage{
cosh(x)
sinh(x)
tanh(x)
acosh(x)
asinh(x)
atanh(x)
}
\alias{cosh}
\alias{sinh}
\alias{tanh}
\alias{acosh}
\alias{asinh}
\alias{atanh}
\description{
These functions give the obvious hyperbolic functions.
They respectively compute the hyperbolic cosine, sine, tangent,
arc-cosine, arc-sine, arc-tangent.
}
\arguments{
  \item{x}{a numeric vector}
}
\seealso{
\code{\link{cos}}, \code{\link{sin}}, \code{\link{tan}},
\code{\link{acos}}, \code{\link{asin}}, \code{\link{atan}}.
}
\keyword{math}
\eof
\name{Hypergeometric}
\alias{Hypergeometric}
\alias{dhyper}
\alias{phyper}
\alias{qhyper}
\alias{rhyper}
\title{The Hypergeometric Distribution}
\description{
  Density, distribution function, quantile function and random
  generation for the hypergeometric distribution.
}
\usage{
dhyper(x, m, n, k, log = FALSE)
phyper(q, m, n, k, lower.tail = TRUE, log.p = FALSE)
qhyper(p, m, n, k, lower.tail = TRUE, log.p = FALSE)
rhyper(nn, m, n, k)
}
\arguments{
  \item{x, q}{vector of quantiles representing the number of white balls
    drawn without replacement from an urn which contains both black and
    white balls.}
  \item{m}{the number of white balls in the urn.}
  \item{n}{the number of black balls in the urn.}
  \item{k}{the number of balls drawn from the urn.}
  \item{p}{probability, it must be between 0 and 1.}
  \item{nn}{number of observations. If \code{length(nn) > 1}, the length
    is taken to be the number required.}
  \item{log, log.p}{logical; if TRUE, probabilities p are given as log(p).}
  \item{lower.tail}{logical; if TRUE (default), probabilities are
    \eqn{P[X \le x]}{P[X <= x]}, otherwise, \eqn{P[X > x]}{P[X > x]}.}
}
\value{
  \code{dhyper} gives the density,
  \code{phyper} gives the distribution function,
  \code{qhyper} gives the quantile function, and
  \code{rhyper} generates random deviates.
}
\details{
  The hypergeometric distribution is used for sampling \emph{without}
  replacement.  The density of this distribution with parameters
  \code{m}, \code{n} and \code{k} (named \eqn{Np}, \eqn{N-Np}, and
  \eqn{n}, respectively in the reference below) is given by
  \deqn{
    p(x) = \left. {m \choose x}{n \choose k-x} \right/ {m+n \choose k}%
  }{p(x) =      choose(m, x) choose(n, k-x) / choose(m+n, k)}
  for \eqn{x = 0, \ldots, k}{x = 0, ..., k}.
}
\references{
  Johnson, N. L., Kotz, S., and Kemp, A. W. (1992)
  \emph{Univariate Discrete Distributions},
  Second Edition. New York: Wiley.
}
\examples{
m <- 10; n <- 7; k <- 8
x <- 0:(k+1)
rbind(phyper(x, m, n, k), dhyper(x, m, n, k))
all(phyper(x, m, n, k) == cumsum(dhyper(x, m, n, k)))# FALSE
## but error is very small:
signif(phyper(x, m, n, k) - cumsum(dhyper(x, m, n, k)), dig=3)
}
\keyword{distribution}
\eof
\name{IQR}
\alias{IQR}
\title{The Interquartile Range}
\usage{
IQR(x, na.rm = FALSE)
}
\description{computes interquartile range of the \code{x} values.}
\arguments{
  \item{x}{a numeric vector.}
  \item{na.rm}{logical. Should missing values be removed?}
}
\details{
  Note that this function computes the quartiles using the
  \code{\link{quantile}} function rather than following
  Tukey's recommendations,
  i.e., \code{IQR(x) = quantile(x,3/4) - quantile(x,1/4)}.

  For normally \eqn{N(m,1)} distributed \eqn{X}, the expected value of
  \code{IQR(X)} is \code{2*qnorm(3/4) = 1.3490}, i.e., for a normal-consistent
  estimate of the standard deviation, use \code{IQR(x) / 1.349}.
}
\references{
  Tukey, J. W. (1977).
  \emph{Exploratory Data Analysis.}
  Reading: Addison-Wesley.
}
\seealso{
 \code{\link{fivenum}}, \code{\link{mad}} which is more robust,
 \code{\link{range}}, \code{\link{quantile}}.
}
\examples{
data(rivers)
IQR(rivers)
}
\keyword{univar}
\keyword{robust}
\keyword{distribution}

\eof
\name{InsectSprays}
\docType{data}
\alias{InsectSprays}
\title{Effectiveness of Insect Sprays}
\description{
  The counts of insects in agricultural experimental units treated with
  different insecticides.
}
\usage{data(InsectSprays)}
\format{
  A data frame with 72 observations on 2 variables.
  \tabular{rlll}{
    [,1]  \tab count  \tab numeric  \tab Insect count\cr
    [,2]  \tab spray  \tab factor   \tab The type of spray
  }
}
\source{
  Beall, G., (1942)
  The Transformation of data from entomological field experiments,
  \emph{Biometrika}, \bold{29}, 243--262.
}
\references{
  McNeil, D. (1977) \emph{Interactive Data Analysis}.
  New York: Wiley.
}
\examples{
data(InsectSprays)
boxplot(count ~ spray, data = InsectSprays,
        xlab = "Type of spray", ylab = "Insect count",
        main = "InsectSprays data", varwidth = TRUE, col = "lightgray")
fm1 <- aov(count ~ spray, data = InsectSprays)
summary(fm1)
opar <- par(mfrow = c(2,2), oma = c(0, 0, 1.1, 0))
plot(fm1)
fm2 <- aov(sqrt(count) ~ spray, data = InsectSprays)
summary(fm2)
plot(fm2)
par(opar)
}
\keyword{datasets}
\eof
\name{Internal}
\title{Call an Internal Function}
\usage{
 .Internal(call)
}
\alias{.Internal}
\description{
\code{.Internal} performs a call to an internal code
which is built in to the \R interpreter.
Only true \R wizards should even consider using this function.
}
\arguments{
  \item{call}{a call expression}
}
\seealso{
\code{\link{.Primitive}}, \code{\link{.C}}, \code{\link{.Fortran}}.
}
\keyword{interface}
\eof
\name{Japanese}
\alias{Japanese}
\title{Japanese characters in R}
\description{
  The implementation of Hershey vector fonts provides a large number of
  Japanese characters (Hiragana, Katakana, and Kanji).
}
\details{
  Without keyboard support for typing Japanese characters, the only way
  to produce these characters is to use special escape sequences: see
  \code{\link{Hershey}}.

  For example, the Hiragana character for the sound "ka" is produced
  by \code{\\\\#J242b} and the Katakana character for this sound is
  produced by \code{\\\\#J252b}.  The Kanji ideograph for "one" is
  produced by \code{\\\\#J306c} or \code{\\\\#N0001}.

  The output from \code{demo(Japanese)} shows tables of the escape
  sequences for the available Japanese characters.
}
\seealso{
  \code{demo(Japanese)},
  \code{\link{Hershey}},
  \code{\link{text}},
  \code{\link{contour}}
}
\references{
  \url{http://www.gnu.org/software/plotutils/plotutils.html}
}
\examples{
plot(1:9, type="n", axes=FALSE, frame=TRUE, ylab="",
     main= "example(Japanese)", xlab= "using Hershey fonts")
par(cex=3)
Vf <- c("serif", "plain")
% doubled "\" -> can't execute here!
text(4, 2, "\\\\#J2438\\\\#J2421\\\\#J2451\\\\#J2473", vfont = Vf)
text(4, 4, "\\\\#J2538\\\\#J2521\\\\#J2551\\\\#J2573", vfont = Vf)
text(4, 6, "\\\\#J467c\\\\#J4b5c", vfont = Vf)
text(4, 8, "Japan", vfont = Vf)
par(cex=1)
text(8, 2, "Hiragana")
text(8, 4, "Katakana")
text(8, 6, "Kanji")
text(8, 8, "English")
}
\keyword{aplot}
\eof
\name{Last.value}
\alias{.Last.value}
\title{Value of Last Evaluated Expression}
\usage{
.Last.value
}
\description{
  The value of the internal evaluation of a top-level \R expression
  is always assigned to \code{.Last.value} (in \code{package:base})
  before further processing (e.g., printing).
}
\details{
  The value of a top-level assignment \emph{is} put in \code{.Last.value},
  unlike S.
  
  Do not assign to \code{.Last.value} in the workspace, because this
  will always mask the object of the same name in \code{package:base}.
}
\seealso{\code{\link{eval}}
}
\examples{
## These will not work correctly from example(),
## but they will in make check or if pasted in,
## as example() does not run them at the top level
gamma(1:15)          # think of some intensive calculation...
fac14 <- .Last.value # keep them

library("eda") # returns invisibly
.Last.value    # shows what library(.) above returned
\dontshow{detach("package:eda")}
}
\keyword{programming}
\eof
\name{LifeCycleSavings}
\docType{data}
\alias{LifeCycleSavings}
\title{Intercountry Life-Cycle Savings Data}
\description{
  Data on the savings ratio 1960--1970.
}
\usage{data(LifeCycleSavings)}
\format{
  A data frame with 50 observations on 5 variables.
  \tabular{rlll}{
    [,1]  \tab sr    \tab numeric  \tab aggregate personal savings \cr
    [,2]  \tab pop15 \tab numeric  \tab \% of population under 15 \cr
    [,3]  \tab pop75 \tab numeric  \tab \% of population over 75 \cr
    [,4]  \tab dpi   \tab numeric  \tab real per-capita disposable
    income \cr
    [,5]  \tab ddpi  \tab numeric  \tab \% growth rate of dpi
  }
}
\source{
  The data were obtained from Belsley, Kuh and Welsch (1980).
  They in turn obtained the data from Sterling (1977).
}
\details{
  Under the life-cycle savings hypothesis as developed by Franco
  Modigliani, the savings ratio (aggregate personal saving divided by
  disposable income) is explained by per-capita disposable income, the
  percentage rate of change in per-capita disposable income, and two
  demographic variables: the percentage of population less than 15
  years old and the percentage of the population over 75 years old.
  The data are averaged over the decade 1960--1970 to remove the
  business cycle or other short-term fluctuations. 
}
\references{
  Sterling, Arnie (1977) Unpublished BS Thesis.
  Massachusetts Institute of Technology.

  Belsley, D. A., Kuh. E. and Welsch, R. E. (1980)
  \emph{Regression Diagnostics}.
  New York: Wiley.
}
\examples{
data(LifeCycleSavings)
pairs(LifeCycleSavings, panel = panel.smooth,
      main = "LifeCycleSavings data")
fm1 <- lm(sr ~ pop15 + pop75 + dpi + ddpi, data = LifeCycleSavings)
summary(fm1)
}
\keyword{datasets}
\eof
\name{log}
\title{Logarithms and Exponentials}
\usage{
log(x, base = exp(1))
logb(x, base = exp(1))
log10(x)
log2(x)
exp(x)
expm1(x)
log1p(x)
}
\alias{log}
\alias{logb}
\alias{log1p}
\alias{log10}
\alias{log2}
\alias{exp}
\alias{expm1}
\arguments{
  \item{x}{a numeric or complex vector.}
  \item{base}{positive number.  The base with respect to which
    logarithms are computed.  Defaults to \eqn{e}=\code{exp(1)}.}
  }
\description{
  \code{log} computes natural logarithms,
  \code{log10} computes common (i.e., base 10) logarithms, and
  \code{log2} computes binary (i.e., base 2) logarithms.
  The general form \code{logb(x, base)} computes logarithms with base
  \code{base} (\code{log10} and \code{log2} are only special cases).

  \code{log1p(x)} computes \eqn{\log(1+x)}{log(1+x)} accurately also for
  \eqn{|x| \ll 1}{|x| << 1} (and less accurately when \eqn{x \approx
    -1}{x is approximately -1}).

  \code{exp} computes the exponential function.

  \code{expm1(x)} computes \eqn{\exp(x) - 1}{exp(x) - 1} accurately also for
  \eqn{|x| \ll 1}{|x| << 1}.
}
\value{
  A vector of the same length as \code{x} containing the transformed
  values.  \code{log(0)} gives \code{-Inf} (when available).
}
\note{
  \code{log} and \code{logb} are the same thing in \R, but \code{logb}
  is preferred if \code{base} is specified, for S-PLUS compatibility.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
  (for \code{log}, \code{\log10} and \code{exp}.)

  Chambers, J. M. (1998)
  \emph{Programming with Data. A Guide to the S Language}.
  Springer. (for \code{logb}.)
}
\seealso{
  \code{\link{Trig}},
  \code{\link{sqrt}},
  \code{\link{Arithmetic}}.
}
\examples{
log(exp(3))
log10(1e7)# = 7

x <- 10^-(1+2*1:9)
cbind(x, log(1+x), log1p(x), exp(x)-1, expm1(x))
}
\keyword{math}
\eof
\name{Logic}
\title{Logical Operators}
\usage{
! x
x & y
x && y
x | y
x || y
xor(x, y)
}
\alias{!}
\alias{&}
\alias{&&}
\alias{|}
\alias{||}
\alias{xor}
\alias{Logic}
\description{
  These operators act on logical vectors.
}
\arguments{
  \item{x, y}{logical vectors}
}
\details{
  \code{!} indicates logical negation (NOT).

  \code{&} and \code{&&} indicate logical AND and \code{|} and \code{||}
  indicate logical OR.  The shorter form performs elementwise
  comparisons in much the same way as arithmetic operators.  The longer
  form evaluates left to right examining only the first element of each
  vector.  Evaluation proceeds only until the result is determined.  The
  longer form is appropriate for programming control-flow and typically
  preferred in \code{\link{if}} clauses.

  \code{xor} indicates elementwise exclusive OR.

  \code{\link{NA}} is a valid logical object.  Where a component of
  \code{x} or \code{y} is \code{NA}, the result will be \code{NA} if the
  outcome is ambiguous.  In other words \code{NA & TRUE} evaluates to
  \code{NA}, but \code{NA & FALSE} evaluates to \code{FALSE}.  See the
  examples below.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{TRUE}} or \code{\link{logical}}.

  \code{\link{Syntax}} for operator precedence.
}
\examples{
y <- 1 + (x <- rpois(50, lambda=1.5) / 4 - 1)
x[(x > 0) & (x < 1)]    # all x values between 0 and 1
if (any(x == 0) || any(y == 0)) "zero encountered"

## construct truth tables :

x <- c(NA, FALSE, TRUE)
names(x) <- as.character(x)
outer(x, x, "&")## AND table
outer(x, x, "|")## OR  table
}
\keyword{logic}
\eof
\name{Logistic}
\alias{Logistic}
\alias{dlogis}
\alias{plogis}
\alias{qlogis}
\alias{rlogis}
\title{The Logistic Distribution}
\description{
  Density, distribution function, quantile function and random
  generation for the logistic distribution with parameters
  \code{location} and \code{scale}.
}
\usage{
dlogis(x, location = 0, scale = 1, log = FALSE)
plogis(q, location = 0, scale = 1, lower.tail = TRUE, log.p = FALSE)
qlogis(p, location = 0, scale = 1, lower.tail = TRUE, log.p = FALSE)
rlogis(n, location = 0, scale = 1)
}
\arguments{
  \item{x, q}{vector of quantiles.}
  \item{p}{vector of probabilities.}
  \item{n}{number of observations. If \code{length(n) > 1}, the length
    is taken to be the number required.}
  \item{location, scale}{location and scale parameters.}
  \item{log, log.p}{logical; if TRUE, probabilities p are given as log(p).}
  \item{lower.tail}{logical; if TRUE (default), probabilities are
    \eqn{P[X \le x]}{P[X <= x]}, otherwise, \eqn{P[X > x]}{P[X > x]}.}
}

\value{
  \code{dlogis} gives the density,
  \code{plogis} gives the distribution function,
  \code{qlogis} gives the quantile function, and
  \code{rlogis} generates random deviates.
}
\details{
  If \code{location} or \code{scale} are omitted, they assume the
  default values of \code{0} and \code{1} respectively.

  The Logistic distribution with \code{location} \eqn{= \mu}{= m} and
  \code{scale} \eqn{= \sigma}{= s} has distribution function
  \deqn{
    F(x) = \frac{1}{1 + e^{-(x-\mu)/\sigma}}%
  }{F(x) = 1 / (1 + exp(-(x-m)/s))}  and density
  \deqn{
    f(x)= \frac{1}{\sigma}\frac{e^{(x-\mu)/\sigma}}{(1 + e^{(x-\mu)/\sigma})^2}%
  }{f(x) = 1/s exp((x-m)/s) (1 + exp((x-m)/s))^-2.}

  It is a long-tailed distribution with mean \eqn{\mu}{m} and variance
  \eqn{\pi^2/3 \sigma^2}{pi^2 /3 s^2}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
var(rlogis(4000, 0, s = 5))# approximately (+/- 3)
pi^2/3 * 5^2
}
\keyword{distribution}
\eof
\name{Lognormal}
\alias{Lognormal}
\alias{dlnorm}
\alias{plnorm}
\alias{qlnorm}
\alias{rlnorm}
\title{The Log Normal Distribution}
\description{
  Density, distribution function, quantile function and random
  generation for the log normal distribution whose logarithm has mean
  equal to \code{meanlog} and standard  deviation equal to \code{sdlog}.
}
\usage{
dlnorm(x, meanlog = 0, sdlog = 1, log = FALSE)
plnorm(q, meanlog = 0, sdlog = 1, lower.tail = TRUE, log.p = FALSE)
qlnorm(p, meanlog = 0, sdlog = 1, lower.tail = TRUE, log.p = FALSE)
rlnorm(n, meanlog = 0, sdlog = 1)
}
\arguments{
  \item{x, q}{vector of quantiles.}
  \item{p}{vector of probabilities.}
  \item{n}{number of observations. If \code{length(n) > 1}, the length
    is taken to be the number required.}
  \item{meanlog, sdlog}{mean and standard deviation of the distribution
    on the log scale with default values of \code{0} and \code{1} respectively.}
  \item{log, log.p}{logical; if TRUE, probabilities p are given as log(p).}
  \item{lower.tail}{logical; if TRUE (default), probabilities are
    \eqn{P[X \le x]}{P[X <= x]}, otherwise, \eqn{P[X > x]}{P[X > x]}.}
}
\value{
  \code{dlnorm} gives the density,
  \code{plnorm} gives the distribution function,
  \code{qlnorm} gives the quantile function, and
  \code{rlnorm} generates random deviates.
}
\details{
  The log normal distribution has density
  \deqn{
    f(x) = \frac{1}{\sqrt{2\pi}\sigma x} e^{-(\log(x) - \mu)^2/2 \sigma^2}%
  }{f(x) = 1/(sqrt(2 pi) sigma x) e^-((log x - mu)^2 / (2 sigma^2))}
  where \eqn{\mu} and \eqn{\sigma} are the mean and standard
  deviation of the logarithm.
  The mean is \eqn{E(X) = exp(\mu + 1/2 \sigma^2)}, and the variance
  \eqn{Var(X) = exp(2\mu + \sigma^2)(exp(\sigma^2) - 1)}{%
    Var(X) = exp(2*mu + sigma^2)*(exp(sigma^2) - 1)} and
  hence the coefficient of variation is
  \eqn{\sqrt{exp(\sigma^2) - 1}}{sqrt(exp(sigma^2) - 1)} which is
    approximately \eqn{\sigma} when that is small (e.g., \eqn{\sigma < 1/2}).
%% Mode = exp(max(0, mu - sigma^2)); Median = exp(mu)
}
\note{
  The cumulative hazard \eqn{H(t) = - \log(1 - F(t))}{H(t) = - log(1 - F(t))}
  is \code{-plnorm(t, r, lower = FALSE, log = TRUE)}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{dnorm}} for the normal distribution.
}
\examples{
dlnorm(1) == dnorm(0)
}
\keyword{distribution}
\eof
\name{abs}
\title{Miscellaneous Mathematical Functions}
\usage{
abs(x)
sqrt(x)
}
\alias{abs}
\alias{sqrt}
\description{
These functions compute miscellaneous mathematical functions.
The naming follows the standard for computer languages
such as C or Fortran.
}
\arguments{
  \item{x}{a numeric vector}
}
\seealso{
\code{\link{Arithmetic}} for simple, \code{\link{log}} for logarithmic,
\code{\link{sin}} for trigonometric, and \code{\link{Special}} for
special mathematical functions.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
xx <- -9:9
plot(xx, sqrt(abs(xx)),  col = "red")
lines(spline(xx, sqrt(abs(xx)), n=101), col = "pink")
}
\keyword{math}
\eof
\name{Memory}
\alias{Memory}
\alias{mem.limits}
\title{Memory Available for Data Storage}
\description{
  Use command line options to control the memory available for \R.
}
\usage{
#ifdef unix
R --min-vsize=vl --max-vsize=vu --min-nsize=nl --max-nsize=nu
#endif
#ifdef windows
Rgui --min-vsize=vl --max-vsize=vu --min-nsize=nl --max-nsize=nu
Rterm --min-vsize=vl --max-vsize=vu --min-nsize=nl --max-nsize=nu
#endif

mem.limits(nsize = NA, vsize = NA)
}
\arguments{
  \item{vl, vu, vsize}{Heap memory in bytes.}
  \item{nl, nu, nsize}{Number of cons cells.}
}
\details{
  \R has a variable-sized workspace (from version 1.2.0). There is now
  much less need to set memory options than previously, and most
  users will never need to set these.  They are provided both as a way
  to control the overall memory usage (which can also be done
#ifdef unix
  by operating-system facilities such as \code{limit} on Unix),
#endif
#ifdef windows
  using the option \option{--max-mem-size} on Windows),
#endif
  and since setting larger values of the minima will make \R slightly
  more efficient on large tasks.

#ifdef windows
  (On Windows the \option{--max-mem-size} option sets the maximum memory
  allocation: it has a minimum allowed value of 10M.  This is intended
  to catch attempts to allocate excessive amounts of memory which may
  cause other processes to run out of resources.  The default is the
  smaller of the amount of physical RAM in the machine and 256Mb. 
  See also \code{\link{memory.limit}}.)
#endif

  To understand the options, one needs to know that \R maintains
  separate areas for fixed and variable sized objects.  The first of these
  is allocated as an array of \dQuote{\emph{cons cells}} (Lisp programmers will
  know what they are, others may think of them as the building blocks of
  the language itself, parse trees, etc.), and the second are thrown on a
  \dQuote{\emph{heap}} of \dQuote{Vcells} of 8 bytes each.  Effectively,
  the input \code{v} is rounded up to the nearest multiple of 8.

  Each cons cell occupies 28 bytes on a 32-bit machine, (usually) 56 bytes
  on a 64-bit machine.

  The \option{--*-nsize} options can be used to specify the number of
  cons cells and the \option{--*-vsize} options specify the size of the
  vector heap in bytes.  Both options must be integers or integers
  followed by \code{G}, \code{M}, \code{K}, or \code{k} meaning
  \code{Giga} (\eqn{2^{30} = 1073741824}) \emph{Mega} (\eqn{2^{20} =
    1048576}), (computer) \emph{Kilo} (\eqn{2^{10} = 1024}), or regular
  \emph{kilo} (1000).

  The \option{--min-*} options set the minimal sizes for the number of
  cons cells and for the vector heap.  These values are also the initial
  values, but thereafter \R will grow or shrink the areas depending on
  usage, but never exceeding the limits set by the \option{--max-*}
  options nor decreasing below the initial values.

  The default values are currently minima of 350k cons cells,
  6Mb of vector heap
  and no maxima (other than machine resources). The maxima can be
  changed during an \R session by calling \code{mem.limits}. (If this is
  called with the default values, it reports the current settings.)
  

  You can find out the current memory consumption (the heap and cons
  cells used as numbers and megabytes) by typing \code{\link{gc}()} at the
  \R prompt.  Note that following \code{\link{gcinfo}(TRUE)}, automatic
  garbage collection always prints memory use statistics.  Maxima will
  never be reduced below the current values for triggering garbage
  collection, and attempts to do so will be silently ignored.

%  The defaults for \option{--min-nsize} and \option{--min-vsize} can be
%  changed by setting the environment variables \env{R\_NSIZE} and
%  \env{R\_VSIZE} respectively, perhaps most conveniently in the file
%  \file{.Renviron} or \file{\eqn{\sim}{~}/.Renviron}.  There should no
%  longer be any need to do so.

  When using \code{\link{read.table}}, the memory requirements are in
  fact higher than anticipated, because the file is first read in as one
  long string which is then split again.  Use \code{\link{scan}} if
  possible in case you run out of memory when reading in a large table.
}

\value{
  (\code{mem.limits}) an integer vector giving the current settings of
  the maxima, possibly \code{NA}.
}

\seealso{
  \code{\link{gc}} for information on the garbage collector,
  \code{\link{memory.profile}} for profiling the usage of cons cells.
#ifdef windows

  \code{\link{memory.size}} to monitor total memory usage,
  \code{\link{memory.limit}} for the current limit.
#endif
}

\note{
  For backwards compatibility, options \option{--nsize} and
  \option{--vsize} are equivalent to \option{--min-nsize} and
  \option{--min-vsize}.
#ifdef windows
  
  When using the \code{Rgui} console it is simplest to make a shortcut and
  put these command-line flags at the end of the Target field.
#endif
}

\examples{
# Start R with 10MB of heap memory and 500k cons cells, limit to
# 100Mb and 1M cells
\dontrun{
## Unix
R --min-vsize=10M --max-vsize=100M --min-nsize=500k --max-nsize=1M
}
}
\keyword{environment}
\eof
\name{Multinomial}
\alias{Multinomial}
\alias{rmultinom}
\alias{dmultinom}
\title{The Multinomial Distribution}
\description{
  Generate multinomially distributed random number vectors and
  compute multinomial \dQuote{density} probabilities.
}
\usage{
rmultinom(n, size, prob)
dmultinom(x, size = NULL, prob, log = FALSE)
}
\arguments{
  \item{x}{vector of length \eqn{K} of integers in \code{0:size}.}
  %%FUTURE:  matrix of \eqn{K} rows or ...
  \item{n}{number of random vectors to draw.}
  \item{size}{integer, say \eqn{N}, specifying the total number
    of objects that are put into \eqn{K} boxes in the typical multinomial
    experiment. For \code{dmultinom}, it defaults to \code{sum(x)}.}
  \item{prob}{numeric non-negative vector of length \eqn{K}, specifying
    the probability for the \eqn{K} classes; is internally normalized to
    sum 1.}
  \item{log}{logical; if TRUE, log probabilities are computed.}
}
\note{\code{dmultinom} is currently \emph{not vectorized} at all and has
  no C interface (API); this may be amended in the future.% yes, DO THIS!
}
\details{
  If \code{x} is a $K$-component vector, \code{dmultinom(x, prob)} is
  the probability
  \deqn{P(X_1=x_1,\ldots,X_K=x_k) = C \times \prod_{j=1}^K \pi_j^{x_j}}{%
    P(X[1]=x[1],\ldots,X[K]=x[k]) = C * prod(j=1,..,K) p[j]^x[j]}
  where \eqn{C} is the \dQuote{multinomial coefficient}
  \eqn{C = N! / (x_1! \cdots x_K!)}{C = N! / (x[1]! * \dots * x[K]!)}
  and \eqn{N = \sum_{j=1}^K x_j}{N = sum(j=1,..,K) x[j]}.
  \cr
  By definition, each component \eqn{X_j}{X[j]} is binomially distributed as
  \code{Bin(size, prob[j])} for \eqn{j = 1,\ldots,K}.

  The \code{rmultinom()} algorithm draws binomials from
  \eqn{Bin(n_j,P_j)}{Bin(n[j], P[j])} sequentially, where
  \eqn{n_1 = N}{n[1] = N} (N := \code{size}),
  \eqn{P_1 = \pi_1}{P[1] = p[1]} (\eqn{\pi}{p} is \code{prob} scaled to sum 1),
  and for \eqn{j \ge 2}{j >= 2}, recursively
  \eqn{n_j = N - \sum_{k=1}^{j-1} n_k}{%
    n[j]= N - sum(k=1, .., j-1) n[k]} and
  \eqn{P_j = \pi_j / (1 - \sum_{k=1}^{j-1} \pi_k)}{%
    P[j]= p[j] / (1 - sum(p[1:(j-1)]))}.
}
\value{
  For \code{rmultinom()},
  an integer \code{K x n} matrix where each column is a random vector
  generated according to the desired multinomial law, and hence summing
  to \code{size}.  Whereas the \emph{transposed} result would seem more
  natural at first, the returned matrix is more efficient because of
  columnwise storage.
}
%%\author{Martin Maechler}
\seealso{\code{\link{rbinom}} which is a special case conceptually.
%% but does not return 2-vectors
}
\examples{
rmultinom(10, size = 12, prob=c(0.1,0.2,0.8))

pr <- c(1,3,6,10) # normalization not necessary for generation
rmultinom(10, 20, prob = pr)

## all possible outcomes of Multinom(N = 3, K = 3)
X <- t(as.matrix(expand.grid(0:3, 0:3))); X <- X[, colSums(X) <= 3]
X <- rbind(X, 3:3 - colSums(X)); dimnames(X) <- list(letters[1:3], NULL)
X
round(apply(X, 2, function(x) dmultinom(x, prob = c(1,2,5))), 3)
}
\keyword{distribution}
\eof
\name{NA}
\alias{NA}
\alias{is.na}
\alias{is.na.data.frame}
\alias{is.na<-}
\alias{is.na<-.default}
\title{Not Available / ``Missing'' Values}
\description{
  \code{NA} is a logical constant of length 1 which contains a missing
  value indicator.  \code{NA} can be freely coerced to any other vector
  type.

  The generic function \code{is.na} indicates which elements are missing.

  The generic function \code{is.na<-} sets elements to \code{NA}.
}
\usage{
NA
is.na(x)
\method{is.na}{data.frame}(x)

is.na(x) <- value
}
\arguments{
  \item{x}{an \R object to be tested.}
  \item{value}{a suitable index vector for use with \code{x}.}
}
\details{
  %% Next par on character NAs taken from R-lang.texi:
  The \code{NA} of character type is as from R 1.5.0 distinct from the
  string \code{"NA"}.  Programmers who need to specify an explicit
  string \code{NA} should use \code{as.character(NA)} rather than
  \code{"NA"}, or set elements to \code{NA} using \code{is.na<-}.

  \code{is.na(x)} works elementwise when \code{x} is a
  \code{\link{list}}. 
  The method dispatching is C-internal, rather than via
  \code{\link{UseMethod}}.

  Function \code{is.na<-} may provide a safer way to set missingness.
  It behaves differently for factors, for example.
}
\value{
  The default method for \code{is.na} returns a logical vector of the same
  \dQuote{form} as its argument \code{x}, containing \code{TRUE} for those
  elements marked \code{NA} or \code{\link{NaN}} (!) and \code{FALSE}
  otherwise.  \code{dim}, \code{dimnames} and \code{names} attributes
  are preserved.

  The method \code{is.na.data.frame} returns a logical matrix with the
  same dimensions as the data frame, and with dimnames taken from the
  row and column names of the data frame.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Chambers, J. M. (1998)
  \emph{Programming with Data. A Guide to the S Language}.
  Springer.
}
\seealso{
  \code{\link{NaN}}, \code{\link{is.nan}}, etc.,
  and the utility function \code{\link{complete.cases}}.

  \code{\link{na.action}}, \code{\link{na.omit}}, \code{\link{na.fail}}
  on how methods can be tuned to deal with missing values.
}
\examples{
is.na(c(1, NA))        #> FALSE  TRUE
is.na(paste(c(1, NA))) #> FALSE FALSE
}
\keyword{NA}
\keyword{logic}
\keyword{manip}
\eof
\name{NULL}
\title{The Null Object}
\usage{
NULL
as.null(x, \dots)
is.null(x)
}
\alias{NULL}
\alias{as.null}
\alias{as.null.default}
\alias{is.null}
\description{
\code{NULL} represents the null object in R.
NULL is used mainly to represent the lists with zero length,
and is often returned by expressions and functions whose
value is undefined.

\code{as.null} ignores its argument and returns the value \code{NULL}.

\code{is.null} returns \code{TRUE} if its argument
is \code{NULL} and \code{FALSE} otherwise.
}
\details{
  \code{is.null} is generic: you can write methods to handle
  of specific classes of objects, see \link{InternalMethods}.
}
\arguments{
  \item{x}{an object to be tested or coerced.}
  \item{\dots}{ignored.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
is.null(list())    # FALSE (on purpose!)
is.null(integer(0))# F
is.null(logical(0))# F
as.null(list(a=1,b='c'))
}
\keyword{attribute}
\keyword{manip}
\keyword{list}
\keyword{sysdata}
\eof
\name{NegBinomial}
\alias{NegBinomial}
\alias{dnbinom}
\alias{pnbinom}
\alias{qnbinom}
\alias{rnbinom}
\title{The Negative Binomial Distribution}
\description{
  Density, distribution function, quantile function and random
  generation for the negative binomial distribution with parameters
  \code{size} and \code{prob}.
}
\usage{
dnbinom(x, size, prob, mu, log = FALSE)
pnbinom(q, size, prob, mu, lower.tail = TRUE, log.p = FALSE)
qnbinom(p, size, prob, mu, lower.tail = TRUE, log.p = FALSE)
rnbinom(n, size, prob, mu)
}
\arguments{
  \item{x}{vector of (non-negative integer) quantiles.}
  \item{q}{vector of quantiles.}
  \item{p}{vector of probabilities.}
  \item{n}{number of observations. If \code{length(n) > 1}, the length
    is taken to be the number required.}
  \item{size}{target for number of successful trials, or dispersion
    parameter (the shape parameter of the gamma mixing distribution).}
  \item{prob}{probability of success in each trial.}
  \item{mu}{alternative parametrization via mean: see Details}
  \item{log, log.p}{logical; if TRUE, probabilities p are given as log(p).}
  \item{lower.tail}{logical; if TRUE (default), probabilities are
    \eqn{P[X \le x]}{P[X <= x]}, otherwise, \eqn{P[X > x]}{P[X > x]}.}
}
\value{
  \code{dnbinom} gives the density,
  \code{pnbinom} gives the distribution function,
  \code{qnbinom} gives the quantile function, and
  \code{rnbinom} generates random deviates.
}
\details{
  The negative binomial distribution with \code{size} \eqn{= n} and
  \code{prob} \eqn{= p} has density
  \deqn{
    p(x) = \frac{\Gamma(x+n)}{\Gamma(n) x!} p^n (1-p)^x}{%
    p(x) = Gamma(x+n)/(Gamma(n) x!) p^n (1-p)^x}
  for \eqn{x = 0, 1, 2, \ldots}

  This represents the number of failures
  which occur in a sequence of Bernoulli trials before a target number
  of successes is reached.

  A negative binomial distribution can arise as a mixture of Poisson
  distributions with mean distributed as a
  gamma (\code{\link{pgamma}}) distribution with scale parameter
  \code{(1 - prob)/prob} and shape parameter \code{size}.  (This
  definition allows non-integer values of \code{size}.)
  In this model \code{prob} = \code{scale/(1+scale)}, and the mean is
  \code{size * (1 - prob)/prob)}
  
  The alternative parametrization (often used in ecology) is by the
  \emph{mean} \code{mu}, and \code{size}, the \emph{dispersion parameter},
  where \code{prob} = \code{size/(size+mu)}.  In this parametrization the
  variance is \code{mu + mu^2/size}.

  If an element of \code{x} is not integer, the result of \code{dnbinom}
  is zero, with a warning.

  The quantile is defined as the smallest value \eqn{x} such that
  \eqn{F(x) \ge p}, where \eqn{F} is the distribution function.
}
\seealso{
  \code{\link{dbinom}} for the binomial, \code{\link{dpois}} for the
  Poisson and \code{\link{dgeom}} for the geometric distribution, which
  is a special case of the negative binomial.
}
\examples{
x <- 0:11
dnbinom(x, size = 1, prob = 1/2) * 2^(1 + x) # == 1
126 /  dnbinom(0:8, size  = 2, prob  = 1/2) #- theoretically integer

## Cumulative ('p') = Sum of discrete prob.s ('d');  Relative error :
summary(1 - cumsum(dnbinom(x, size = 2, prob = 1/2)) /
                  pnbinom(x, size  = 2, prob = 1/2))

x <- 0:15
size <- (1:20)/4
persp(x,size, dnb <- outer(x,size,function(x,s)dnbinom(x,s, pr= 0.4)),
      xlab = "x", ylab = "s", zlab="density", theta = 150)
title(tit <- "negative binomial density(x,s, pr = 0.4)  vs.  x & s")

image  (x,size, log10(dnb), main= paste("log [",tit,"]"))
contour(x,size, log10(dnb),add=TRUE)

## Alternative parametrization
x1 <- rnbinom(500, mu = 4, size = 1)
x2 <- rnbinom(500, mu = 4, size = 10)
x3 <- rnbinom(500, mu = 4, size = 100)
h1 <- hist(x1, breaks = 20, plot = FALSE)
h2 <- hist(x2, breaks = h1$breaks, plot = FALSE)
h3 <- hist(x3, breaks = h1$breaks, plot = FALSE)
barplot(rbind(h1$counts, h2$counts, h3$counts),
        beside = TRUE, col = c("red","blue","cyan"),
        names.arg = round(h1$breaks[-length(h1$breaks)]))
}
\keyword{distribution}
\eof
\name{Normal}
\alias{Normal}
\alias{dnorm}
\alias{pnorm}
\alias{qnorm}
\alias{rnorm}
\title{The Normal Distribution}
\description{
  Density, distribution function, quantile function and random
  generation for the normal distribution with mean equal to \code{mean}
  and standard deviation equal to \code{sd}.
}
\usage{
dnorm(x, mean=0, sd=1, log = FALSE)
pnorm(q, mean=0, sd=1, lower.tail = TRUE, log.p = FALSE)
qnorm(p, mean=0, sd=1, lower.tail = TRUE, log.p = FALSE)
rnorm(n, mean=0, sd=1)
}
\arguments{
  \item{x,q}{vector of quantiles.}
  \item{p}{vector of probabilities.}
  \item{n}{number of observations. If \code{length(n) > 1}, the length
    is taken to be the number required.}
  \item{mean}{vector of means.}
  \item{sd}{vector of standard deviations.}
  \item{log, log.p}{logical; if TRUE, probabilities p are given as log(p).}
  \item{lower.tail}{logical; if TRUE (default), probabilities are
    \eqn{P[X \le x]}{P[X <= x]}, otherwise, \eqn{P[X > x]}{P[X > x]}.}
}
\value{
  \code{dnorm} gives the density,
  \code{pnorm} gives the distribution function,
  \code{qnorm} gives the quantile function, and
  \code{rnorm} generates random deviates.
}
\details{
  If \code{mean} or \code{sd} are not specified they assume the default
  values of \code{0} and \code{1}, respectively.

  The normal distribution has density
  \deqn{
    f(x) =
    \frac{1}{\sqrt{2\pi}\sigma} e^{-(x-\mu)^2/2\sigma^2}}{
    f(x) = 1/(sqrt(2 pi) sigma) e^-((x - mu)^2/(2 sigma^2))
  }
  where \eqn{\mu}{mu} is the mean of the distribution and
  \eqn{\sigma}{sigma} the standard deviation.

  \code{qnorm} is based on Wichura's algorithm AS 241 which provides
  precise results up to about 16 digits.
}
\seealso{
  \code{\link{runif}} and \code{\link{.Random.seed}} about random number
  generation, and \code{\link{dlnorm}} for the \emph{Log}normal distribution.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Wichura, M. J. (1988)
  Algorithm AS 241: The Percentage Points of the Normal Distribution.
  \emph{Applied Statistics}, \bold{37}, 477--484.
}
\examples{
dnorm(0) == 1/ sqrt(2*pi)
dnorm(1) == exp(-1/2)/ sqrt(2*pi)
dnorm(1) == 1/ sqrt(2*pi*exp(1))

## Using "log = TRUE" for an extended range :
par(mfrow=c(2,1))
plot(function(x)dnorm(x, log=TRUE), -60, 50, main = "log { Normal density }")
curve(log(dnorm(x)), add=TRUE, col="red",lwd=2)
mtext("dnorm(x, log=TRUE)", adj=0); mtext("log(dnorm(x))", col="red", adj=1)

plot(function(x)pnorm(x, log=TRUE), -50, 10, main = "log { Normal Cumulative }")
curve(log(pnorm(x)), add=TRUE, col="red",lwd=2)
mtext("pnorm(x, log=TRUE)", adj=0); mtext("log(pnorm(x))", col="red", adj=1)

## if you want the so-called 'error function'
erf <- function(x) 2 * pnorm(x * sqrt(2)) - 1
## and the so-called 'complementary error function'
erfc <- function(x) 2 * pnorm(x * sqrt(2), lower=FALSE)
}
\keyword{distribution}
\eof
\name{OrchardSprays}
\docType{data}
\alias{OrchardSprays}
\title{Potency of Orchard Sprays}
\description{
  An experiment was conducted to assess the potency of various
  constituents of orchard sprays in repelling honeybees, using a
  Latin square design.
}
\usage{data(OrchardSprays)}
\format{
  A data frame with 64 observations on 4 variables.
  \tabular{rlll}{
    [,1]  \tab rowpos    \tab numeric \tab Row of the design\cr
    [,2]  \tab colpos    \tab numeric \tab Column of the design\cr
    [,3]  \tab treatment \tab factor  \tab Treatment level\cr
    [,4]  \tab decrease  \tab numeric \tab Response
  }
}
\details{
  Individual cells of dry comb were filled with measured amounts of lime
  sulphur emulsion in sucrose solution.  Seven different concentrations
  of lime sulphur ranging from a concentration of 1/100 to 1/1,562,500
  in successive factors of 1/5 were used as well as a solution
  containing no lime sulphur. 
  
  The responses for the different solutions were obtained by releasing
  100 bees into the chamber for two hours, and then measuring the
  decrease in volume of the solutions in the various cells.
  
  An \eqn{8 \times 8}{8 x 8} Latin square design was used and the
  treatments were coded as follows:
  \tabular{rl}{
    A \tab highest level of lime sulphur\cr
    B \tab next highest level of lime sulphur\cr
    . \tab \cr
    . \tab \cr
    . \tab \cr
    G \tab lowest level of lime sulphur\cr
    H \tab no lime sulphur
  }
}
\source{
  Finney, D. J. (1947)
  \emph{Probit Analysis}.
  Cambridge.
}
\references{
  McNeil, D. R. (1977)
  \emph{Interactive Data Analysis}.
  New York: Wiley.
}
\examples{
data(OrchardSprays)
pairs(OrchardSprays, main = "OrchardSprays data")
}
\keyword{datasets}
\eof
\name{Paren}
\alias{Paren}
\alias{(}
\alias{{}
\title{Parentheses and Braces}
\usage{
( \dots )

{ \dots }
}
\description{
  Open parenthesis, \code{(}, and open brace, \code{\{}, are
  \code{\link{.Primitive}} functions in \R.

  Effectively, \code{(} is semantically equivalent to the identity
  \code{function(x) x}, whereas \code{\{} is slightly more interesting,
  see examples.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{if}}, \code{\link{return}}, etc for other objects used in
  the \R language itself.

  \code{\link{Syntax}} for operator precedence.
}
\examples{
f <- get("(")
e <- expression(3 + 2 * 4)
f(e) == e           # TRUE

do <- get("\{")
do(x <- 3, y <- 2*x-3, 6-x-y); x; y
}
\keyword{programming}
\eof
\name{PkgUtils}
\alias{build}
\alias{check}
\title{Utilities for Building and Checking Add-on Packages}
\description{
  Utilities for checking whether the sources of an \R add-on package
  work correctly, and for building a source or binary package from
  them.
}
\usage{
#ifdef unix
R CMD build [options] pkgdirs
R CMD check [options] pkgdirs
#endif
#ifdef windows
Rcmd build [options] pkgdirs
Rcmd check [options] pkgdirs
#endif
}
\arguments{
  \item{pkgdirs}{a list of names of directories with sources of \R
    add-on packages.}
  \item{options}{further options to control the processing, or for
    obtaining information about usage and version of the utility.}
}
\details{
#ifdef unix
  \code{R CMD check}
#endif
#ifdef windows
  \code{Rcmd check}
#endif
  checks \R add-on packages from their sources, performing a wide
  variety of diagnostic checks.

#ifdef unix
  \code{R CMD build}
#endif
#ifdef windows
  \code{Rcmd build}
#endif
  builds \R source or binary packages from their sources.  It will
  create index files in the sources if necessary, so it is often helpful
  to run \code{build} before \code{check}.

  Use
#ifdef unix
  \code{R CMD foo --help}
#endif
#ifdef windows
  \code{Rcmd foo --help}
#endif
  to obtain usage information on utility \code{foo}.

  Several of the options to \code{build --binary} are passed to
  \code{\link{INSTALL}} so consult its help for the details.
}
#ifdef windows
\note{
  These may not work correctly under Windows 95/98/ME because of
  problems Perl has launching programs on those limited OSes.

  They make use of a temporary directory specified by the enironment
  variable \code{TMPDIR} and defaulting to \code{c:/TEMP}.  Do ensure
  that if set forward slashes are used.
}
#endif
\seealso{
  The chapter \dQuote{Processing Rd format} in \dQuote{Writing \R
    Extensions}
#ifdef unix
  (see the \file{doc/manual} subdirectory of the \R source tree).
#endif
#ifdef windows
  (see the Manuals sub-menu of the Help menu on the console).
#endif

  \code{\link{INSTALL}} is called by \code{build --binary}.
}
\keyword{utilities}
\eof
\name{PlantGrowth}
\docType{data}
\alias{PlantGrowth}
\title{Results from an Experiment on Plant Growth}
\description{
  Results from an experiment to compare yields (as measured by dried
  weight of plants) obtained under a control and two different treatment
  conditions.
}
\usage{data(PlantGrowth)}
\format{
  A data frame of 30 cases on 2 variables.

  \tabular{rll}{
    [, 1] \tab weight \tab numeric \cr
    [, 2] \tab group  \tab factor
  }

  The levels of \code{group} are \sQuote{ctrl}, \sQuote{trt1}, and \sQuote{trt2}.
}
\examples{
## One factor ANOVA example from Dobson's book, cf. Table 7.4:
data(PlantGrowth)
boxplot(weight ~ group, data = PlantGrowth, main = "PlantGrowth data",
        ylab = "Dried weight of plants", col = "lightgray",
        notch = TRUE, varwidth = TRUE)
anova(lm(weight ~ group, data = PlantGrowth))
}
\source{
  Dobson, A. J. (1983)
  \emph{An Introduction to Statistical Modelling}.
  London: Chapman and Hall.
}
\keyword{datasets}
\eof
\name{.Platform}
\title{Platform Specific Variables}
\usage{
.Platform
}
\alias{.Platform}
\description{
  \code{.Platform} is a list with some details of the platform under
  which \R was built.  This provides means to write OS portable \R
  code.
}
\value{
  A list with at least the following components:
  
  \item{OS.type}{
    character, giving the \bold{O}perating \bold{S}ystem
    (family) of the computer.  One of \code{"unix"} or \code{"windows"}.
  }
  \item{file.sep}{
    character, giving the \bold{file} \bold{sep}arator,
    used on your platform, e.g., \code{"/"} on Unix alikes.
  }
  \item{dynlib.ext}{
    character, giving the file name \bold{ext}ension of
    \bold{dyn}amically loadable \bold{lib}raries, e.g., \code{".dll"} on
    Windows.
  }
  \item{GUI}{
    character, giving the type of GUI in use, or
    \code{"unknown"} if no GUI can be assumed.
  }
  \item{endian}{
    character, \code{"big"} or \code{"little"}, giving the
    endianness of the processor in use.
  }
}
\seealso{
  \code{\link{R.version}} and \code{\link{Sys.info}} give more details
  about the OS.  In particular, \code{R.version$platform} is the
  canonical name of the platform under which \R was compiled.
  
  \code{\link{.Machine}} for details of the arithmetic used, and
  \code{\link{system}} for invoking platform-specific system commands.
}
\examples{
## Note: this can be done in a system-independent way by file.info()$isdir
if(.Platform$OS.type == "unix") {
   system.test <- function(...) { system(paste("test", ...)) == 0 }
   dir.exists <- function(dir) sapply(dir, function(d)system.test("-d", d))
   dir.exists(c(R.home(), "/tmp", "~", "/NO"))# > T T T F
}
}
\keyword{file}
\keyword{utilities}
\eof
\name{Poisson}
\alias{Poisson}
\alias{dpois}
\alias{ppois}
\alias{qpois}
\alias{rpois}
\title{The Poisson Distribution}
\description{
  Density, distribution function, quantile function and random
  generation for the Poisson distribution with parameter \code{lambda}.
}
\usage{
dpois(x, lambda, log = FALSE)
ppois(q, lambda, lower.tail = TRUE, log.p = FALSE)
qpois(p, lambda, lower.tail = TRUE, log.p = FALSE)
rpois(n, lambda)
}
\arguments{
  \item{x}{vector of (non-negative integer) quantiles.}
  \item{q}{vector of quantiles.}
  \item{p}{vector of probabilities.}
  \item{n}{number of random values to return.}
  \item{lambda}{vector of positive means.}
  \item{log, log.p}{logical; if TRUE, probabilities p are given as log(p).}
  \item{lower.tail}{logical; if TRUE (default), probabilities are
    \eqn{P[X \le x]}{P[X <= x]}, otherwise, \eqn{P[X > x]}{P[X > x]}.}
}
\value{
  \code{dpois} gives the (log) density,
  \code{ppois} gives the (log) distribution function,
  \code{qpois} gives the quantile function, and
  \code{rpois} generates random deviates.
}
\details{
  The Poisson distribution has density
%-- please leave the linebreaking for the next two ! --
  \deqn{p(x) = \frac{\lambda^x e^{-\lambda}}{x!}}{%
        p(x) = lambda^x exp(-lambda)/x!}
  for \eqn{x = 0, 1, 2, \ldots}.  The mean and variance are
  \eqn{E(X) = Var(X) = \lambda}.

  If an element of \code{x} is not integer, the result of \code{dpois}
  is zero, with a warning.
  \eqn{p(x)} is computed using Loader's algorithm, see the reference in
  \code{\link{dbinom}}.

  The quantile is left continuous: \code{qgeom(q, prob)} is the largest
  integer \eqn{x} such that \eqn{P(X \le x) < q}.

  Setting \code{lower.tail = FALSE} allows to get much more precise
  results when the default, \code{lower.tail = TRUE} would return 1, see
  the example below.
}
\seealso{
  \code{\link{dbinom}} for the binomial and \code{\link{dnbinom}} for
  the negative binomial distribution.
}
\examples{
-log(dpois(0:7, lambda=1) * gamma(1+ 0:7)) # == 1
Ni <- rpois(50, lam= 4); table(factor(Ni, 0:max(Ni)))

1 - ppois(10*(15:25), lambda=100)		# becomes 0 (cancellation)
    ppois(10*(15:25), lambda=100, lower=FALSE)	# no cancellation

par(mfrow = c(2, 1))
x <- seq(-0.01, 5, 0.01)
plot(x, ppois(x, 1), type="s", ylab="F(x)", main="Poisson(1) CDF")
plot(x, pbinom(x, 100, 0.01),type="s", ylab="F(x)",
     main="Binomial(100, 0.01) CDF")
}
\keyword{distribution}
\eof
\name{Primitive}
\alias{.Primitive}
\title{Call a ``Primitive'' Internal Function}
\description{
  \code{.Primitive} returns an entry point to a \dQuote{primitive}
  (internally implemented) function.

  The advantage of \code{.Primitive} over \code{\link{.Internal}}
  functions is the potential efficiency of argument passing.
}
\usage{
.Primitive(name)
}
\arguments{
  \item{name}{name of the \R function.}
}
\seealso{
  \code{\link{.Internal}}.
}
\examples{
mysqrt <- .Primitive("sqrt")
c
.Internal # this one *must* be primitive!
get("if") # just 'if' or 'print(if)' are not syntactically ok.
}
\keyword{interface}
\eof
\name{Random.user}
\title{User-supplied Random Number Generation}
\alias{Random.user}
\description{
  Function \code{\link{RNGkind}} allows user-coded uniform and
  normal random number generators to be supplied.  The details are given
  here.
}
\details{
  A user-specified uniform RNG is called from entry points in
  dynamically-loaded compiled code. The user must supply the entry point
  \code{user_unif_rand}, which takes no arguments and returns a
  \emph{pointer to} a double. The example below will show the general
  pattern.

  Optionally, the user can supply the entry point \code{user_unif_init},
  which is called with an \code{unsigned int} argument when
  \code{\link{RNGkind}} (or \code{set.seed}) is called, and is intended
  to be used to initialize the user's RNG code. The argument is intended
  to be used to set the \dQuote{seeds}; it is the \code{seed} argument to
  \code{set.seed} or an essentially random seed if \code{\link{RNGkind}}
  is called.

  If only these functions are supplied, no information about the
  generator's state is recorded in \code{.Random.seed}. Optionally,
  functions \code{user_unif_nseed} and \code{user_unif_seedloc} can be
  supplied which are called with no arguments and should return pointers
  to the number of \dQuote{seeds} and to an integer array of
  \dQuote{seeds}.  Calls 
  to \code{GetRNGstate} and \code{PutRNGstate} will then copy this array
  to and from \code{.Random.seed}.

  A user-specified normal RNG is specified by a single entry point
  \code{user_norm_rand}, which takes no arguments and returns a
  \emph{pointer to} a double.
}
\section{Warning}{As with all compiled code, mis-specifying these
  functions can crash \R.  Do include the \file{R\_ext/Random.h}
  header file for type checking.
}
\examples{\dontrun{
##  Marsaglia's conguential PRNG
#include <R_ext/Random.h>

static Int32 seed;
static double res;
static int nseed = 1;

double * user_unif_rand()
{
    seed = 69069 * seed + 1;
    res = seed * 2.32830643653869e-10;
    return &res;
}

void  user_unif_init(Int32 seed_in) { seed = seed_in; }
int * user_unif_nseed() { return &nseed; }
int * user_unif_seedloc() { return (int *) &seed; }

/*  ratio-of-uniforms for normal  */
#include <math.h>
static double x;

double * user_norm_rand()
{
    double u, v, z;
    do {
        u = unif_rand();
        v = 0.857764 * (2. * unif_rand() - 1);
        x = v/u; z = 0.25 * x * x;
        if (z < 1. - u) break;
        if (z > 0.259/u + 0.35) continue;
    } while (z > -log(u));
    return &x;
}

## Use under Unix:
R SHLIB urand.c
R
> dyn.load("urand.so")
> RNGkind("user")
> runif(10)
> .Random.seed
> RNGkind(, "user")
> rnorm(10)
> RNGkind()
[1] "user-supplied" "user-supplied"
}}
\keyword{distribution}
\keyword{sysdata}
\eof
\name{Random}
\alias{.Random.seed}
\alias{RNG}
\alias{RNGkind}
\alias{RNGversion}
\alias{set.seed}
\title{Random Number Generation}
\description{
  \code{.Random.seed} is an integer vector, containing the random number
  generator (RNG) \bold{state} for random number generation in \R.  It
  can be saved and restored, but should not be altered by the user.

  \code{RNGkind} is a more friendly interface to query or set the kind
  of RNG in use.

  \code{RNGversion} can be used to set the random generators as they
  were in an earlier \R version (for reproducibility).
  
  \code{set.seed} is the recommended way to specify seeds.
}
\usage{
.Random.seed <- c(rng.kind, n1, n2, \dots)
save.seed <- .Random.seed

RNGkind(kind = NULL, normal.kind = NULL)
RNGversion(vstr)
set.seed(seed, kind = NULL)
}
\arguments{
  \item{kind}{character or \code{NULL}.  If \code{kind} is a character
    string, set \R's RNG to the kind desired. If it is \code{NULL},
    return the currently used RNG. Use \code{"default"} to return to the
    \R default.}
  \item{normal.kind}{character string or \code{NULL}.  If it is a character
    string, set the method of Normal generation. Use \code{"default"}
    to return to the \R default.}
  \item{seed}{a single value, interpreted as an integer.}
  \item{vstr}{a character string containing a version number,
    e.g., \code{"1.6.2"}}
  \item{rng.kind}{integer code in \code{0:k} for the above \code{kind}.}
  \item{n1, n2, \dots}{integers. See the details for how many are required
    (which depends on \code{rng.kind}).}
}
\details{
  %% source and more detailed references:  ../../../main/RNG.c
  The currently available RNG kinds are given below.  \code{kind} is
  partially matched to this list.  The default is
  \code{"Mersenne-Twister"}.
  \describe{
    \item{\code{"Wichmann-Hill"}}{
    The seed, \code{.Random.seed[-1] == r[1:3]} is an integer vector of
    length 3, where each \code{r[i]} is in \code{1:(p[i] - 1)}, where
    \code{p} is the length 3 vector of primes, \code{p = (30269, 30307,
      30323)}.
    The Wichmann--Hill generator has a cycle length of
    \eqn{6.9536 \times 10^{12}}{6.9536e12} (=
    \code{prod(p-1)/4}, see \emph{Applied Statistics} (1984)
    \bold{33}, 123 which corrects the original article).}

    \item{\code{"Marsaglia-Multicarry"}:}{
    A \emph{multiply-with-carry} RNG is used, as recommended by George
    Marsaglia in his post to the mailing list \file{sci.stat.math}.
    It has a period of more than \eqn{2^{60}}{2^60} and has passed
    all tests (according to Marsaglia).  The seed is two integers (all
    values allowed).}

    \item{\code{"Super-Duper"}:}{
    Marsaglia's famous Super-Duper from the 70's.  This is the original
    version which does \emph{not} pass the MTUPLE test of the Diehard
    battery.  It has a period of \eqn{\approx 4.6\times 10^{18}}{about
      4.6*10^18} for most initial seeds.  The seed is two integers (all
    values allowed for the first seed: the second must be odd).

    We use the implementation by Reeds et al.\ (1982--84).

    The two seeds are the Tausworthe and congruence long integers,
    respectively.  A one-to-one mapping to S's \code{.Random.seed[1:12]}
    is possible but we will not publish one, not least as this generator
    is \bold{not} exactly the same as that in recent versions of S-PLUS.}

    \item{\code{"Mersenne-Twister":}}{
      From Matsumoto and Nishimura (1998). A twisted GFSR with period
      \eqn{2^{19937} - 1}{2^19937 - 1} and equidistribution in 623
      consecutive dimensions (over the whole period).  The \dQuote{seed} is a
      624-dimensional set of 32-bit integers plus a current position in
      that set.
    }

    \item{\code{"Knuth-TAOCP":}}{
      From Knuth (1997).  A GFSR using lagged Fibonacci sequences with
      subtraction. That is, the recurrence used is
      \deqn{X_j = (X_{j-100} - X_{j-37}) \bmod 2^{30}%
      }{X[j] = (X[j-100] - X[j-37]) mod 2^30}
      and the \dQuote{seed} is the set of the 100 last numbers (actually
      recorded as 101 numbers, the last being a cyclic shift of the
      buffer).  The period is around \eqn{2^{129}}{2^129}.
      }

    \item{\code{"Knuth-TAOCP-2002":}}{
      The 2002 version which not backwards compatible with the earlier
      version: the initialization of the GFSR from the seed was altered.
      \R did not allow you to choose consecutive
      seeds, the reported \sQuote{weakness}, and already scrambled the seeds.
    }

    \item{\code{"user-supplied":}}{
    Use a user-supplied generator. See \code{\link{Random.user}} for details.
    }
  }

  \code{normal.kind} can be \code{"Kinderman-Ramage"}, 
  \code{"Buggy Kinderman-Ramage"},
  \code{"Ahrens-Dieter"}, \code{"Box-Muller"}, \code{"Inversion"} (the
  default), or
  \code{"user-supplied"}.  (For inversion, see the reference in
  \code{\link{qnorm}}.) The Kinderman-Ramage generator used in versions prior
  to 1.7.1 had several approximation errors and should only be used for
  reproduction of older results.

  \code{set.seed} uses its single integer argument to set as many seeds
  as are required.  It is intended as a simple way to get quite different
  seeds by specifying small integer arguments, and also as a way to get
  valid seed sets for the more complicated methods (especially
  \code{"Mersenne-Twister"} and \code{"Knuth-TAOCP"}).
}
\note{
  Initially, there is no seed;	a new one is created from the current
  time when one is required.  Hence, different sessions will give
  different simulation results, by default.

  \code{.Random.seed} saves the seed set for the uniform random-number
  generator, at least for the system generators.  It does not
  necessarily save the state of other generators, and in particular does
  not save the state of the Box--Muller normal generator.  If you want
  to reproduce work later, call \code{set.seed} rather than set
  \code{.Random.seed}.

  As from \R 1.8.0, \code{.Random.seed} is only looked for in the user's
  workspace.
}
\value{
  \code{.Random.seed} is an \code{\link{integer}} vector whose first
  element \emph{codes} the kind of RNG and normal generator. The lowest
  two decimal digits are in \code{0:(k-1)}
  where \code{k} is the number of available RNGs. The hundreds
  represent the type of normal generator (starting at \code{0}).

  In the underlying C, \code{.Random.seed[-1]} is \code{unsigned};
  therefore in \R \code{.Random.seed[-1]} can be negative.

  \code{RNGkind} returns a two-element character vector of the RNG and
  normal kinds in use \emph{before} the call, invisibly if either
  argument is not \code{NULL}. \code{RNGversion} returns the same
  information.

  \code{set.seed} returns \code{NULL}, invisibly.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole. (\code{set.seed}, storing in \code{.Random.seed}.)

  Wichmann, B. A.  and Hill, I. D. (1982)
  \emph{Algorithm AS 183: An Efficient and Portable Pseudo-random Number
    Generator}, Applied Statistics, \bold{31}, 188--190; Remarks:
  \bold{34}, 198 and \bold{35}, 89.

  De Matteis, A. and Pagnutti, S. (1993)
  \emph{Long-range Correlation Analysis of the Wichmann-Hill Random
      Number Generator}, Statist. Comput., \bold{3}, 67--70.

  Marsaglia, G. (1997) \emph{A random number generator for C.} Discussion
  paper, posting on Usenet newsgroup \code{sci.stat.math} on
  September 29, 1997.

  Reeds, J., Hubert, S. and Abrahams, M. (1982--4) C implementation of
  SuperDuper, University of California at Berkeley.  (Personal
  communication from Jim Reeds to Ross Ihaka.)

  Marsaglia, G. and Zaman, A. (1994) Some portable very-long-period
  random number generators. \emph{Computers in Physics}, \bold{8},
  117--121.

  Matsumoto, M. and Nishimura, T. (1998)
  Mersenne Twister: A 623-dimensionally equidistributed uniform
  pseudo-random number generator,
  \emph{ACM Transactions on Modeling and Computer Simulation},
  \bold{8}, 3--30.\cr
  Source code at \url{http://www.math.keio.ac.jp/~matumoto/emt.html}.

  Knuth, D. E. (1997)
  \emph{The Art of Computer Programming.} Volume 2, third edition.\cr
  Source code at \url{http://www-cs-faculty.stanford.edu/~knuth/taocp.html}.

  Knuth, D. E. (2002)
  \emph{The Art of Computer Programming.} Volume 2, third edition, ninth
  printing.\cr
  See \url{http://Sunburn.Stanford.EDU/~knuth/news02.html}.


  Kinderman, A. J. and Ramage, J. G. (1976)
  Computer generation of normal random variables.
  \emph{Journal of the American Statistical Association} \bold{71},
  893-896.

  Ahrens, J.H. and Dieter, U. (1973)
  Extensions of Forsythe's method for random sampling from the normal
  distribution.
  \emph{Mathematics of Computation} \bold{27}, 927-937.

  Box, G.E.P. and Muller, M.E. (1958) A note on the generation of normal
  random deviates. \emph{Annals of Mathmatical Statistics} \bold{29},
  610--611.
}
\author{of RNGkind: Martin Maechler. Current implementation, B. D. Ripley}

\seealso{\code{\link{runif}}, \code{\link{rnorm}}, \ldots.}
%	this is ./Uniform.Rd
\examples{
runif(1); .Random.seed; runif(1); .Random.seed
## If there is no seed, a "random" new one is created:
rm(.Random.seed); runif(1); .Random.seed

RNGkind("Wich")# (partial string matching on 'kind')

## This shows how 'runif(.)' works for Wichmann-Hill,
## using only R functions:

p.WH <- c(30269, 30307, 30323)
a.WH <- c(  171,   172,   170)
next.WHseed <- function(i.seed = .Random.seed[-1])
  { (a.WH * i.seed) \%\% p.WH }
my.runif1 <- function(i.seed = .Random.seed)
  { ns <- next.WHseed(i.seed[-1]); sum(ns / p.WH) \%\% 1 }
rs <- .Random.seed
(WHs <- next.WHseed(rs[-1]))
u <- runif(1)
stopifnot(
 next.WHseed(rs[-1]) == .Random.seed[-1],
 all.equal(u, my.runif1(rs))
)

## ----
.Random.seed
ok <- RNGkind()
RNGkind("Super")#matches  "Super-Duper"
RNGkind()
.Random.seed # new, corresponding to  Super-Duper

## Reset:
RNGkind(ok[1])
}
\keyword{distribution}
\keyword{sysdata}
\eof
\name{RdUtils}
\alias{Rdconv}
\alias{Rd2txt}
\alias{Rd2dvi}
\alias{Sd2Rd}
\title{Utilities for Processing Rd Files}
\description{
  Utilities for converting files in R documentation (Rd) format to other
  formats or create indices from them, and for converting documentation
  in other formats to Rd format.
}
\usage{
#ifdef unix
R CMD Rdconv [options] file
R CMD Rd2dvi [options] files
R CMD Rd2txt [options] file
R CMD Sd2Rd [options] file
#endif
#ifdef windows
Rcmd Rdconv [options] file
Rcmd Rd2dvi.sh [options] files
Rcmd Rd2txt [options] file
Rcmd Sd2Rd [options] file
#endif
}
\arguments{
  \item{file}{the path to a file to be processed.}
  \item{files}{a list of file names specifying the R documentation
    sources to use, by either giving the paths to the files, or the path
    to a directory with the sources of a package.}
  \item{options}{further options to control the processing, or for
    obtaining information about usage and version of the utility.}
}
\details{
  \code{Rdconv} converts Rd format to other formats.  Currently,
  plain text, HTML, LaTeX, S version 3 (Sd), and S version 4 (.sgml)
  formats are supported.  It can also extract the examples for
  run-time testing.

  \code{Rd2dvi} and \code{Rd2txt} are user-level programs
  for producing DVI/PDF output or pretty text output from Rd sources.

  \code{Sd2Rd} converts S (version 3 or 4) documentation formats to Rd
  format.

  Use
#ifdef unix
  \code{R CMD foo --help}
#endif
#ifdef windows
  \code{Rcmd foo --help}
#endif
  to obtain usage information on utility \code{foo}.  
}
\note{
  Conversion to S version 3/4 formats is rough: there are some
  \code{.Rd} constructs for which there is no natural analogue.
  They are intended as a starting point for hand-tuning.
}
\seealso{
  The chapter \dQuote{Processing Rd format} in \dQuote{Writing \R
    Extensions}
#ifdef unix
  (see the \file{doc/manual} subdirectory of the \R source tree).
#endif
#ifdef windows
  (see the Manuals sub-menu of the Help menu on the console).
#endif
}
\keyword{utilities}
\eof
\name{Recall}
\alias{Recall}
\title{Recursive Calling}
\usage{
Recall(\dots)
}
\arguments{
  \item{\dots}{all the arguments to be passed.}
}
\description{
  \code{Recall} is used as a placeholder for the name of the function
  in which it is called.  It allows the definition of recursive
  functions which still work after being renamed, see example below.
}
% \details{
% 
% }
\seealso{\code{\link{do.call}} and \code{\link{call}}.}
\examples{
## A trivial (but inefficient!) example:
fib <- function(n) if(n<=2) {if(n>=0) 1 else 0} else Recall(n-1) + Recall(n-2)
fibonacci <- fib; rm(fib)
## renaming wouldn't work without Recall
fibonacci(10) # 55
}
\keyword{programming}

\eof
\name{R.home}
\alias{R.home}
\title{Return the R Home Directory}
\description{
 Return the \R home directory.
}
\usage{
R.home()
}
\value{
  A character string giving the current home directory.
}
\keyword{utilities}
\eof
\name{Round}
\title{Rounding of Numbers}
\usage{
ceiling(x)
floor(x)
round(x, digits = 0)
signif(x, digits = 6)
trunc(x)
zapsmall(x, digits= getOption("digits"))
}
\alias{ceiling}
\alias{floor}
\alias{round}
\alias{signif}
\alias{trunc}
\alias{zapsmall}
\description{
  \code{ceiling} takes a single numeric argument \code{x} and returns a
  numeric vector containing the smallest integers not less than the
  corresponding elements of \code{x}.

  \code{floor} takes a single numeric argument \code{x} and returns a
  numeric vector containing the largest integers not greater than the
  corresponding elements of \code{x}.

  \code{round} rounds the values in its first argument to the specified
  number of decimal places (default 0).
  Note that for rounding off a 5, the IEEE standard is used,
  \dQuote{\emph{go to the even digit}}.
  Therefore \code{round(0.5)} is \code{0} and \code{round(-1.5)} is \code{-2}.

  \code{signif} rounds the values in its first argument to the specified
  number of significant digits.

  \code{trunc} takes a single numeric argument \code{x} and returns a
  numeric vector containing the integers by truncating the values in
  \code{x} toward \code{0}.

  \code{zapsmall} determines a \code{digits} argument \code{dr} for
  calling \code{round(x, digits = dr)} such that values \dQuote{close to
    zero} values are \dQuote{zapped}, i.e., treated as \code{0}.
}
\arguments{
  \item{x}{a numeric vector.}
  \item{digits}{integer indicating the precision to be used.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole. (except \code{zapsmall}.)

  Chambers, J. M. (1998)
  \emph{Programming with Data. A Guide to the S Language}.
  Springer. (\code{zapsmall}.)
}
\seealso{
  \code{\link{as.integer}}.
}
\examples{
round(.5 + -2:4) # IEEE rounding: -2  0  0  2  2  4  4
( x1 <- seq(-2, 4, by = .5) )
round(x1)#-- IEEE rounding !
x1[trunc(x1) != floor(x1)]
x1[round(x1) != floor(x1 + .5)]
(non.int <- ceiling(x1) != floor(x1))

x2 <- pi * 100^(-1:3)
round(x2, 3)
signif(x2, 3)

print   (x2 / 1000, digits=4)
zapsmall(x2 / 1000, digits=4)
zapsmall(exp(1i*0:4*pi/2))
}
\keyword{arith}
\eof
\name{Rprof}
\alias{Rprof}
\title{Enable Profiling of R's Execution}
\description{
  Enable or disable profiling of the execution of \R expressions.
}
\usage{
Rprof(filename = "Rprof.out", append = FALSE, interval = 0.02)
}
\arguments{
  \item{filename}{
    The file to be used for recording the profiling results.
    Set to \code{NULL} or \code{""} to disable profiling.
  }
  \item{append}{
    logical: should the file be over-written or appended to?
  }
  \item{interval}{
    real: time interval between samples.
  }
}
\details{
  Enabling profiling automatically disables any existing profiling to
  another or the same file.
  
  Profiling works by writing out the call stack every \code{interval}
  seconds, to the file specified. Either the \code{\link{summaryRprof}}
#ifdef windows
  function or the Perl script \code{Rcmd Rprof}
  can be used to process the output file to produce a summary of the
  usage; use \code{Rcmd Rprof --help} for usage information.
#endif
#ifdef unix
  function or the Perl script \code{R CMD Rprof} can be used to process
  the output file to produce a summary of the
  usage; use \code{R CMD Rprof --help} for usage information.
#endif

#ifdef windows
  Exactly what the time interval measures is subtle: it is time that the
  \R process is running and executing an \R command.  It is not however just
  CPU time, for if \code{readline()} is waiting for input, that counts
  (on Windows, but not on Unix).

  Note that the timing interval cannot be too small, for the time spent
  in each profiling step is added to the interval.  What is feasible is
  machine-dependent, but 10ms seems as small as advisable on a 1GHz machine.
#endif
#ifdef unix
  Note that the timing interval cannot be too small: once the timer goes
  off, the information is not recorded until the next clock tick
  (probably every 10msecs).  Thus the interval is rounded to the nearest
  integer number of clock ticks, and is made to be at least one clock
  tick (at which resolution the total time spent is liable to be
  underestimated).
#endif
}
\note{
#ifdef windows
  Using \code{Rcmd Rprof} needs Windows Perl to be installed.
#endif
#ifdef unix
  Profiling is not available on all platforms.  By default, it is
  attempted to compile support for profiling.  Configure \R with
  \option{--disable-R-profiling} to change this.

  As \R profiling uses the same mechanisms as C profiling, the two
  cannot be used together, so do not use \code{Rprof} in an executable
  built for profiling.
#endif
}
\seealso{
  The chapter on \dQuote{Tidying and profiling R code} in
  \dQuote{Writing \R Extensions} (see the \file{doc/manual} subdirectory
  of the \R source tree).

  \code{\link{summaryRprof}}
}
\examples{
\dontrun{Rprof()
## some code to be profiled
Rprof(NULL)
## some code NOT to be profiled
Rprof(append=TRUE)
## some code to be profiled
Rprof(NULL)
\dots
## Now post-process the output as described in Details
}}
\keyword{utilities}
\eof
\name{SignRank}
\alias{SignRank}
\alias{dsignrank}
\alias{psignrank}
\alias{qsignrank}
\alias{rsignrank}
\title{Distribution of the Wilcoxon Signed Rank Statistic}
\description{
  Density, distribution function, quantile function and random
  generation for the distribution of the Wilcoxon Signed Rank statistic
  obtained from a sample with size \code{n}.
}
\usage{
dsignrank(x, n, log = FALSE)
psignrank(q, n, lower.tail = TRUE, log.p = FALSE)
qsignrank(p, n, lower.tail = TRUE, log.p = FALSE)
rsignrank(nn, n)
}
\arguments{
  \item{x,q}{vector of quantiles.}
  \item{p}{vector of probabilities.}
  \item{nn}{number of observations. If \code{length(nn) > 1}, the length
    is taken to be the number required.}
  \item{n}{numbers of observations in the sample.  Must be positive
    integers less than 50.}
  \item{log, log.p}{logical; if TRUE, probabilities p are given as log(p).}
  \item{lower.tail}{logical; if TRUE (default), probabilities are
    \eqn{P[X \le x]}{P[X <= x]}, otherwise, \eqn{P[X > x]}{P[X > x]}.}
}
\value{
  \code{dsignrank} gives the density,
  \code{psignrank} gives the distribution function,
  \code{qsignrank} gives the quantile function, and
  \code{rsignrank} generates random deviates.
}
\details{
  This distribution is obtained as follows.  Let \code{x} be a sample of
  size \code{n} from a continuous distribution symmetric about the
  origin.  Then the Wilcoxon signed rank statistic is the sum of the
  ranks of the absolute values \code{x[i]} for which \code{x[i]} is
  positive.  This statistic takes values between \eqn{0} and
  \eqn{n(n+1)/2}, and its mean and variance are \eqn{n(n+1)/4} and
  \eqn{n(n+1)(2n+1)/24}, respectively.
}
\author{Kurt Hornik \email{hornik@ci.tuwien.ac.at}}
\seealso{\code{\link{dwilcox}} etc, for the \emph{two-sample} Wilcoxon
    rank sum statistic.}
\examples{
par(mfrow=c(2,2))
for(n in c(4:5,10,40)) {
  x <- seq(0, n*(n+1)/2, length=501)
  plot(x, dsignrank(x,n=n), type='l', main=paste("dsignrank(x,n=",n,")"))
}
}
\keyword{distribution}
\eof
\name{Special}
\alias{Special}
\alias{beta}
\alias{lbeta}
\alias{gamma}
\alias{lgamma}
\alias{digamma}
\alias{trigamma}
\alias{tetragamma}
\alias{pentagamma}
\alias{choose}
\alias{lchoose}
\title{Special Functions of Mathematics}
\description{
  Special mathematical functions related to the beta and gamma
  functions.
}
\usage{
beta(a, b)
lbeta(a, b)
gamma(x)
lgamma(x)
digamma(x)
trigamma(x)
tetragamma(x)
pentagamma(x)
choose(n, k)
lchoose(n, k)
}
\arguments{
  \item{a, b, x}{numeric vectors.}
  \item{n, k}{integer vectors.}
}
\details{
%---- This should be improved! ---  want mathematical definitions
%----   AND References to Abramowitz and Stegun
  The functions \code{beta} and \code{lbeta} return the beta function
  and the natural logarithm of the beta function,
  \deqn{B(a,b) = \frac{\Gamma(a)\Gamma(b)}{\Gamma(a+b)}.}{%
        B(a,b) = (Gamma(a)Gamma(b))/(Gamma(a+b)).}

  The functions \code{gamma} and \code{lgamma} return the gamma function
  \eqn{\Gamma(x)} and the natural logarithm of the absolute value of the
  gamma function.

  The functions \code{digamma}, \code{trigamma}, \code{tetragamma} and
  \code{pentagamma} return the first, second, third and fourth
  derivatives of the logarithm of the gamma function.
  \deqn{\code{digamma(x)} = \psi(x) = \frac{d}{dx}\ln\Gamma(x) =
    \frac{\Gamma'(x)}{\Gamma(x)}}{%
    \code{digamma(x)} = psi(x) = d/dx {ln Gamma(x)} = Gamma'(x) / Gamma(x)}

  The functions \code{choose} and \code{lchoose} return binomial
  coefficients and their logarithms.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole. (for \code{gamma} and \code{lgamma}.)

  Abramowitz, M. and Stegun, I. A. (1972)
  \emph{Handbook of Mathematical Functions.} New York: Dover.
  Chapter 6: Gamma and Related Functions.
}
\seealso{
  \code{\link{Arithmetic}} for simple, \code{\link{sqrt}} for
  miscellaneous mathematical functions and \code{\link{Bessel}} for the
  real Bessel functions.
}
\examples{
choose(5, 2)
for (n in 0:10) print(choose(n, k = 0:n))

## gamma has discontinuities are 0, -1, -2, ...
\dontrun{## use plots of points to show this.
curve(gamma(x),-3,4, n=1001, ylim=c(-10,100),
      col="red", lwd=2, main="gamma(x)")
abline(h=0,v=0, lty=3, col="midnightblue")}

x <- seq(.1, 4, length = 201); dx <- diff(x)[1]
par(mfrow = c(2, 3))
for (ch in c("", "l","di","tri","tetra","penta")) {
  is.deriv <- nchar(ch) >= 2
  if (is.deriv) dy <- diff(y) / dx
  nm <- paste(ch, "gamma", sep = "")
  y <- get(nm)(x)
  plot(x, y, type = "l", main = nm, col = "red")
  abline(h = 0, col = "lightgray")
  if (is.deriv) lines(x[-1], dy, col = "blue", lty = 2)
}
}
\keyword{math}
\eof
\name{Startup}
\alias{Startup}
\alias{Rprofile}
\alias{.Rprofile}
\alias{Rprofile.site}
\alias{Renviron.site}
\alias{.Renviron}
\alias{.First}
\alias{.First.sys}
\title{Initialization at Start of an R Session}
\usage{
.First <- function() { \dots\dots }

.Rprofile <startup file>
}
\description{
  In \R, the startup mechanism is as follows.

  Unless \option{--no-environ} was given on the command line, \R
  searches for user and site files to process for setting environment
  variables.  The name of the site file is the one pointed to by the
  environment variable \env{R\_ENVIRON}; if this is unset or empty,
  \file{\$R\_HOME/etc/Renviron.site} is used (if it exists, which it
  does not in a \dQuote{factory-fresh} installation).
  The user files searched for are \file{.Renviron} in the current or in
  the user's home directory (in that order).
  See \bold{Details} for how the files are read.

  Then \R searches for the site-wide startup profile unless the command
  line option \option{--no-site-file} was given.  The name of this file
  is taken from the value of the \env{R\_PROFILE} environment variable.
  If this variable is unset, the default is
  \file{\$R\_HOME/etc/Rprofile.site}, which is used if it exists
  (which it does not in a \dQuote{factory-fresh} installation).
  This code is loaded into package \pkg{base}.  Users need to be
  careful not to unintentionally overwrite objects in base, and it
  is normally advisable to use \code{\link{local}} if code needs to be
  executed: see the examples.

  Then, unless \option{--no-init-file} was given, \R searches for a file
  called \file{.Rprofile} in the current directory or in the user's
  home directory (in that order) and sources it into the user
  workspace.

  It then loads a saved image of the user workspace from \file{.RData}
  if there is one (unless \option{--no-restore-data} was specified, or
  \option{--no-restore}, on the command line).

  Next, if a function \code{.First} is found on the search path,
  it is executed as \code{.First()}.
  Finally, function \code{.First.sys()} in the \pkg{base} package is run.
  This calls \code{\link{require}} to attach the default packages
  specified by \code{\link{options}("defaultPackages")}.

  A function \code{.First} (and \code{\link{.Last}}) can be defined in
  appropriate \file{.Rprofile} or \file{Rprofile.site} files or have
  been saved in \file{.RData}.  If you want a different set of packages
  than the default ones when you start, insert a call to
  \code{\link{options}} in the \file{.Rprofile} or \file{Rprofile.site}
  file.  For example, \code{options(defaultPackages = character())} will
  attach no extra packages on startup.  Alternatively, set
  \code{R_DEFAULT_PACKAGES=NULL} as an environment variable before
  running \R.  Using \code{options(defaultPackages = "")} or
  \code{R_DEFAULT_PACKAGES=""} enforces the R \emph{system} default.

  The commands history is read from the file specified by the
  environment variable \env{R\_HISTFILE} (default \file{.Rhistory})
  unless \option{--no-restore-history} was specified (or
  \option{--no-restore}).

  The command-line flag \option{--vanilla} implies
  \option{--no-site-file}, \option{--no-init-file},
  \option{--no-restore} and \option{--no-environ}.
}
\details{
  Note that there are two sorts of files used in startup:
  \emph{environment files} which contain lists of environment variables
  to be set, and \emph{profile files} which contain \R code.

  Lines in a site or user environment file should be either comment
  lines starting with \code{#}, or lines of the form \code{name=value}.
  The latter sets the environmental variable \code{name} to
  \code{value}, overriding an existing value.  If \code{value} is of the
  form \code{${foo-bar}}, the value is that of the environmental
  variable \code{foo} if that exists and is set to a non-empty value,
  otherwise \code{bar}.  This construction can be nested, so
  \code{bar} can be of the same form (as in \code{${foo-${bar-blah}}}).

  Leading and trailing white space in \code{value} are stripped.
%  No other interpretation of \code{value} is performed. In particular,
%  if it is enclosed in quotes, the quotes form part of the value.
  \code{value} is processed in a similar way to a Unix shell.  In particular
  quotes are stripped, and backslashes are removed except inside quotes.
}
#ifdef unix
\note{
  The file \file{\$R\_HOME/etc/Renviron} is always read very early in
  the start-up processing.  It contains environment variables set by \R
  in the configure process.  Values in that file can be overriden in
  site or user environment files: do not change
  \file{\$R\_HOME/etc/Renviron} itself.
}
#endif
\section{Historical notes}{
  Prior to \R version 1.4.0, the environment files searched were
  \file{.Renviron} in the current directory, the file pointed to by
  \env{R\_ENVIRON} if set, and \file{.Renviron} in the user's home
  directory.

  Prior to \R version 1.2.1, \file{.Rprofile} was sourced after
  \file{.RData} was loaded, although the documented order was as here.

  The format for site and user environment files was changed in version
  1.2.0.  Older files are quite likely to work but may generate warnings
  on startup if they contained unnecessary \code{export} statements.

  Values in environment files were not processed prior to version
  1.4.0.
}
\seealso{
  \code{\link{.Last}} for final actions before termination.

  For profiling code, see \code{\link{Rprof}}.
}
\examples{
\dontrun{
# Example ~/.Renviron on Unix
R_LIBS=~/R/library
PAGER=/usr/local/bin/less

# Example .Renviron on Windows
R_LIBS=C:/R/library
MY_TCLTK=yes
TCL_LIBRARY=c:/packages/Tcl/lib/tcl8.4

# Example of .Rprofile
options(width=65, digits=5)
options(show.signif.stars=FALSE)
ps.options(horizontal=FALSE)
set.seed(1234)
.First <- function() cat("\n   Welcome to R!\n\n")
.Last <- function()  cat("\n   Goodbye!\n\n")

# Example of Rprofile.site
local({
  old <- getOption("defaultPackages")
  options(defaultPackages = c(old, "MASS"))
})

## if .Renviron contains
FOOBAR="coo\bar"doh\\ex"abc\"def'"

## then we get
> cat(Sys.getenv("FOOBAR"), "\n")
coo\bardoh\exabc"def'
}}
\keyword{environment}
\eof
\name{Syntax}
\alias{Syntax}
\title{Operator Syntax}
\description{
  Outlines \R syntax and gives the precedence of operators
}
\details{
  The following unary and binary operators are defined.  They are listed
  in precedence groups, from highest to lowest.
  \tabular{ll}{
    \code{[ [[}\tab indexing\cr
    \code{::}\tab name space/variable name separator\cr
    \code{$ @}\tab component / slot extraction\cr
    \code{^}\tab exponentiation (right to left)\cr
    \code{- +}\tab unary minus and plus\cr
    \code{:}\tab sequence operator\cr
    \code{\%any\%}\tab special operators\cr
    \code{* /}\tab multiply, divide\cr
    \code{+ -}\tab (binary) add, subtract\cr
    \code{< > <= >= == !=}\tab ordering and comparison\cr
    \code{!}\tab negation\cr
    \code{&  &&}\tab and\cr
    \code{| ||}\tab or\cr
    \code{~}\tab as in formulae\cr
    \code{-> ->>}\tab rightwards assignment\cr
    \code{=}\tab assignment (right to left)\cr
    \code{<- <<-}\tab assignment (right to left)\cr
    \code{?}\tab help (unary and binary)\cr
  }
  Within an expression operators of equal precedence are evaluated
  from left to right except where indicated.

  The links in the \bold{See Also} section covers most other aspects of
  the basic syntax.
}
\note{
  There are substantial precedence differences between \R and S.  In
  particular, in S \code{?} has the same precedence as \code{+ -} and
  \code{& && | ||} have equal precedence.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{Arithmetic}}, \code{\link{Comparison}}, \code{\link{Control}},
  \code{\link{Extract}}, \code{\link{Logic}}, \code{\link{Paren}}

  The \emph{R Language Definition} manual.
}
\keyword{documentation}
\eof
\name{Sys.info}
\alias{Sys.info}
\title{Extract System and User Information}
\description{
  Reports system and user information.
}
\usage{
Sys.info()
}
\value{
  A character vector with fields
  \item{sysname}{The operating system.}
  \item{release}{The OS release.}
  \item{version}{The OS version.}
  \item{nodename}{A name by which the machine is known on the network (if
    any).}
  \item{machine}{A concise description of the hardware.}
  \item{login}{The user's login name, or \code{"unknown"} if it cannot be
    ascertained.}
  \item{user}{The name of the real user ID, or \code{"unknown"} if it
    cannot be ascertained.}
#ifdef unix
The first five fields come from the \code{uname(2)} system call.  The
login name comes from \code{getlogin(2)}, and the user name from
\code{getpwuid(getuid())}
#endif
#ifdef windows
The information is obtained from Windows system calls.  It is likely to
be most complete on Windows NT/2000/XP systems.
#endif
}
\details{
  This function is not implemented on all \R platforms, and returns
  \code{NULL} when not available.  Where possible it is based on POSIX
  system calls.

  \code{Sys.info()} returns details of the platform \R is running on,
  whereas \code{\link{R.version}} gives details of the platform \R was
  built on: they may well be different.
}
\note{
  The meaning of OS \dQuote{release} and \dQuote{version} is highly
  system-dependent and there is no guarantee that the node or
  login or user names will be what you might reasonably expect.
  (In particular on some Linux distributions the login name is unknown
  from sessions with re-directed inputs.)
}

\seealso{
  \code{\link{.Platform}}, and \code{\link{R.version}}.
}

\examples{
Sys.info()
## An alternative (and probably better) way to get the login name on Unix
Sys.getenv("LOGNAME")
}
\keyword{utilities}
\eof
\name{Sys.sleep}
\alias{Sys.sleep}
\title{Suspend Execution for a Time Interval}
\description{
  Suspend execution of \R expressions for a given number of seconds
}
\usage{
Sys.sleep(time)
}
\arguments{
  \item{time}{The time interval to suspend execution for, in seconds.}
}
\details{
  Using this function allows \R to be given very low priority and hence
  not to interfere with more important foreground tasks. A typical use
  is to allow a process lauched from \R to set itself up and read its
  input files before \R execution is resumed.
  
  The intention is that this function suspends execution of \R
  expressions but wakes the process up often enough to respond to GUI
  events, typically every 0.5 seconds.

  There is no guarantee that the process will sleep for the whole of the
  specified interval, and it may well take slightly longer in real time
  to resume execution.  The resolution of the time interval is
  system-dependent, but will normally be down to 0.02 secs or better.
}
\value{
  Invisible \code{NULL}.
}
\note{This function may not be implemented on all systems.}

\examples{
testit <- function(x)
{
    p1 <- proc.time()
    Sys.sleep(x)
    proc.time() - p1 # The cpu usage should be negligible
}
testit(3.7)
}
\keyword{utilities}
\eof
\name{Sys.time}
\alias{Sys.time}
\alias{Sys.timezone}

\title{Get Current Time and Timezone}
\description{
  \code{Sys.time} returns the system's idea of the current time and
  \code{Sys.timezone} returns the current time zone.
}
\usage{
Sys.time()
Sys.timezone()
}
\value{
  \code{Sys.time} returns an object of class \code{"POSIXct"} (see
  \link{DateTimeClasses}).

  \code{Sys.timezone} returns an OS-specific character string, possibly
  an empty string.
}
\seealso{
  \code{\link{date}} for the system time in a fixed-format character
  string.
}
\examples{
Sys.time()
## locale-specific version of date()
format(Sys.time(), "\%a \%b \%d \%X \%Y")

Sys.timezone()
}
\keyword{utilities}
\keyword{chron}
\eof
\name{TDist}
\alias{TDist}
\alias{dt}
\alias{pt}
\alias{qt}
\alias{rt}
\title{The Student t Distribution}
\description{
  Density, distribution function, quantile function and random
  generation for the t distribution with \code{df} degrees of freedom
  (and optional noncentrality parameter \code{ncp}).
}
\usage{
dt(x, df, ncp=0, log = FALSE)
pt(q, df, ncp=0, lower.tail = TRUE, log.p = FALSE)
qt(p, df,        lower.tail = TRUE, log.p = FALSE)
rt(n, df)
}
\arguments{
  \item{x, q}{vector of quantiles.}
  \item{p}{vector of probabilities.}
  \item{n}{number of observations. If \code{length(n) > 1}, the length
    is taken to be the number required.}
  \item{df}{degrees of freedom (\eqn{> 0}, maybe non-integer).}
  \item{ncp}{non-centrality parameter \eqn{\delta};
    currently for \code{pt()} and \code{dt()}, only for \code{ncp <= 37.62}.}
  \item{log, log.p}{logical; if TRUE, probabilities p are given as log(p).}
  \item{lower.tail}{logical; if TRUE (default), probabilities are
    \eqn{P[X \le x]}{P[X <= x]}, otherwise, \eqn{P[X > x]}{P[X > x]}.}
}
\value{
  \code{dt} gives the density,
  \code{pt} gives the distribution function,
  \code{qt} gives the quantile function, and
  \code{rt} generates random deviates.
}
\details{
  The \eqn{t} distribution with \code{df} \eqn{= \nu}{= n} degrees of
  freedom has density
  \deqn{
    f(x) = \frac{\Gamma ((\nu+1)/2)}{\sqrt{\pi \nu} \Gamma (\nu/2)}
    (1 + x^2/\nu)^{-(\nu+1)/2}%
  }{f(x) = Gamma((n+1)/2) / (sqrt(n pi) Gamma(n/2)) (1 + x^2/n)^-((n+1)/2)}
  for all real \eqn{x}.
  It has mean \eqn{0} (for \eqn{\nu > 1}{n > 1}) and
  variance \eqn{\frac{\nu}{\nu-2}}{n/(n-2)} (for \eqn{\nu > 2}{n > 2}).

  The general \emph{non-central} \eqn{t}
  with parameters \eqn{(\nu,\delta)}{(df,Del)} \code{= (df, ncp)}
  is defined as a the distribution of
  \eqn{T_{\nu}(\delta) := \frac{U + \delta}{\chi_{\nu}/\sqrt{\nu}}}{%
      T(df,Del) := (U + Del) / (Chi(df) / sqrt(df)) }
  where \eqn{U} and \eqn{\chi_{\nu}}{Chi(df)}  are independent random
  variables, \eqn{U \sim {\cal N}(0,1)}{U \~ N(0,1)}, and
%%fails  \eqn{{\chi_{\nu}}^2}{(Chi(df))^2}
  \eqn{\chi^2_\nu}{Chi(df)^2}
  is chi-squared, see \code{\link{pchisq}}.

  The most used applications are power calculations for \eqn{t}-tests:\cr
  Let \eqn{T= \frac{\bar{X} - \mu_0}{S/\sqrt{n}}}{T= (mX - m0) / (S/sqrt(n))}
  where
  \eqn{\bar{X}}{mX} is the \code{\link{mean}} and \eqn{S} the sample standard
  deviation (\code{\link{sd}}) of \eqn{X_1,X_2,\dots,X_n} which are i.i.d.
%%fails \eqn{{\cal N}(\mu,\sigma^2)}{N(mu,sigma^2)}
        \eqn{       N(\mu,\sigma^2)}{N(mu,sigma^2)}.
  Then \eqn{T} is distributed as non-centrally \eqn{t} with
  \code{df}\eqn{= n-1}
  degrees of freedom and \bold{n}on-\bold{c}entrality \bold{p}arameter
  \code{ncp}\eqn{= (\mu - \mu_0) \sqrt{n}/\sigma}{= (mu - m0) * sqrt(n)/sigma}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole. (except non-central versions.)

  Lenth, R. V. (1989). \emph{Algorithm AS 243} ---
    Cumulative distribution function of the non-central \eqn{t} distribution,
    \emph{Appl.\ Statist.} \bold{38}, 185--189.
}
\seealso{\code{\link{df}} for the F distribution.}
\examples{
1 - pt(1:5, df = 1)
qt(.975, df = c(1:10,20,50,100,1000))

tt <- seq(0,10, len=21)
ncp <- seq(0,6, len=31)
ptn <- outer(tt,ncp, function(t,d) pt(t, df = 3, ncp=d))
image(tt,ncp,ptn, zlim=c(0,1),main=t.tit <- "Non-central t - Probabilities")
persp(tt,ncp,ptn, zlim=0:1, r=2, phi=20, theta=200, main=t.tit,
      xlab = "t", ylab = "noncentrality parameter", zlab = "Pr(T <= t)")

op <- par(yaxs="i")
plot(function(x) dt(x, df = 3, ncp = 2), -3, 11, ylim = c(0, 0.32),
     main="Non-central t - Density")
par(op)
}
\keyword{distribution}
\eof
\name{Titanic}
\docType{data}
\alias{Titanic}
\title{Survival of passengers on the Titanic}
\description{
  This data set provides information on the fate of passengers on the
  fatal maiden voyage of the ocean liner \sQuote{Titanic}, summarized according
  to economic status (class), sex, age and survival.
}
\usage{data(Titanic)}
\format{
  A 4-dimensional array resulting from cross-tabulating 2201
  observations on 4 variables.  The variables and their levels are as
  follows:

  \tabular{rll}{
    No \tab Name \tab Levels\cr
    1 \tab Class \tab 1st, 2nd, 3rd, Crew\cr
    2 \tab Sex \tab Male, Female\cr
    3 \tab Age \tab Child, Adult\cr
    4 \tab Survived \tab No, Yes
  }
}
\details{
  The sinking of the Titanic is a famous event, and new books are still
  being published about it.  Many well-known facts---from the
  proportions of first-class passengers to the \dQuote{women and
    children first} policy, and the fact that that policy was not
  entirely successful in saving the women and children in the third
  class---are reflected in the survival rates for various classes of
  passenger.

  These data were originally collected by the British Board of Trade in
  their investigation of the sinking.  Note that there is not complete
  agreement among primary sources as to the exact numbers on board,
  rescued, or lost.

  Due in particular to the very successful film \sQuote{Titanic}, the last
  years saw a rise in public interest in the Titanic.  Very detailed
  data about the passengers is now available on the Internet, at sites
  such as \emph{Encyclopedia Titanica}
  (\url{http://www.rmplc.co.uk/eduweb/sites/phind}).
}
\source{
  Dawson, Robert J. MacG. (1995),
  The \sQuote{Unusual Episode} Data Revisited.
  \emph{Journal of Statistics Education}, \bold{3}.
  \url{http://www.amstat.org/publications/jse/v3n3/datasets.dawson.html}

  The source provides a data set recording class, sex, age, and survival
  status for each person on board of the Titanic, and is based on data
  originally collected by the British Board of Trade and reprinted in:

  British Board of Trade (1990),
  \emph{Report on the Loss of the \sQuote{Titanic} (S.S.)}.
  British Board of Trade Inquiry Report (reprint).
  Gloucester, UK: Allan Sutton Publishing.
}
\examples{
data(Titanic)
mosaicplot(Titanic, main = "Survival on the Titanic")
## Higher survival rates in children?
apply(Titanic, c(3, 4), sum)
## Higher survival rates in females?
apply(Titanic, c(2, 4), sum)
## Use loglm() in package 'MASS' for further analysis ...
}
\keyword{datasets}
\eof
\name{ToothGrowth}
\docType{data}
\alias{ToothGrowth}
\title{The Effect of Vitamin C on Tooth Growth in Guinea Pigs}
\description{
  The response is the length of odontoblasts (teeth) in each of 10
  guinea pigs at each of three dose levels of Vitamin C (0.5, 1, and 2
  mg) with each of two delivery methods (orange juice or ascorbic
  acid).
}
\usage{data(ToothGrowth)}
\format{
  A data frame with 60 observations on 3 variables.
  \tabular{rlll}{
    [,1]  \tab len   \tab numeric  \tab Tooth length\cr
    [,2]  \tab supp  \tab factor   \tab Supplement type (VC or OJ).\cr
    [,3]  \tab dose  \tab numeric  \tab Dose in milligrams.
  }
}
\source{
  C. I. Bliss (1952)
  \emph{The Statistics of Bioassay}.
  Academic Press.
}
\references{
  McNeil, D. R. (1977)
  \emph{Interactive Data Analysis}.
  New York: Wiley.
}
\examples{
data(ToothGrowth)
coplot(len ~ dose | supp, data = ToothGrowth, panel = panel.smooth,
       xlab = "ToothGrowth data: length vs dose, given type of supplement")
}
\keyword{datasets}
\eof
\name{Trig}
\alias{Trig}
\alias{cos}
\alias{sin}
\alias{tan}
\alias{acos}
\alias{asin}
\alias{atan}
\alias{atan2}
\title{Trigonometric Functions}
\description{
  These functions give the obvious trigonometric functions.  They
  respectively compute the cosine, sine, tangent, arc-cosine, arc-sine,
  arc-tangent, and the two-argument arc-tangent.
}
\usage{
cos(x)
sin(x)
tan(x)
acos(x)
asin(x)
atan(x)
atan2(y, x)
}
\arguments{
  \item{x, y}{numeric vector}
}
\details{
  The arc-tangent of two arguments \code{atan2(y,x)} returns the angle
  between the x-axis and the vector from the origin to \eqn{(x,y)},
  i.e., for positive arguments \code{atan2(y,x) == atan(y/x)}.

  Angles are in radians, not degrees (i.e., a right angle is
  \eqn{\pi/2}).
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\keyword{math}
\eof
\name{Tukey}
\alias{Tukey}
\title{The Studentized Range Distribution}
\usage{
ptukey(q, nmeans, df, nranges = 1, lower.tail = TRUE, log.p = FALSE)
qtukey(p, nmeans, df, nranges = 1, lower.tail = TRUE, log.p = FALSE)
}
\alias{ptukey}
\alias{qtukey}
\arguments{
  \item{q}{vector of quantiles.}
  \item{p}{vector of probabilities.}
  \item{nmeans}{sample size for range (same for each group).}
  \item{df}{degrees of freedom for \eqn{s} (see below).}
  \item{nranges}{number of \emph{groups} whose \bold{maximum} range is
    considered.}
  \item{log.p}{logical; if TRUE, probabilities p are given as log(p).}
  \item{lower.tail}{logical; if TRUE (default), probabilities are
    \eqn{P[X \le x]}{P[X <= x]}, otherwise, \eqn{P[X > x]}{P[X > x]}.}
}
\description{
  Functions on the distribution of
  the studentized range, \eqn{R/s}, where \eqn{R} is the range of a
  standard normal sample of size \eqn{n} and \eqn{s^2} is independently
  distributed as chi-squared with \eqn{df} degrees of freedom, see
  \code{\link{pchisq}}.
}
\details{
  If \eqn{n_g =}{ng =}\code{nranges} is greater than one, \eqn{R} is
  the \emph{maximum} of \eqn{n_g}{ng} groups of \code{nmeans}
  observations each.
}
\value{
  \code{ptukey} gives the distribution function and \code{qtukey} its
  inverse, the quantile function.
}
\note{
  A Legendre 16-point formula is used for the integral of \code{ptukey}.
  The computations are relatively expensive, especially for
  \code{qtukey} which uses a simple secant method for finding the
  inverse of \code{ptukey}.
  \code{qtukey} will be accurate to the 4th decimal place.
}
\references{
  Copenhaver, Margaret Diponzio and Holland, Burt S. (1988)
  Multiple comparisons of simple effects in
  the two-way analysis of variance with fixed effects.
  \emph{Journal of Statistical Computation and Simulation}, \bold{30}, 1--15.
}
\seealso{
  \code{\link{pnorm}} and \code{\link{qnorm}} for the corresponding
  functions for the normal distribution.
}
\examples{
if(interactive())
  curve(ptukey(x, nm=6, df=5), from=-1, to=8, n=101)
(ptt <- ptukey(0:10, 2, df= 5))
(qtt <- qtukey(.95, 2, df= 2:11))
## The precision may be not much more than about 8 digits:
summary(abs(.95 - ptukey(qtt,2, df = 2:11)))
}
\keyword{distribution}
\eof
\name{TukeyHSD}
\alias{TukeyHSD}
\alias{TukeyHSD.aov}
\alias{print.TukeyHSD}
\alias{plot.TukeyHSD}
\title{Compute Tukey Honest Significant Differences}
\description{
  Create a set of confidence intervals on the differences between the
  means of the levels of a factor with the specified family-wise
  probability of coverage.  The intervals are based on the Studentized
  range statistic, Tukey's \sQuote{Honest Significant Difference}
  method.  There is a \code{plot} method.
}
\usage{
TukeyHSD(x, which, ordered = FALSE, conf.level = 0.95, \dots)
}
\arguments{
 \item{x}{A fitted model object, usually an \code{\link{aov}} fit.}
 \item{which}{A list of terms in the fitted model for which the
   intervals should be calculated.  Defaults to all the terms.}
 \item{ordered}{A logical value indicating if the levels of the factor
   should be ordered according to increasing average in the sample
   before taking differences.  If \code{ordered} is true then
   the calculated differences in the means will all be positive.  The
   significant differences will be those for which the \code{lwr} end
   point is positive.}
 \item{conf.level}{A numeric value between zero and one giving the
   family-wise confidence level to use.}
 \item{\dots}{Optional additional arguments.  None are used at present.}
}
\details{
  When comparing the means for the levels of a factor in an analysis of
  variance, a simple comparison using t-tests will inflate the
  probability of declaring a significant difference when it is not in
  fact present.  This because the intervals are calculated with a
  given coverage probability for each interval but the interpretation of
  the coverage is usually with respect to the entire family of
  intervals.

  John Tukey introduced intervals based on the range of the
  sample means rather than the individual differences.  The intervals
  returned by this function are based on this Studentized range
  statistics.

  Technically the intervals constructed in this way would only apply to
  balanced designs where there are the same number of observations made
  at each level of the factor.  This function incorporates an adjustment
  for sample size that produces sensible intervals for mildly unbalanced
  designs.
}
\value{
  A list with one component for each term requested in \code{which}.
  Each component is a matrix with columns \code{diff} giving the
  difference in the observed means, \code{lwr} giving the lower
  end point of the interval, and \code{upr} giving the upper end point.
}
\references{
  Miller, R. G. (1981)
  \emph{Simultaneous Statistical Inference}. Springer.

  Yandell, B. S. (1997)
  \emph{Practical Data Analysis for Designed Experiments}.
  Chapman \& Hall.
}
\author{
  Douglas Bates
}
\seealso{
  \code{\link{aov}}, \code{\link{qtukey}}, \code{\link{model.tables}}
}
\examples{
data(warpbreaks)
summary(fm1 <- aov(breaks ~ wool + tension, data = warpbreaks))
TukeyHSD(fm1, "tension", ordered = TRUE)
plot(TukeyHSD(fm1, "tension"))
}
\keyword{models}
\keyword{design}
\eof
\name{UCBAdmissions}
\docType{data}
\alias{UCBAdmissions}
\title{Student Admissions at UC Berkeley}
\description{
  Aggregate data on applicants to graduate school at Berkeley for the
  six largest departments in 1973 classified by admission and sex.
}
\usage{data(UCBAdmissions)}
\format{
  A 3-dimensional array resulting from cross-tabulating 4526
  observations on 3 variables.  The variables and their levels are as
  follows:

  \tabular{rll}{
    No \tab Name \tab Levels\cr
    1 \tab Admit \tab Admitted, Rejected\cr
    2 \tab Gender \tab Male, Female\cr
    3 \tab Dept \tab A, B, C, D, E, F
  }
}
\details{
  This data set is frequently used for illustrating Simpson's paradox,
  see Bickel et al.\ (1975).  At issue is whether the data show evidence
  of sex bias in admission practices.  There were 2691 male applicants,
  of whom 1198 (44.5\%) were admitted, compared with 1835 female
  applicants of whom 557 (30.4\%) were admitted.  This gives a sample
  odds ratio of 1.83, indicating that males were almost twice as likely
  to be admitted.  In fact, graphical methods (as in the example below)
  or log-linear modelling show that the apparent association between
  admission and sex stems from differences in the tendency of males and
  females to apply to the individual departments (females used to apply
  \dQuote{more} to departments with higher rejection rates).

  This data set can also be used for illustrating methods for graphical
  display of categorical data, such as the general-purpose mosaic plot
  or the \dQuote{fourfold display} for 2-by-2-by-\eqn{k} tables.  See the
  home page of Michael Friendly
  (\url{http://www.math.yorku.ca/SCS/friendly.html}) for further
  information.
}
\references{
  Bickel, P. J., Hammel, E. A., and O'Connell, J. W. (1975)
  Sex bias in graduate admissions: Data from Berkeley.
  \emph{Science}, \bold{187}, 398--403.
}
\examples{
data(UCBAdmissions)
## Data aggregated over departments
apply(UCBAdmissions, c(1, 2), sum)
mosaicplot(apply(UCBAdmissions, c(1, 2), sum),
           main = "Student admissions at UC Berkeley")
## Data for individual departments
opar <- par(mfrow = c(2, 3), oma = c(0, 0, 2, 0))
for(i in 1:6)
  mosaicplot(UCBAdmissions[,,i],
    xlab = "Admit", ylab = "Sex",
    main = paste("Department", LETTERS[i]))
mtext(expression(bold("Student admissions at UC Berkeley")),
      outer = TRUE, cex = 1.5)
par(opar)
}
\keyword{datasets}
\eof
\name{USArrests}
\docType{data}
\alias{USArrests}
\title{Violent Crime Rates by US State}
\description{
  This data set contains statistics, in arrests per 100,000 residents
  for assault, murder, and rape in each of the 50 US states in 1973.
  Also given is the percent of the population living in urban areas.
}
\usage{data(USArrests)}
\format{
  A data frame with 50 observations on 4 variables.

  \tabular{rlll}{
    [,1]  \tab Murder    \tab numeric
    \tab Murder arrests (per 100,000)\cr
    [,2]  \tab Assault   \tab numeric
    \tab Assault arrests (per 100,000)\cr
    [,3]  \tab UrbanPop  \tab numeric
    \tab Percent urban population\cr
    [,4]  \tab Rape      \tab numeric
    \tab Rape arrests (per 100,000)
  }
}
\source{
  World Almanac and Book of facts 1975.  (Crime rates).

  Statistical Abstracts of the United States 1975.  (Urban rates).
}
\seealso{The \code{\link{state}} data sets.}
\references{
  McNeil, D. R. (1977)
  \emph{Interactive Data Analysis}.
  New York: Wiley.
}
\examples{
data(USArrests)
pairs(USArrests, panel = panel.smooth, main = "USArrests data")
}
\keyword{datasets}
\eof
\name{USJudgeRatings}
\docType{data}
\alias{USJudgeRatings}
\title{Lawyers' Ratings of State Judges in the US Superior Court}
\description{
  Lawyers' ratings of state judges in the US Superior Court.
}
\usage{data(USJudgeRatings)}
\format{
  A data frame containing 43 observations on 12 numeric variables.

  \tabular{rll}{
    [,1] \tab CONT \tab Number of contacts of lawyer with judge.\cr
    [,2] \tab INTG \tab Judicial integrity.\cr
    [,3] \tab DMNR \tab Demeanor.\cr
    [,4] \tab DILG \tab Diligence.\cr
    [,5] \tab CFMG \tab Case flow managing.\cr
    [,6] \tab DECI \tab Prompt decisions.\cr
    [,7] \tab PREP \tab Preparation for trial.\cr
    [,8] \tab FAMI \tab Familiarity with law.\cr
    [,9] \tab ORAL \tab Sound oral rulings.\cr
    [,10] \tab WRIT \tab Sound written rulings.\cr
    [,11] \tab PHYS \tab Physical ability.\cr
    [,12] \tab RTEN \tab Worthy of retention.
  }
}
\source{
  New Haven Register, 14 January, 1977 (from John Hartigan).
}
\examples{
data(USJudgeRatings)
pairs(USJudgeRatings, main = "USJudgeRatings data")
}
\keyword{datasets}
\eof
\name{USPersonalExpenditure}
\docType{data}
\alias{USPersonalExpenditure}
\title{Personal Expenditure Data}
\description{
  This data set consists of United States personal expenditures (in
  billions of dollars) in the categories; food and tobacco, household
  operation, medical and health, personal care, and private education
  for the years 1940, 1945, 1950, and 1960.
}
\usage{data(USPersonalExpenditure)}
\format{A matrix with 5 rows and 5 columns.}
\source{The World Almanac and Book of Facts, 1962, page 756.}
\references{
  Tukey, J. W. (1977)
  \emph{Exploratory Data Analysis}.
  Addison-Wesley.

  McNeil, D. R. (1977)
  \emph{Interactive Data Analysis}.
  Wiley.
}
\examples{
data(USPersonalExpenditure)
USPersonalExpenditure
eda::medpolish(log10(USPersonalExpenditure))
}
\keyword{datasets}
\eof
\name{Uniform}
\alias{Uniform}
\title{The Uniform Distribution}
\usage{
dunif(x, min=0, max=1, log = FALSE)
punif(q, min=0, max=1, lower.tail = TRUE, log.p = FALSE)
qunif(p, min=0, max=1, lower.tail = TRUE, log.p = FALSE)
runif(n, min=0, max=1)
}
\alias{dunif}
\alias{punif}
\alias{qunif}
\alias{runif}
\arguments{
  \item{x,q}{vector of quantiles.}
  \item{p}{vector of probabilities.}
  \item{n}{number of observations. If \code{length(n) > 1}, the length
    is taken to be the number required.}
  \item{min,max}{lower and upper limits of the distribution.}
  \item{log, log.p}{logical; if TRUE, probabilities p are given as log(p).}
  \item{lower.tail}{logical; if TRUE (default), probabilities are
    \eqn{P[X \le x]}{P[X <= x]}, otherwise, \eqn{P[X > x]}{P[X > x]}.}
}
\description{
  These functions provide information about the uniform distribution
  on the interval from \code{min} to \code{max}.  \code{dunif} gives the
  density, \code{punif} gives the distribution function \code{qunif}
  gives the quantile function and \code{runif} generates random
  deviates.
}
\details{
  If \code{min} or \code{max} are not specified they assume the default
  values of \code{0} and \code{1} respectively.

  The uniform distribution has density
  \deqn{f(x) = \frac{1}{max-min}}{f(x) = 1/(max-min)}
  for \eqn{min \le x \le max}.

  For the case of \eqn{u := min == max}, the limit case of
  \eqn{X \equiv u}{X == u} is assumed.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{.Random.seed}} about random number generation,
  \code{\link{rnorm}}, etc for other distributions.
}
\examples{
u <- runif(20)

## The following relations always hold :
punif(u) == u
dunif(u) == 1

var(runif(10000))#- ~ = 1/12 = .08333
}
\keyword{distribution}
\eof
\name{UseMethod}
\title{Class Methods}
\alias{UseMethod}
\alias{NextMethod}
\alias{S3Methods}
\alias{.isMethodsDispatchOn}
\description{
  \R possesses a simple generic function mechanism which can be used for
  an object-oriented style of programming.  Method despatch takes place
  based on the class of the first argument to the generic function or on
  the object supplied as an argument to \code{UseMethod} or \code{NextMethod}.
}
\usage{
UseMethod(generic, object)
NextMethod(generic = NULL, object = NULL, \dots)
}
\arguments{
  \item{generic}{a character string naming a function.}
  \item{object}{an object whose class will determine the method to be
    dispatched.  Defaults to the first argument of the enclosing function.}
  \item{\dots}{further arguments to be passed to the method.}
}
\details{
  An \R \dQuote{object} is a data object which has a \code{class} attribute.
  A class attribute is a character vector giving the names of
  the classes which the object \dQuote{inherits} from.
  If the object does not have a class attribute, it has an implicit
  class, \code{"matrix"}, \code{"array"} or the result of
  \code{\link{mode}(x)}.

  When a generic
  function \code{fun} is applied to an object with class attribute
  \code{c("first", "second")}, the system searches for a function called
  \code{fun.first} and, if it finds it, applied it to the object.  If no
  such function is found a function called \code{fun.second} is tried.
  If no class name produces a suitable function, the function
  \code{fun.default} is used.

  Function \code{\link{methods}} can be used to find out about the
  methods for a particular generic function or class.

  Now for some obscure details that need to appear somewhere.  These
  comments will be slightly different than those in Appendix A of the
  White S Book. \code{UseMethod} creates a \dQuote{new} function call with
  arguments matched as they came in to the generic.  Any local variables
  defined before the call to \code{UseMethod} are retained (unlike S).  Any
  statements after the call to \code{UseMethod} will not be evaluated as
  \code{UseMethod} does not return.  \code{UseMethod} can be called with
  more than two arguments: a warning will be given and additional
  arguments ignored. (They are not completely ignored in S.)  If it is
  called with just one argument, the class of the first argument of the
  enclosing function is used as \code{object}: unlike S this is the
  actual argument passed and not the current value of the object of that
  name.

  \code{NextMethod} invokes the next method (determined by the
  class).  It does this by creating a special call frame for that
  method.  The arguments will be the same in number, order and name as
  those to the current method but their values will be promises to
  evaluate their name in the current method and environment.  Any
  arguments matched to \code{\dots} are handled specially.  They are
  passed on as the promise that was supplied as an argument to the
  current environment. (S does this differently!)  If they have been
  evaluated in the current (or a previous environment) they remain
  evaluated.

  \code{NextMethod} should not be called except in methods called by
  \code{UseMethod}. In particular it will not work inside anonymous
  calling functions (eg \code{get("print.ts")(AirPassengers)}).

  Name spaces can register methods for generic functions.  To support
  this, \code{UseMethod} and \code{NextMethod} search for methods in
  two places: first in the environment in which the generic function
  is called, and then in the registration data base for the
  environment in which the generic is defined (typically a name space).
  So methods for a generic function need to either be available in the
  environment of the call to the generic, or they must be registered.
  It does not matter whether they are visible in the environment in
  which the generic is defined.

}
\note{
  This scheme is called \emph{S3} (S version 3).  For new projects,
  it is recommended to use the more flexible and robust \emph{S4} scheme
  provided in the \pkg{methods} package. 

  The function \code{.isMethodsDispatchOn()} returns \code{TRUE} if
  the S4 method dispatch has been turned on in the evaluator. It is
  meant for \R internal use only.
}
\seealso{
  \code{\link{methods}}, \code{\link[base]{class}}, \code{\link{getS3method}}
}
\references{
  Chambers, J. M. (1992)
  \emph{Classes and methods: object-oriented programming in S.}
  Appendix A of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\keyword{methods}
\eof
\name{VADeaths}
\docType{data}
\alias{VADeaths}
\title{Death Rates in Virginia (1940)}
\description{
  Death rates per 100 in Virginia in 1940.
}
\usage{data(VADeaths)}
\format{A matrix with 5 rows and 5 columns.}
\details{
  The death rates are cross-classified by age group (rows) and
  population group (columns).  The age groups are: 50--54, 55--59,
  60--64, 65--69, 70--74 and the population groups are Rural/Male,
  Rural/Female, Urban/Male and Urban/Female.

  This provides a rather nice 3-way analysis of variance example.
}
\source{
  Moyneau, L.,  Gilliam, S. K., and  Florant, L. C.(1947)
  Differences in Virginia death rates by color, sex, age,
  and rural or urban residence.
  \emph{American Sociological Review}, \bold{12}, 525--535.
}
\references{
  McNeil, D. R. (1977)
  \emph{Interactive Data Analysis}.
  Wiley.
}
\examples{
data(VADeaths)
n <- length(dr <- c(VADeaths))
nam <- names(VADeaths)
d.VAD <- data.frame(
 Drate = dr,
 age = rep(ordered(rownames(VADeaths)),length=n),
 gender= gl(2,5,n, labels= c("M", "F")),
 site =  gl(2,10,  labels= c("rural", "urban")))
coplot(Drate ~ as.numeric(age) | gender * site, data = d.VAD,
       panel = panel.smooth, xlab = "VADeaths data - Given: gender")
summary(aov.VAD <- aov(Drate ~ .^2, data = d.VAD))
opar <- par(mfrow = c(2,2), oma = c(0, 0, 1.1, 0))
plot(aov.VAD)
par(opar)
}
\keyword{datasets}
\eof
\name{R.Version}
\title{Version Information}
\usage{
R.Version()
R.version
R.version.string
}
\alias{R.Version}
\alias{R.version}
\alias{version}
\alias{R.version.string}
\description{
    \code{R.Version()} provides detailed information about the version of
    \R running. \cr
    \code{R.version} is a variable (a \code{\link{list}}) holding this
    information (and \code{version} is a copy of it for
    S compatibility), whereas \code{R.version.string} is a simple
    \code{\link{character}} string, useful for plotting, etc.
}
\value{
 \code{R.Version} returns a list with components
  \item{platform}{the platform for which \R was built.  Under Unix, a
    triplet of the form CPU-VENDOR-OS, as determined by the configure
    script.  E.g, \code{"i586-unknown-linux"}.}
  \item{arch}{the architecture (CPU) \R was built on/for.}
  \item{os}{the underlying operating system}
  \item{system}{CPU and OS.}
  \item{status}{the status of the version (e.g., \code{"Alpha"})}
  \item{status.rev}{the status revision level}
  \item{major}{the major version number}
  \item{minor}{the minor version number}
  \item{year}{the year the version was released}
  \item{month}{the month the version was released}
  \item{day}{the day the version was released}
  \item{language}{always \code{"R"}.}
}
\note{
  Do \emph{not} use \code{R.version$os} to test the platform the
  code is running on: use \code{.Platform$OS.type} instead.  Slightly
  different versions of the OS may report different values of
  \code{R.version$os}, as may different versions of \R.
}
\seealso{
  \code{\link{.Platform}}.
}
\examples{
R.version$os # to check how lucky you are ...
plot(0) # any plot
mtext(R.version.string, side=1,line=4,adj=1)# a useful bottom-right note
}
\keyword{environment}
\keyword{sysdata}
\keyword{programming}
\eof
\name{Weibull}
\alias{Weibull}
\alias{dweibull}
\alias{pweibull}
\alias{qweibull}
\alias{rweibull}
\title{The Weibull Distribution}
\description{
  Density, distribution function, quantile function and random
  generation for the Weibull distribution with parameters \code{shape}
  and \code{scale}.
}
\usage{
dweibull(x, shape, scale = 1, log = FALSE)
pweibull(q, shape, scale = 1, lower.tail = TRUE, log.p = FALSE)
qweibull(p, shape, scale = 1, lower.tail = TRUE, log.p = FALSE)
rweibull(n, shape, scale = 1)
}
\arguments{
  \item{x, q}{vector of quantiles.}
  \item{p}{vector of probabilities.}
  \item{n}{number of observations. If \code{length(n) > 1}, the length
    is taken to be the number required.}
  \item{shape, scale}{shape and scale parameters, the latter defaulting to 1.}
  \item{log, log.p}{logical; if TRUE, probabilities p are given as log(p).}
  \item{lower.tail}{logical; if TRUE (default), probabilities are
    \eqn{P[X \le x]}{P[X <= x]}, otherwise, \eqn{P[X > x]}{P[X > x]}.}
}
\value{
  \code{dweibull} gives the density,
  \code{pweibull} gives the distribution function,
  \code{qweibull} gives the quantile function, and
  \code{rweibull} generates random deviates.
}
\details{
  The Weibull distribution with \code{shape} parameter \eqn{a} and
  \code{scale} parameter \eqn{\sigma}{b} has density given by
  \deqn{f(x) = (a/\sigma) {(x/\sigma)}^{a-1} \exp (-{(x/\sigma)}^{a})}{%
        f(x) = (a/b) (x/b)^(a-1) exp(- (x/b)^a)}
  for \eqn{x > 0}.
  The cumulative is
  \eqn{F(x) = 1 - \exp(-{(x/\sigma)}^a)}{F(x) = 1 - exp(- (x/b)^a)}, the
  mean is \eqn{E(X) = \sigma \Gamma(1 + 1/a)}{E(X) = b Gamma(1 + 1/a)}, and
  the \eqn{Var(X) = \sigma^2(\Gamma(1 + 2/a)-(\Gamma(1 + 1/a))^2)}{%
           Var(X) = b^2 * (gamma(1 + 2/a) - (gamma(1 + 1/a))^2)}.
}
\note{
  The cumulative hazard \eqn{H(t) = - \log(1 - F(t))}{H(t) = - log(1 - F(t))}
  is \code{-pweibull(t, a, b, lower = FALSE, log = TRUE)} which is just
  \eqn{H(t) = {(t/b)}^a}.
}
\seealso{
  \code{\link{dexp}} for the Exponential which is a special case of a
  Weibull distribution.
}
\examples{
x <- c(0,rlnorm(50))
all.equal(dweibull(x, shape = 1), dexp(x))
all.equal(pweibull(x, shape = 1, scale = pi), pexp(x, rate = 1/pi))
## Cumulative hazard H():
all.equal(pweibull(x, 2.5, pi, lower=FALSE, log=TRUE), -(x/pi)^2.5, tol=1e-15)
all.equal(qweibull(x/11, shape = 1, scale = pi), qexp(x/11, rate = 1/pi))
}
\keyword{distribution}
\eof
\name{Wilcoxon}
\alias{Wilcoxon}
\alias{dwilcox}
\alias{pwilcox}
\alias{qwilcox}
\alias{rwilcox}
\title{Distribution of the Wilcoxon Rank Sum Statistic}
\description{
  Density, distribution function, quantile function and random
  generation for the distribution of the Wilcoxon rank sum statistic
  obtained from samples with size \code{m} and \code{n}, respectively.
}
\usage{
dwilcox(x, m, n, log = FALSE)
pwilcox(q, m, n, lower.tail = TRUE, log.p = FALSE)
qwilcox(p, m, n, lower.tail = TRUE, log.p = FALSE)
rwilcox(nn, m, n)
}
\arguments{
  \item{x, q}{vector of quantiles.}
  \item{p}{vector of probabilities.}
  \item{nn}{number of observations. If \code{length(nn) > 1}, the length
    is taken to be the number required.}
  \item{m, n}{numbers of observations in the first and second sample,
    respectively.}
  \item{log, log.p}{logical; if TRUE, probabilities p are given as log(p).}
  \item{lower.tail}{logical; if TRUE (default), probabilities are
    \eqn{P[X \le x]}{P[X <= x]}, otherwise, \eqn{P[X > x]}{P[X > x]}.}
}
\value{
  \code{dwilcox} gives the density,
  \code{pwilcox} gives the distribution function,
  \code{qwilcox} gives the quantile function, and
  \code{rwilcox} generates random deviates.
}
\details{
  This distribution is obtained as follows.  Let \code{x} and \code{y}
  be two random, independent samples of size \code{m} and \code{n}.
  Then the Wilcoxon rank sum statistic is the number of all pairs
  \code{(x[i], y[j])} for which \code{y[j]} is not greater than
  \code{x[i]}.  This statistic takes values between \code{0} and
  \code{m * n}, and its mean and variance are \code{m * n / 2} and
  \code{m * n * (m + n + 1) / 12}, respectively.
}
\note{
  S-PLUS uses a different (but equivalent) definition of the Wilcoxon
  statistic.
}
\author{Kurt Hornik \email{hornik@ci.tuwien.ac.at}}
\seealso{\code{\link{dsignrank}} etc, for the \emph{one-sample} Wilcoxon
    rank statistic.}
\examples{
x <- -1:(4*6 + 1)
fx <- dwilcox(x, 4, 6)
Fx <- pwilcox(x, 4, 6)

layout(rbind(1,2),width=1,heights=c(3,2))
plot(x, fx,type='h', col="violet",
     main= "Probabilities (density) of Wilcoxon-Statist.(n=6,m=4)")
plot(x, Fx,type="s", col="blue",
     main= "Distribution of Wilcoxon-Statist.(n=6,m=4)")
abline(h=0:1, col="gray20",lty=2)
layout(1)# set back

N <- 200
hist(U <- rwilcox(N, m=4,n=6), breaks=0:25 - 1/2, border="red", col="pink",
     sub = paste("N =",N))
mtext("N * f(x),  f() = true \"density\"", side=3, col="blue")
 lines(x, N*fx, type='h', col='blue', lwd=2)
points(x, N*fx, cex=2)

## Better is a Quantile-Quantile Plot
qqplot(U, qw <- qwilcox((1:N - 1/2)/N, m=4,n=6),
       main = paste("Q-Q-Plot of empirical and theoretical quantiles",
                     "Wilcoxon Statistic,  (m=4, n=6)",sep="\n"))
n <- as.numeric(names(print(tU <- table(U))))
text(n+.2, n+.5, labels=tU, col="red")
}
\keyword{distribution}
\eof
\name{abbreviate}
\title{Abbreviate Strings}
\usage{
abbreviate(names.arg, minlength = 4, use.classes = TRUE,
           dot = FALSE)
}
\alias{abbreviate}
\arguments{
  \item{names.arg}{a vector of names to be abbreviated.}
  \item{minlength}{the minimum length of the abbreviations.}
  \item{use.classes}{logical (currently ignored by \R).}
  \item{dot}{logical; should a dot (\code{"."}) be appended?}
}
\description{
  Abbreviate strings to at least \code{minlength} characters,
  such that they remain \emph{unique} (if they were).
}
\details{
  The algorithm used is similar to that of S.
  First spaces at the beginning of the word are stripped.
  Then any other spaces are stripped.
  Next lower case vowels are removed followed by lower case consonants.
  Finally if the abbreviation is still longer than \code{minlength}
  upper case letters are stripped.

  Letters are always stripped from the end of the word first.
  If an element of \code{names.arg} contains more than one word (words
  are separated by space) then at least one letter from each word will be
  retained.
  If a single string is passed it is abbreviated in the same manner as a
  vector of strings.

  Missing (\code{NA}) values are not abbreviated.
  
  If \code{use.classes} is \code{FALSE} then the only distinction is to
  be between letters and space.  This has NOT been implemented.
}
\value{
  A character vector containing abbreviations for the strings in its
  first argument.  Duplicates in the original \code{names.arg} will be
  given identical abbreviations.  If any non-duplicated elements have
  the same \code{minlength} abbreviations then \code{minlength} is
  incremented by one and new abbreviations are found for those elements
  only.  This process is repeated until all unique elements of
  \code{names.arg} have unique abbreviations.

  The character version of \code{names.arg} is attached to the returned
  value as a names argument.
}
\seealso{
  \code{\link{substr}}.
}
\examples{
x <- c("abcd", "efgh", "abce")
abbreviate(x, 2)

data(state)
(st.abb <- abbreviate(state.name, 2))
table(nchar(st.abb))# out of 50, 3 need 4 letters
}
\keyword{character}
\eof
\name{abline}
\alias{abline}
\title{Add a Straight Line to a Plot}
\description{
  This function adds one or more straight lines through the current plot.
}
\synopsis{
abline(a = NULL, b = NULL, h = NULL, v = NULL, reg = NULL,
       coef = NULL, untf = FALSE, col = par("col"),
       lty = par("lty"), lwd = NULL, ...)
}
\usage{
abline(a, b, untf = FALSE, \dots)
abline(h=, untf = FALSE, \dots)
abline(v=, untf = FALSE, \dots)
abline(coef=, untf = FALSE, \dots)
abline(reg=, untf = FALSE, \dots)
}
\arguments{
  \item{a,b}{the intercept and slope.}
  \item{untf}{logical asking to \emph{untransform}.  See Details.}
  \item{h}{the y-value for a horizontal line.}
  \item{v}{the x-value for a vertical line.}
  \item{coef}{a vector of length two giving the intercept and slope.}
  \item{reg}{an object with a \code{coef} component. See Details.}
  \item{\dots}{graphical parameters.}
}
\details{
  The first form specifies the line in intercept/slope form
  (alternatively \code{a} can be specified on its own and is taken to
  contain the slope and intercept in vector form).

  The \code{h=} and \code{v=} forms draw horizontal and vertical lines
  at the specified coordinates.

  The \code{coef} form specifies the line by a vector containing the
  slope and intercept.

  \code{reg} is a regression object which contains \code{reg$coef}.  If
  it is of length 1 then the value is taken to be the slope of a line
  through the origin, otherwise, the first 2 values are taken to be the
  intercept and slope.

  If \code{untf} is true, and one or both axes are log-transformed, then
  a curve is drawn corresponding to a line in original coordinates,
  otherwise a line is drawn in the transformed coordinate system. The
  \code{h} and \code{v} parameters always refer to original coordinates.

  The graphical parameters \code{col} and \code{lty} can be specified as
  arguments to \code{abline}; see \code{par} for details.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{lines}} and \code{\link{segments}} for connected and
  arbitrary lines given by their \emph{endpoints}.
  \code{\link{par}}.
}
\examples{
data(cars)
z <- lm(dist ~ speed, data = cars)
plot(cars)
abline(z)
}
\keyword{aplot}
\eof
\name{add1}
\alias{add1}
\alias{add1.default}
\alias{add1.lm}
\alias{add1.glm}
\alias{add1.mlm}
\alias{drop1}
\alias{drop1.default}
\alias{drop1.lm}
\alias{drop1.glm}
\alias{drop1.mlm}
\title{Add or Drop All Possible Single Terms to a Model}
\usage{
add1(object, scope, \dots)

\method{add1}{default}(object, scope, scale = 0, test = c("none", "Chisq"),
     k = 2, trace = FALSE, \dots)

\method{add1}{lm}(object, scope, scale = 0, test = c("none", "Chisq", "F"),
     x = NULL, k = 2, \dots)

\method{add1}{glm}(object, scope, scale = 0, test = c("none", "Chisq", "F"),
     x = NULL, k = 2, \dots)

drop1(object, scope, \dots)

\method{drop1}{default}(object, scope, scale = 0, test = c("none", "Chisq"),
      k = 2, trace = FALSE, \dots)

\method{drop1}{lm}(object, scope, scale = 0, all.cols = TRUE,
      test=c("none", "Chisq", "F"),k = 2, \dots)

\method{drop1}{glm}(object, scope, scale = 0, test = c("none", "Chisq", "F"),
      k = 2, \dots)
}
\arguments{
  \item{object}{a fitted model object.}
  \item{scope}{a formula giving the terms to be considered for adding or
    dropping.}
  \item{scale}{an estimate of the residual mean square to be
    used in computing \eqn{C_p}{Cp}. Ignored if \code{0} or \code{NULL}.}
  \item{test}{should the results include a test statistic relative to the
    original model?  The F test is only appropriate for \code{\link{lm}} and
    \code{\link{aov}} models or perhaps for \code{\link{glm}} fits with
    estimated dispersion.
    The \eqn{\chi^2}{Chisq} test can be an exact test
    (\code{lm} models with known scale) or a likelihood-ratio test or a
    test of the reduction in scaled deviance depending on the method.}
  \item{k}{the penalty constant in AIC / \eqn{C_p}{Cp}.}
  \item{trace}{if \code{TRUE}, print out progress reports.}
  \item{x}{a model matrix containing columns for the fitted model and all
    terms in the upper scope.  Useful if \code{add1} is to be called
    repeatedly.}
  \item{all.cols}{(Provided for compatibility with S.) Logical to specify
    whether all columns of the design matrix should be used. If
    \code{FALSE} then non-estimable columns are dropped, but the result
    is not usually statistically meaningful.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\description{
  Compute all the single terms in the \code{scope} argument that can be
  added to or dropped from the model, fit those models and compute a
  table of the changes in fit.
}
\details{
  For \code{drop1} methods, a missing \code{scope} is taken to be all
  terms in the model. The hierarchy is respected when considering terms
  to be added or dropped: all main effects contained in a second-order
  interaction must remain, and so on.

  The methods for \code{\link{lm}} and \code{\link{glm}} are more
  efficient in that they do not recompute the model matrix and call the
  \code{fit} methods directly.

  The default output table gives AIC, defined as minus twice log
  likelihood plus \eqn{2p} where \eqn{p} is the rank of the model (the
  number of effective parameters).  This is only defined up to an
  additive constant (like log-likelihoods).  For linear Gaussian models
  with fixed scale, the constant is chosen to give Mallows' \eqn{C_p}{Cp},
  \eqn{RSS/scale + 2p - n}.  Where \eqn{C_p}{Cp} is used,
  the column is labelled as \code{Cp} rather than \code{AIC}.
}
\value{
  An object of class \code{"anova"} summarizing the differences in fit
  between the models.
}
\author{
  The design was inspired by the S functions of the same names described
  in Chambers (1992).
}
\references{
  Chambers, J. M. (1992)
  \emph{Linear models.}
  Chapter 4 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\note{
  These are not fully equivalent to the functions in S.  There is no
  \code{keep} argument, and the methods used are not quite so
  computationally efficient.
    
  Their authors' definitions of Mallows' \eqn{C_p}{Cp} and Akaike's AIC
  are used, not those of the authors of the models chapter of S.
}
\section{Warning}{
  The model fitting must apply the models to the same dataset. Most
  methods will attempt to use a subset of the data with no missing
  values for any of the variables if \code{na.action=na.omit}, but
  this may give biased results.  Only use
  these functions with data containing missing values with great care.
}
\seealso{
  \code{\link{step}}, \code{\link{aov}}, \code{\link{lm}},
  \code{\link{extractAIC}}, \code{\link{anova}}
}
\examples{
example(step)#-> swiss
add1(lm1, ~ I(Education^2) + .^2)
drop1(lm1, test="F")  # So called 'type II' anova

example(glm)
drop1(glm.D93, test="Chisq")
drop1(glm.D93, test="F")
}
\keyword{models}
\eof
\name{aggregate}
\alias{aggregate}
\alias{aggregate.default}
\alias{aggregate.data.frame}
\alias{aggregate.ts}
\title{Compute Summary Statistics of Data Subsets}
\usage{
aggregate(x, \dots)

\method{aggregate}{default}(x, \dots)

\method{aggregate}{data.frame}(x, by, FUN, \dots)

\method{aggregate}{ts}(x, nfrequency = 1, FUN = sum, ndeltat = 1,
          ts.eps = getOption("ts.eps"), \dots)
}
\description{
  Splits the data into subsets, computes summary statistics for each,
  and returns the result in a convenient form.
}
\arguments{
  \item{x}{an R object.}
  \item{by}{a list of grouping elements, each as long as the variables
    in \code{x}.  Names for the grouping variables are provided if
    they are not given.  The elements of the list will be coerced to
    factors (if they are not already factors).}
  \item{FUN}{a scalar function to compute the summary statistics which
    can be applied to all data subsets.}
  \item{nfrequency}{new number of observations per unit of time; must
    be a divisor of the frequency of \code{x}.}
  \item{ndeltat}{new fraction of the sampling period between
    successive observations; must be a divisor of the sampling
    interval of \code{x}.}
  \item{ts.eps}{tolerance used to decide if \code{nfrequency} is a
    sub-multiple of the original frequency.}
  \item{\dots}{further arguments passed to or used by methods.}
}
\details{
  \code{aggregate} is a generic function with methods for data frames
  and time series.
  
  The default method \code{aggregate.default} uses the time series
  method if \code{x} is a time series, and otherwise coerces \code{x}
  to a data frame and calls the data frame method.

  \code{aggregate.data.frame} is the data frame method.  If \code{x}
  is not a data frame, it is coerced to one.  Then, each of the
  variables (columns) in \code{x} is split into subsets of cases
  (rows) of identical combinations of the components of \code{by}, and
  \code{FUN} is applied to each such subset with further arguments in
  \code{\dots} passed to it.
  (I.e., \code{tapply(VAR, by, FUN, \dots, simplify = FALSE)} is done
  for each variable \code{VAR} in \code{x}, conveniently wrapped into
  one call to \code{lapply()}.)
  Empty subsets are removed, and the result is reformatted into a data
  frame containing the variables in \code{by} and \code{x}.  The ones
  arising from \code{by} contain the unique combinations of grouping
  values used for determining the subsets, and the ones arising from
  \code{x} the corresponding summary statistics for the subset of the
  respective variables in \code{x}.
  
  \code{aggregate.ts} is the time series method.  If \code{x} is not a
  time series, it is coerced to one.  Then, the variables in \code{x}
  are split into appropriate blocks of length
  \code{frequency(x) / nfrequency}, and \code{FUN} is applied to each
  such block, with further (named) arguments in \code{\dots} passed to
  it.  The result returned is a time series with frequency
  \code{nfrequency} holding the aggregated values.
}
\author{Kurt Hornik}
\seealso{
  \code{\link{apply}}, \code{\link{lapply}}, \code{\link{tapply}}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
data(state)

## Compute the averages for the variables in 'state.x77', grouped
## according to the region (Northeast, South, North Central, West) that
## each state belongs to.
aggregate(state.x77, list(Region = state.region), mean)

## Compute the averages according to region and the occurrence of more
## than 130 days of frost.
aggregate(state.x77,
          list(Region = state.region,
               Cold = state.x77[,"Frost"] > 130),
          mean)
## (Note that no state in 'South' is THAT cold.)

data(presidents)
## Compute the average annual approval ratings for American presidents.
aggregate(presidents, nf = 1, FUN = mean)
## Give the summer less weight.
aggregate(presidents, nf = 1, FUN = weighted.mean, w = c(1, 1, 0.5, 1))
}
\keyword{category}
\keyword{array}
\eof
\name{agrep}
\alias{agrep}
\title{Approximate String Matching (Fuzzy Matching)}
\description{
  Searches for approximate matches to \code{pattern} (the first argument)
  within the string \code{x} (the second argument) using the Levenshtein
  edit distance.
}
\usage{
agrep(pattern, x, ignore.case = FALSE, value = FALSE, max.distance = 0.1)
}
\arguments{
  \item{pattern}{a non-empty character string to be matched (\emph{not}
    a regular expression!)}
  \item{x}{character vector where matches are sought.}
  \item{ignore.case}{if \code{FALSE}, the pattern matching is \emph{case
      sensitive} and if \code{TRUE}, case is ignored during matching.}
  \item{value}{if \code{FALSE}, a vector containing the (integer)
    indices of the matches determined is returned and if \code{TRUE}, a
    vector containing the matching elements themselves is returned.}
  \item{max.distance}{Maximum distance allowed for a match.  Expressed
    either as integer, or as a fraction of the pattern length (will be
    replaced by the smallest integer not less than the corresponding
    fraction), or a list with possible components
    \describe{
      \item{\code{all}:}{maximal (overall) distance}
      \item{\code{insertions}:}{maximum number/fraction of insertions}
      \item{\code{deletions}:}{maximum number/fraction of deletions}
      \item{\code{substitutions}:}{maximum number/fraction of
	substitutions}
    }
    If \code{all} is missing, it is set to 10\%, the other components
    default to \code{all}.  The component names can be abbreviated.
  }
}
\details{
  The Levensthein edit distance is used as measure of approximateness:
  it is the the total number of insertions, deletions and substitutions
  required to transform one string into another.

  The function is a simple interface to the \code{apse} library
  developed by Jarkko Hietaniemi (also used in the Perl String::Approx
  module).
}
\value{
  Either a vector giving the indices of the elements that yielded a
  match, of, if \code{value} is \code{TRUE}, the matched elements.
}
\author{David Meyer \email{David.Meyer@ci.tuwien.ac.at} (based on C code
  by Jarkko Hietaniemi); modifications by Kurt Hornik}
}
\seealso{\code{\link{grep}}}
\examples{
agrep("lasy", "1 lazy 2")
agrep("lasy", "1 lazy 2", max = list(sub = 0))
agrep("laysy", c("1 lazy", "1", "1 LAZY"), max = 2)
agrep("laysy", c("1 lazy", "1", "1 LAZY"), max = 2, value = TRUE)
agrep("laysy", c("1 lazy", "1", "1 LAZY"), max = 2, ignore.case = TRUE)
}
\keyword{character}
\eof
\name{airmiles}
\docType{data}
\alias{airmiles}
\title{Passenger Miles on Commercial US Airlines, 1937--1960}
\description{
  The revenue passenger miles flown by commercial airlines in
  the United States for each year from 1937 to 1960.
}
\usage{data(airmiles)}
\format{
  A time-series of 24 observations; yearly, 1937--1960.
}
\source{F.A.A. Statistical Handbook of Aviation.}
\references{
  Brown, R. G. (1963)
  \emph{Smoothing, Forecasting and Prediction of Discrete Time Series}.
  Prentice-Hall.
}
\examples{
data(airmiles)
plot(airmiles, main = "airmiles data",
     xlab = "Passenger-miles flown by U.S. commercial airlines", col = 4)
}
\keyword{datasets}
\eof
\name{airquality}
\docType{data}
\alias{airquality}
\title{New York Air Quality Measurements}
\description{
  Daily air quality measurements in New York, May to September 1973.
}
\usage{data(airquality)}
\format{
  A data frame with 154 observations on 6 variables.

  \tabular{rlll}{
    \code{[,1]} \tab \code{Ozone}   \tab numeric \tab Ozone (ppb)\cr
    \code{[,2]} \tab \code{Solar.R} \tab numeric \tab Solar R (lang)\cr
    \code{[,3]} \tab \code{Wind}    \tab numeric \tab Wind (mph)\cr
    \code{[,4]} \tab \code{Temp}    \tab numeric \tab Temperature (degrees F)\cr
    \code{[,5]} \tab \code{Month}   \tab numeric \tab Month (1--12)\cr
    \code{[,6]} \tab \code{Day}     \tab numeric \tab Day of month (1--31)
  }
}
\details{
  Daily readings of the following air quality values for May 1, 1973 (a
  Tuesday) to September 30, 1973.

  \itemize{
    \item \code{Ozone}: Mean ozone in parts per
    billion from 1300 to 1500 hours at Roosevelt Island
    \item \code{Solar.R}: Solar radiation
    in Langleys in the frequency band 4000--7700 Angstroms from
    0800 to 1200 hours at Central Park
    \item \code{Wind}: Average wind speed in miles
    per hour at 0700 and 1000 hours at LaGuardia Airport
    \item \code{Temp}: Maximum daily
    temperature in degrees Fahrenheit at La Guardia Airport.
  }
}
\source{
  The data were obtained from the New York State Department of
  Conservation (ozone data) and the National Weather Service
  (meteorological data).
}
\references{
  Chambers, J. M., Cleveland, W. S., Kleiner, B. and Tukey, P. A. (1983)
  \emph{Graphical Methods for Data Analysis}.
  Belmont, CA: Wadsworth.
}
\examples{
data(airquality)
pairs(airquality, panel = panel.smooth, main = "airquality data")
}
\keyword{datasets}
\eof
\name{alias}
\title{Find Aliases (Dependencies) in a Model}
\usage{
alias(object, \dots)

\method{alias}{formula}(object, data, \dots)

\method{alias}{lm}(object, complete = TRUE, partial = FALSE,
      partial.pattern = FALSE, \dots)
}
\alias{alias}
\alias{alias.formula}
\alias{alias.lm}
\alias{print.mtable}
\arguments{
  \item{object}{A fitted model object, for example from \code{lm} or
    \code{aov}, or a formula for \code{alias.formula}.}
  \item{data}{Optionally, a data frame to search for the objects
    in the formula.}
  \item{complete}{Should information on complete aliasing be included?}
  \item{partial}{Should information on partial aliasing be included?}
  \item{partial.pattern}{Should partial aliasing be presented in a
    schematic way? If this is done, the results are presented in a
    more compact way, usually giving the deciles of the coefficients.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\description{
  Find aliases (linearly dependent terms) in a linear model specified by
  a formula.
}
\details{
  Although the main method is for class \code{"lm"}, \code{alias} is
  most useful for experimental designs and so is used with fits from
  \code{aov}.
  Complete aliasing refers to effects in linear models that cannot be estimated
  independently of the terms which occur earlier in the model and so
  have their coefficients omitted from the fit. Partial aliasing refers
  to effects that can be estimated less precisely because of
  correlations induced by the design.
}
\value{
  A list (of \code{\link[base]{class} "listof"}) containing components
  \item{Model}{Description of the model; usually the formula.}
  \item{Complete}{A matrix with columns corresponding to effects that
    are linearly dependent on the rows; may be of class \code{"mtable"}
    which has its own \code{\link{print}} method.}
  \item{Partial}{The correlations of the estimable effects, with a zero
    diagonal.}
}
\note{The aliasing pattern may depend on the contrasts in use: Helmert
  contrasts are probably most useful.

  The defaults are different from those in S.
}
\references{
  Chambers, J. M., Freeny, A and Heiberger, R. M. (1992)
  \emph{Analysis of variance; designed experiments.}
  Chapter 5 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\author{
  The design was inspired by the S function of the same name described
  in Chambers \emph{et al.} (1992).
}
\examples{
had.VR <- "package:MASS" \%in\% search()
## The next line is for fractions() which gives neater results
if(!had.VR) res <- require(MASS)
## From Venables and Ripley (2002) p.165.
N <- c(0,1,0,1,1,1,0,0,0,1,1,0,1,1,0,0,1,0,1,0,1,1,0,0)
P <- c(1,1,0,0,0,1,0,1,1,1,0,0,0,1,0,1,1,0,0,1,0,1,1,0)
K <- c(1,0,0,1,0,1,1,0,0,1,0,1,0,1,1,0,0,0,1,1,1,0,1,0)
yield <- c(49.5,62.8,46.8,57.0,59.8,58.5,55.5,56.0,62.8,55.8,69.5,55.0,
           62.0,48.8,45.5,44.2,52.0,51.5,49.8,48.8,57.2,59.0,53.2,56.0)
npk <- data.frame(block=gl(6,4), N=factor(N), P=factor(P),
                  K=factor(K), yield=yield)

op <- options(contrasts=c("contr.helmert", "contr.poly"))
npk.aov <- aov(yield ~ block + N*P*K, npk)
alias(npk.aov)
if(!had.VR && res) detach(package:MASS)
options(op)# reset
}
\keyword{models}
\eof
\name{all}
\title{Are All Values True?}
\usage{
all(\dots, na.rm = FALSE)
}
\alias{all}
\description{
  Given a set of logical vectors, are all of the values true?
}
\arguments{
  \item{\dots}{one or more logical vectors.}
  \item{na.rm}{logical. If true \code{NA} values are removed before
    the result is computed.}
}
\value{
  Given a sequence of logical arguments, a logical value indicating
  whether or not all of the elements of \code{x} are \code{TRUE}.

  The value returned is \code{TRUE} if all the values in \code{x}
  are \code{TRUE}, and \code{FALSE} if any the values in \code{x}
  are \code{FALSE}.

  If \code{x} consists of a mix of \code{TRUE} and \code{NA} values,
  then value is \code{NA}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{any}}, the \dQuote{complement} of \code{all}, and
  \code{\link{stopifnot}(*)} which is an \code{all(*)}
  \dQuote{insurance}.
}
\examples{
range(x <- sort(round(rnorm(10) - 1.2,1)))
if(all(x < 0)) cat("all x values are negative\n")
}
\keyword{logic}
\eof
\name{all.equal}
\title{Test if Two Objects are (Nearly) Equal}
\alias{all.equal}
\alias{all.equal.default}
\alias{all.equal.numeric}
\alias{all.equal.character}
\alias{all.equal.factor}
\alias{all.equal.formula}
\alias{all.equal.list}
\alias{all.equal.language}
\alias{attr.all.equal}
\usage{
all.equal(target, current, \dots)

\method{all.equal}{numeric}(target, current,
          tolerance= .Machine$double.eps ^ 0.5, scale=NULL, \dots)
}
\arguments{
  \item{target}{\R object.}
  \item{current}{other \R object, to be compared with \code{target}.}
  \item{\dots}{Further arguments for different methods, notably the
    following two, for numerical comparison:}
  \item{tolerance}{numeric \eqn{\ge}{>=} 0.  Differences smaller than
    \code{tolerance} are not considered.}
  \item{scale}{numeric scalar > 0 (or \code{NULL}). See Details.}
}
\description{
    \code{all.equal(x,y)} is a utility to compare \R objects \code{x}
    and \code{y} testing \dQuote{near equality}.  If they are different,
    comparison is still made to some extent, and a report of the
    differences is returned.  Don't use \code{all.equal} directly in
    \code{if} expressions---either use \code{\link{identical}} or combine
    the two, as shown in the documentation for \code{identical}.
}
\details{
    There are several methods available, most of which are dispatched by
    the default method, see \code{\link{methods}("all.equal")}.
    \code{all.equal.list} and \code{all.equal.language} provide
    comparison of recursive objects.

    Numerical comparisons for \code{scale = NULL} (the default) are done
    by first computing the mean absolute difference of the two numerical
    vectors. If this is smaller than \code{tolerance} or not finite,
    absolute differences are used, otherwise relative differences scaled
    by the mean absolute difference.

    If \code{scale} is positive, absolute comparisons are after scaling
    (dividing) by \code{scale}.

    For complex arguments, \code{\link{Mod}} of difference is used.

    \code{attr.all.equal} is used for comparing
    \code{\link{attributes}}, returning \code{NULL} or \code{character}.
}
\value{
    Either \code{TRUE} or a vector of \code{\link{mode}}
    \code{"character"} describing the differences between \code{target}
    and \code{current}.

  Numerical differences are reported by relative error
}
\references{
  Chambers, J. M. (1998)
  \emph{Programming with Data. A Guide to the S Language}.
  Springer (for \code{=}).
}
\seealso{\code{\link{==}}, and \code{\link{all}} for exact equality testing.}
\examples{
all.equal(pi, 355/113) # not precise enough (default tol) > relative error

d45 <- pi*(1/4 + 1:10)
stopifnot(
all.equal(tan(d45), rep(1,10))) # TRUE, but
all      (tan(d45) == rep(1,10)) # FALSE, since not exactly
all.equal(tan(d45), rep(1,10), tol=0) # to see difference

all.equal(options(), .Options)
all.equal(options(), as.list(.Options))# TRUE
.Options $ myopt <- TRUE
all.equal(options(), as.list(.Options))
rm(.Options)
}
\keyword{utilities}
\keyword{logic}
\keyword{arith}


\eof
\name{all.names}
\alias{all.names}
\alias{all.vars}
\title{Find All Names in an Expression}
\description{
  Return a character vector containing all the names which occur in an
  expression or call.
}
\usage{
all.names(expr, functions = TRUE, max.names = 200, unique = FALSE)

all.vars(expr, functions = FALSE, max.names = 200, unique = TRUE)
}
\arguments{
  \item{expr}{an expression or call from which the names are to be
    extracted.}
  \item{functions}{a logical value indicating whether function names
    should be included in the result.}
  \item{max.names}{the maximum number of names to be returned.}
  \item{unique}{a logical value which indicates whether duplicate names
    should be removed from the value.}
}
\details{
  These functions differ only in the default values for their
  arguments.
}
\value{
  A character vector with the extracted names.
}
\examples{
all.names(expression(sin(x+y)))
all.vars(expression(sin(x+y)))
}
\keyword{programming}
\eof
\name{anova}
\alias{anova}
\alias{print.anova}
\title{Anova Tables}
\usage{
anova(object, \dots)
}
\description{
  Compute analysis of variance (or deviance) tables for one or more
  fitted model objects.
}
\arguments{
  \item{object}{an object containing the results returned by a model
    fitting function (e.g., \code{lm} or \code{glm}).} 
  \item{\dots}{additional objects of the same type.}
}
\value{
  This (generic) function returns an object of class \code{anova}.
  These objects represent analysis-of-variance and analysis-of-deviance tables.
  When given a single argument it produces a table which
  tests whether the model terms are significant.

  When given a sequence of objects, \code{anova} tests
  the models against one another in the order specified.

  The print method for \code{anova} objects prints
  tables in a \dQuote{pretty} form.
}
\section{Warning}{
  The comparison between two or more models will only be valid if they
  are fitted to the same dataset. This may be a problem if there are
  missing values and \R's default of \code{na.action = na.omit} is used.
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S}, Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{coefficients}}, \code{\link{effects}},
  \code{\link{fitted.values}}, \code{\link{residuals}},
  \code{\link{summary}}, \code{\link{drop1}}, \code{\link{add1}}.
}
\keyword{regression}
\keyword{models}
\eof
\name{anova.glm}
\title{Analysis of Deviance for Generalized Linear Model Fits}
\usage{
\method{anova}{glm}(object, \dots, dispersion = NULL, test = NULL)
}
\alias{anova.glm}
\alias{anova.glmlist}
%\alias{anova.glm.null}
\description{
  Compute an analysis of deviance table for one or more generalized
  linear model fits.
}
\arguments{
  \item{object, \dots}{objects of class \code{glm}, typically
    the result of a call to \code{\link{glm}}, or a list of
    \code{objects} for the \code{"glmlist"} method.}
  \item{dispersion}{the dispersion parameter for the fitting family.
    By default it is obtained from \code{glm.obj}.}
  \item{test}{a character string, (partially) matching one of \code{"Chisq"},
    \code{"F"} or \code{"Cp"}. See \code{\link{stat.anova}}.}
}
\details{
  Specifying a single object gives a sequential analysis of deviance
  table for that fit.  That is, the reductions in the residual deviance
  as each term of the formula is added in turn are given in as
  the rows of a table, plus the residual deviances themselves.

  If more than one object is specified, the table has a row for the
  residual degrees of freedom and deviance for each model.
  For all but the first model, the change in degrees of freedom and
  deviance is also given. (This only make statistical sense if the
  models are nested.)  It is conventional to list the models from
  smallest to largest, but this is up to the user.

  The table will optionally contain test statistics (and P values)
  comparing the reduction in deviance for the row to the residuals.
  For models with known dispersion (e.g., binomial and Poisson fits)
  the chi-squared test is most appropriate, and for those with
  dispersion estimated by moments (e.g., \code{gaussian},
  \code{quasibinomial} and \code{quasipoisson} fits) the F test is
  most appropriate.  Mallows' \eqn{C_p}{Cp} statistic is the residual
  deviance plus twice the estimate of \eqn{\sigma^2}{sigma^2} times
  the residual degrees of freedom, which is closely related to AIC (and
  a multiple of it if the dispersion is known).
}
\value{
  An object of class \code{"anova"} inheriting from class \code{"data.frame"}.
}
\section{Warning}{
  The comparison between two or more models by \code{anova} or
  \code{anova.glmlist} will only be valid if they
  are fitted to the same dataset. This may be a problem if there are
  missing values and \R's default of \code{na.action = na.omit} is used,
  and \code{anova.glmlist} will detect this with an error.
}
\references{
  Hastie, T. J. and Pregibon, D. (1992)
  \emph{Generalized linear models.}
  Chapter 6 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{glm}}, \code{\link{anova}}.

  \code{\link{drop1}} for
  so-called \sQuote{type II} anova where each term is dropped one at a
  time respecting their hierarchy.
}
\examples{
## --- Continuing the Example from  '?glm':%\code{\link{glm}}:
\dontshow{example("glm", echo = FALSE)}
anova(glm.D93)
anova(glm.D93, test = "Cp")
anova(glm.D93, test = "Chisq")
}
\keyword{models}
\keyword{regression}

\eof
\name{anova.lm}
\title{ANOVA for Linear Model Fits}
\usage{
\method{anova}{lm}(object, \dots)

anova.lmlist(object, \dots, scale = 0, test = "F")
}
\alias{anova.lm}
%\alias{anova.lm.null}
\alias{anova.lmlist}
\alias{anova.mlm}
\description{
  Compute an analysis of variance table for one or more linear model fits.
}
\arguments{
  \item{object, \dots}{objects of class \code{lm}, usually, a result of a
    call to \code{\link{lm}}.}
  \item{test}{a character string specifying the test statistic to be
    used. Can be one of \code{"F"}, \code{"Chisq"} or \code{"Cp"},
    with partial matching allowed, or \code{NULL} for no test.}
  \item{scale}{numeric. An estimate of the noise variance
    \eqn{\sigma^2}{sigma^2}. If zero this will be estimated from the
    largest model considered.
  }
}
\details{
  Specifying a single object gives a sequential analysis of variance
  table for that fit.  That is, the reductions in the residual sum of
  squares as each term of the formula is added in turn are given in as
  the rows of a table, plus the residual sum of squares.

  The table will contain F statistics (and P values) comparing the
  mean square for the row to the residual mean square.

  If more than one object is specified, the table has a row for the
  residual degrees of freedom and sum of squares for each model.
  For all but the first model, the change in degrees of freedom and sum
  of squares is also given. (This only make statistical sense if the
  models are nested.)  It is conventional to list the models from
  smallest to largest, but this is up to the user.

  Optionally the table can include test statistics.  Normally the
  F statistic is most appropriate, which compares the mean square for a
  row to the residual sum of squares for the largest model considered.
  If \code{scale} is specified chi-squared tests can be used. Mallows'
  \eqn{C_p}{Cp} statistic is the residual sum of squares plus twice the
  estimate of \eqn{\sigma^2}{sigma^2} times the residual degrees of freedom.
}
\value{
  An object of class \code{"anova"} inheriting from class \code{"data.frame"}.
}
\note{
  Versions of \R prior to 1.2.0 based F tests on pairwise comparisons,
  and this behaviour can still be obtained by a direct call to
  \code{anovalist.lm}.
}
\section{Warning}{
  The comparison between two or more models will only be valid if they
  are fitted to the same dataset. This may be a problem if there are
  missing values and \R's default of \code{na.action = na.omit} is used,
  and \code{anova.lmlist} will detect this with an error.
}
\references{
  Chambers, J. M. (1992)
  \emph{Linear models.}
  Chapter 4 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\seealso{
  The model fitting function \code{\link{lm}}, \code{\link{anova}}.

  \code{\link{drop1}} for
  so-called \sQuote{type II} anova where each term is dropped one at a
  time respecting their hierarchy.
}
\examples{
## sequential table
data(LifeCycleSavings)
fit <- lm(sr ~ ., data = LifeCycleSavings)
anova(fit)

## same effect via separate models
fit0 <- lm(sr ~ 1, data = LifeCycleSavings)
fit1 <- update(fit0, . ~ . + pop15)
fit2 <- update(fit1, . ~ . + pop75)
fit3 <- update(fit2, . ~ . + dpi)
fit4 <- update(fit3, . ~ . + ddpi)
anova(fit0, fit1, fit2, fit3, fit4, test="F")

anova(fit4, fit2, fit0, test="F") # unconventional order
}
\keyword{regression}
\keyword{models}
\eof
\name{anscombe}
\docType{data}
\alias{anscombe}
\title{Anscombe's Quartet of ``Identical'' Simple Linear Regressions}
\description{
  Four \eqn{x}-\eqn{y} datasets which have the same traditional
  statistical properties (mean, variance, correlation, regression line,
  etc.), yet are quite different.
}
\usage{data(anscombe)}
\format{
  A data frame with 11 observations on 8 variables.
  \tabular{rl}{
    x1 == x2 == x3 \tab the integers 4:14, specially arranged \cr
    x4             \tab values 8 and 19 \cr
    y1, y2, y3, y4 \tab numbers in (3, 12.5) with mean 7.5 and sdev 2.03}
}
\source{
  Tufte, Edward R. (1989)
  \emph{The Visual Display of Quantitative Information}, 13--14.
  Graphics Press.
}
\references{
  Anscombe, Francis J. (1973)  Graphs in statistical analysis.
  \emph{American Statistician}, \bold{27}, 17--21.
}
\examples{
data(anscombe)
summary(anscombe)

##-- now some "magic" to do the 4 regressions in a loop:
ff <- y ~ x
for(i in 1:4) {
  ff[2:3] <- lapply(paste(c("y","x"), i, sep=""), as.name)
  ## or   ff[[2]] <- as.name(paste("y", i, sep=""))
  ##      ff[[3]] <- as.name(paste("x", i, sep=""))
  assign(paste("lm.",i,sep=""), lmi <- lm(ff, data= anscombe))
  print(anova(lmi))
}

## See how close they are (numerically!)
sapply(objects(pat="lm\.[1-4]$"), function(n) coef(get(n)))
lapply(objects(pat="lm\.[1-4]$"), function(n) summary(get(n))$coef)

## Now, do what you should have done in the first place: PLOTS
op <- par(mfrow=c(2,2), mar=.1+c(4,4,1,1), oma= c(0,0,2,0))
for(i in 1:4) {
  ff[2:3] <- lapply(paste(c("y","x"), i, sep=""), as.name)
  plot(ff, data =anscombe, col="red", pch=21, bg = "orange", cex = 1.2,
       xlim=c(3,19), ylim=c(3,13))
  abline(get(paste("lm.",i,sep="")), col="blue")
}
mtext("Anscombe's 4 Regression data sets", outer = TRUE, cex=1.5)
par(op)
}
\keyword{datasets}
\eof
\name{any}
\title{Are Some Values True?}
\usage{
any(\dots, na.rm = FALSE)
}
\alias{any}
\description{
  Given a set of logical vectors, are any of the values true?
}
\arguments{
  \item{\dots}{one or more logical vectors.}
  \item{na.rm}{logical. If true \code{NA} values are removed before
    the result is computed.}
}
\value{
  Given a sequence of logical arguments, a logical value indicating
  whether or not any of the elements of \code{x} are \code{TRUE}.

  The value returned is \code{TRUE} if any the values in \code{x}
  are \code{TRUE}, and \code{FALSE} if all the values in \code{x}
  are \code{FALSE}.

  If \code{x} consists of a mix of \code{FALSE} and \code{NA} values,
  the value is \code{NA}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{all}}, the \dQuote{complement} of \code{any}.
}
\examples{
range(x <- sort(round(rnorm(10) - 1.2,1)))
if(any(x < 0)) cat("x contains negative values\n")
}
\keyword{logic}
\eof
\name{aov}
\title{Fit an Analysis of Variance Model}
\usage{
aov(formula, data = NULL, projections = FALSE, qr = TRUE,
    contrasts = NULL, \dots)
}
\alias{aov}
\alias{print.aov}
\alias{print.aovlist}
\alias{Error}
\arguments{
  \item{formula}{A formula specifying the model.}
  \item{data}{A data frame in which the variables specified in the
    formula will be found. If missing, the variables are searched for in
    the standard way.}
  \item{projections}{Logical flag: should the projections be returned?}
  \item{qr}{Logical flag: should the QR decomposition be returned?}
  \item{contrasts}{A list of contrasts to be used for some of the factors
    in the formula. These are not used for any \code{Error} term, and
    supplying contrasts for factors only in the \code{Error} term will give
    a warning.}
  \item{\dots}{Arguments to be passed to \code{lm}, such as \code{subset}
    or \code{na.action}.}
}
\description{
  Fit an analysis of variance model by a call to \code{lm} for each stratum.
}
\details{
  This provides a wrapper to \code{lm} for fitting linear models to
  balanced or unbalanced experimental designs.

  The main difference from \code{lm} is in the way \code{print},
  \code{summary} and so on handle the fit: this is expressed in the
  traditional language of the analysis of variance rather than of linear
  models.

  If the formula contains a single \code{Error} term, this is used to
  specify error strata, and appropriate models are fitted within each
  error stratum.

  The formula can specify multiple responses.

  Weights can be specified by a \code{weights} argument, but should not
  be used with an \code{Error} term, and are incompletely supported
  (e.g., not by \code{\link{model.tables}}).
}
\value{
  An object of class \code{c("aov", "lm")} or for multiple responses
  of class \code{c("maov", "aov", "mlm", "lm")} or for multiple error
  strata of class \code{"aovlist"}.  There are
  \code{\link{print}} and \code{\link{summary}} methods available for these.
}
\references{
  Chambers, J. M., Freeny, A and Heiberger, R. M. (1992)
  \emph{Analysis of variance; designed experiments.}
  Chapter 5 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\author{
  The design was inspired by the S function of the same name described
  in Chambers \emph{et al.} (1992).
}
\seealso{
  \code{\link{lm}}, \code{\link{summary.aov}}, \code{\link{alias}},
  \code{\link{proj}}, \code{\link{model.tables}}, \code{\link{TukeyHSD}}
}
\examples{
## From Venables and Ripley (2002) p.165.
N <- c(0,1,0,1,1,1,0,0,0,1,1,0,1,1,0,0,1,0,1,0,1,1,0,0)
P <- c(1,1,0,0,0,1,0,1,1,1,0,0,0,1,0,1,1,0,0,1,0,1,1,0)
K <- c(1,0,0,1,0,1,1,0,0,1,0,1,0,1,1,0,0,0,1,1,1,0,1,0)
yield <- c(49.5,62.8,46.8,57.0,59.8,58.5,55.5,56.0,62.8,55.8,69.5,55.0,
           62.0,48.8,45.5,44.2,52.0,51.5,49.8,48.8,57.2,59.0,53.2,56.0)
npk <- data.frame(block=gl(6,4), N=factor(N), P=factor(P),
                  K=factor(K), yield=yield)

( npk.aov <- aov(yield ~ block + N*P*K, npk) )
summary(npk.aov)
coefficients(npk.aov)

## as a test, not particularly sensible statistically
op <- options(contrasts=c("contr.helmert", "contr.treatment"))
npk.aovE <- aov(yield ~  N*P*K + Error(block), npk)
npk.aovE
summary(npk.aovE)
options(op)# reset to previous
}
\keyword{models}
\keyword{regression}
\eof
\name{aperm}
\alias{aperm}
\title{Array Transposition}
\description{
  Transpose an array by permuting its dimensions and optionally resizing
  it.
}
\usage{
aperm(a, perm, resize = TRUE)
}
\arguments{
  \item{a}{the array to be transposed.}
  \item{perm}{the subscript permutation vector, which must be a
    permutation of the integers \code{1:n}, where \code{n} is the
    number of dimensions of \code{a}.  The default is to reverse the
    order of the dimensions.}
  \item{resize}{a flag indicating whether the vector should be
    resized as well as having its elements reordered (default \code{TRUE}).}
}
\value{
  A transposed version of array \code{a}, with subscripts permuted as
  indicated by the array \code{perm}.  If \code{resize} is \code{TRUE},
  the array is reshaped as well as having its elements permuted, the
  \code{dimnames} are also permuted;
  if \code{FALSE} then the returned object has the same dimensions as
  \code{a}, and the dimnames are dropped.

  The function \code{t} provides a faster and more convenient way of
  transposing matrices.
}
\author{Jonathan Rougier, \email{J.C.Rougier@durham.ac.uk} did the
  faster C implementation.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{\code{\link{t}}, to transpose matrices.
}
\examples{
# interchange the first two subscripts on a 3-way array x
x  <- array(1:24, 2:4)
xt <- aperm(x, c(2,1,3))
stopifnot(t(xt[,,2]) == x[,,2],
          t(xt[,,3]) == x[,,3],
          t(xt[,,4]) == x[,,4])

}
\keyword{array}
\eof
\name{append}
\alias{append}
\title{Vector Merging}
\description{
  Add elements to a vector.
}
\usage{
append(x, values, after=length(x))
}
\arguments{
  \item{x}{the vector to be modified.}
  \item{values}{to be included in the modified vector.}
  \item{after}{a subscript, after which the values are to be appended.}
}
\value{
  A vector containing the values in \code{x} with the elements of
  \code{values} appended after the specified element of \code{x}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
append(1:5, 0:1, after=3)
}
\keyword{manip}
\eof
\name{apply}
\alias{apply}
\title{Apply Functions Over Array Margins}
\description{
  Returns a vector or array or list of values obtained by applying a
  function to margins of an array.
}
\usage{
apply(X, MARGIN, FUN, \dots)
}
\arguments{
  \item{X}{the array to be used.}
  \item{MARGIN}{a vector giving the subscripts which the function will
    be applied over.
    \code{1} indicates rows, \code{2} indicates columns,
    \code{c(1,2)} indicates rows and columns.}
  \item{FUN}{the function to be applied.
    In the case of functions like \code{+}, \code{\%*\%}, etc., the
    function name must be quoted.}
  \item{\dots}{optional arguments to \code{FUN}.}
}
\details{
  If \code{X} is not an array but has a dimension attribute,
  \code{apply} attempts to coerce it to an array via \code{as.matrix}
  if it is two-dimensional (e.g., data frames) or via \code{as.array}.
}
\value{
  If each call to \code{FUN} returns a vector of length \code{n}, then
  \code{apply} returns an array of dimension \code{c(n, dim(X)[MARGIN])}
  if \code{n > 1}.  If \code{n} equals \code{1}, \code{apply} returns a
  vector if \code{MARGIN} has length 1 and an array of dimension
  \code{dim(X)[MARGIN]} otherwise.
  If \code{n} is \code{0}, the result has length 0 but not necessarily
  the \dQuote{correct} dimension.

  If the calls to \code{FUN} return vectors of different lengths,
  \code{apply} returns a list of length \code{dim(X)[MARGIN]}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{lapply}}, \code{\link{tapply}}, and convenience functions
  \code{\link{sweep}} and \code{\link{aggregate}}.
}
\examples{
## Compute row and column sums for a matrix:
x <- cbind(x1 = 3, x2 = c(4:1, 2:5))
dimnames(x)[[1]] <- letters[1:8]
apply(x, 2, mean, trim = .2)
col.sums <- apply(x, 2, sum)
row.sums <- apply(x, 1, sum)
rbind(cbind(x, Rtot = row.sums), Ctot = c(col.sums, sum(col.sums)))

stopifnot( apply(x,2, is.vector)) # not ok in R <= 0.63.2

## Sort the columns of a matrix
apply(x, 2, sort)

##- function with extra args:
cave <- function(x, c1,c2) c(mean(x[c1]),mean(x[c2]))
apply(x,1, cave,  c1="x1", c2=c("x1","x2"))

ma <- matrix(c(1:4, 1, 6:8), nr = 2)
ma
apply(ma, 1, table)  #--> a list of length 2
apply(ma, 1, quantile)# 5 x n matrix with rownames

stopifnot(dim(ma) == dim(apply(ma, 1:2, sum)))## wasn't ok before R 0.63.1

}
\keyword{iteration}
\keyword{array}
\eof
\name{approxfun}
\alias{approx}
\alias{approxfun}
\title{Interpolation Functions}
\description{
  Return a list of points which linearly interpolate given data points,
  or a function performing the linear (or constant) interpolation.
}
\usage{
approx   (x, y = NULL, xout, method="linear", n=50,
          yleft, yright, rule = 1, f=0, ties = mean)

approxfun(x, y = NULL,       method="linear",
          yleft, yright, rule = 1, f=0, ties = mean)
}
\arguments{
  \item{x, y}{vectors giving the coordinates of the points to be
    interpolated.  Alternatively a single plotting structure can be
    specified: see \code{\link{xy.coords}}.}
  \item{xout}{an optional set of values specifying where interpolation
    is to take place.}
  \item{method}{specifies the interpolation method to be used.  Choices
    are \code{"linear"} or \code{"constant"}.}
  \item{n}{If \code{xout} is not specified, interpolation takes place at
    \code{n} equally spaced points spanning the interval [\code{min(x)},
    \code{max(x)}].}
  \item{yleft}{the value to be returned when input \code{x} values
    less than \code{min(x)}. The default is defined by the value
    of \code{rule} given below.}
  \item{yright}{the value to be returned when input \code{x} values
    greater than \code{max(x)}. The default is defined by the value
    of \code{rule} given below.}
  \item{rule}{an integer describing how interpolation is to take place
    outside the interval [\code{min(x)}, \code{max(x)}].
    If \code{rule} is \code{1} then \code{NA}s are returned for such
    points and if it is \code{2}, the value at the closest data extreme
    is used.}
  \item{f}{For \code{method="constant"} a number between 0 and 1
    inclusive, indicating a compromise between left- and
    right-continuous step functions. If \code{y0} and \code{y1} are the
    values to the left and right of the point then the value is
    \code{y0*(1-f)+y1*f} so that \code{f=0} is right-continuous and
    \code{f=1} is left-continuous.}
  \item{ties}{Handling of tied \code{x} values. Either a function
    with a single vector argument returning a single number result or
    the string \code{"ordered"}.}
}
\value{
  \code{approx} returns a list with components \code{x} and \code{y},
  containing \code{n} coordinates which interpolate the given data
  points according to the \code{method} (and \code{rule}) desired.

  The function \code{approxfun} returns a function performing (linear or
  constant) interpolation of the given data points.  For a given set of
  \code{x} values, this function will return the corresponding
  interpolated values.  This is often more useful than \code{approx}.
}
\details{
  The inputs can contain missing values which are deleted, so at least
  two complete \code{(x, y)} pairs are required.  If there are
  duplicated (tied) \code{x} values and \code{ties} is a function it is
  applied to the \code{y} values for each distinct \code{x} value.
  Useful functions in this context include \code{\link{mean}},
  \code{\link{min}}, and \code{\link{max}}.  If \code{ties="ordered"}
  the \code{x} values are assumed to be already ordered.  The first
  \code{y} value will be used for interpolation to the left and the last
  one for interpolation to the right.
}
\seealso{
  \code{\link{spline}} and \code{\link{splinefun}} for spline
  interpolation.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
x <- 1:10
y <- rnorm(10)
par(mfrow = c(2,1))
plot(x, y, main = "approx(.) and approxfun(.)")
points(approx(x, y), col = 2, pch = "*")
points(approx(x, y, method = "constant"), col = 4, pch = "*")

f <- approxfun(x, y)
curve(f(x), 0, 10, col = "green")
points(x, y)
is.function(fc <- approxfun(x, y, method = "const")) # TRUE
curve(fc(x), 0, 10, col = "darkblue", add = TRUE)

## Show treatment of 'ties' :

x <- c(2,2:4,4,4,5,5,7,7,7)
y <- c(1:6, 5:4, 3:1)
approx(x,y, xout=x)$y # warning
(ay <- approx(x,y, xout=x, ties = "ordered")$y)
stopifnot(ay == c(2,2,3,6,6,6,4,4,1,1,1))
approx(x,y, xout=x, ties = min)$y
approx(x,y, xout=x, ties = max)$y

%%-- MM has nice utility plotting -- do in demo ?
}
\keyword{arith}
\keyword{dplot}
\eof
\name{apropos}
\title{Find Objects by (Partial) Name}
\usage{
apropos(what, where = FALSE, mode = "any")

find(what, mode = "any", numeric. = FALSE, simple.words = TRUE)
}
\alias{apropos}
\alias{find}
\arguments{
  \item{what}{name of an object, or regular expression to match against}
  \item{where, numeric.}{a logical indicating whether positions in the
    search list should also be returned}
  \item{mode}{character; if not \code{"any"}, only objects who's
    \code{\link{mode}} equals \code{mode} are searched.}
  \item{simple.words}{logical; if \code{TRUE}, the \code{what} argument is
    only searched as whole only word.}
}
\description{
  \code{apropos} returns a character vector giving the names of
  all objects in the search list matching \code{what}.

  \code{find} is a different user interface to the same task as \code{apropos}.
}
\details{
  If \code{mode != "any"} only those objects which are of mode \code{mode}
  are considered.
  If \code{where} is \code{TRUE}, the positions in the search list are
  returned as the names attribute.

  \code{find} is a different user interface for the same task as \code{apropos}.
  However, by default (\code{simple.words == TRUE}), only full words are
  searched.
}
\author{Kurt Hornik and Martin Maechler (May 1997).}
\seealso{
  \code{\link{objects}} for listing objects from one place,
  \code{\link{help.search}} for searching the help system,
  \code{\link{search}} for the search path.
}
\examples{
%% some of these have enormous output that varies a lot by version
\dontrun{apropos("lm")}
apropos(ls)
apropos("lq")

lm <- 1:pi
find(lm)        #> ".GlobalEnv"   "package:base"
find(lm, num=TRUE) # numbers with these names
find(lm, num=TRUE, mode="function")# only the second one
rm(lm)

\dontrun{apropos(".", mode="list") # a long list}

# need a DOUBLE backslash '\\\\' (in case you don't see it anymore)
apropos("\\\\[")

\dontrun{# everything % not diff-able
length(apropos("."))

# those starting with 'pr'
apropos("^pr")

# the 1-letter things
apropos("^.$")
# the 1-2-letter things
apropos("^..?$")
# the 2-to-4 letter things
apropos("^.{2,4}$")

# the 8-and-more letter things
apropos("^.{8,}$")
table(nchar(apropos("^.{8,}$")))
}}
\keyword{data}
\keyword{documentation}
\keyword{environment}
\eof
\name{args}
\alias{args}
\title{Argument List of a Function}
\description{
  Displays the argument names and corresponding default values of a
  function.
}
\usage{
args(name)
}
\arguments{
  \item{name}{an interpreted function.
    If \code{name} is a character string then the function with that
    name is found and used.}
}
\value{
  A function with identical formal argument list but an empty body if
  given an interpreted function; \code{NULL} in case of a variable or
  primitive (non-interpreted) function.
}
\details{
  This function is mainly used interactively.
  For programming, use \code{\link{formals}} instead.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{formals}},
  \code{\link{help}}.
}
\examples{
args(c)            # -> NULL (c is a 'primitive' function)
args(plot.default)
}
\keyword{documentation}
\eof
\name{array}
\alias{array}
\alias{as.array}
\alias{is.array}
\title{Multi-way Arrays}
\description{
  Creates or tests for arrays.
}
\usage{
array(data = NA, dim = length(data), dimnames = NULL)
as.array(x)
is.array(x)
}
\arguments{
  \item{data}{a vector giving data to fill the array.}
  \item{dim}{the dim attribute for the array to be created, that is a
    vector of length one or more giving the maximal indices in
    each dimension.}
  \item{dimnames}{the names for the dimensions. This is a list with one
    component for each dimension, either NULL or a character vector of
    the length given by \code{dim} for that dimension.  The list can be
    names, and the names will be used as names for the dimensions.}
  \item{x}{an \R object.}
}
\value{
  \code{array} returns an array with the extents specified in \code{dim}
  and naming information in \code{dimnames}.  The values in \code{data} are
  taken to be those in the array with the leftmost subscript moving
  fastest.  If there are too few elements in \code{data} to fill the array,
  then the elements in \code{data} are recycled.

  \code{as.array()} coerces its argument to be an array by attaching a
  \code{\link{dim}} attribute to it.  It also attaches
  \code{\link{dimnames}} if \code{x} has \code{\link{names}}.
  The sole purpose of this is to make it possible to access the
  \code{dim}[names] attribute at a later time.

  \code{is.array} returns \code{TRUE} or \code{FALSE} depending on
  whether its argument is an array (i.e., has a \code{dim} attribute)
  or not. It is generic: you can write methods to handle
  of specific classes of objects, see \link{InternalMethods}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{aperm}}, \code{\link{matrix}},
  \code{\link{dim}}, \code{\link{dimnames}}.
}
\examples{
dim(as.array(letters))
array(1:3, c(2,4)) # recycle 1:3 "2 2/3 times"
#     [,1] [,2] [,3] [,4]
#[1,]    1    3    2    1
#[2,]    2    1    3    2

# funny object:
str(a0 <- array(1:3, 0))
}
\keyword{array}
\eof
\name{arrows}
\title{Add Arrows to a Plot}
\usage{
arrows(x0, y0, x1, y1, length = 0.25, angle = 30, code = 2,
       col = par("fg"), lty = NULL, lwd = par("lwd"), xpd = NULL)
}
\alias{arrows}
\arguments{
  \item{x0, y0}{coordinates of points \bold{from} which to draw.}
  \item{x1, y1}{coordinates of points \bold{to} which to draw.}
  \item{length}{length of the edges of the arrow head (in inches).}
  \item{angle}{angle from the shaft of the arrow to the edge of the
    arrow head.}
  \item{code}{integer code, determining \emph{kind} of arrows to be
    drawn.}
  \item{col, lty, lwd, xpd}{usual graphical parameters as in
    \code{\link{par}}.}
}
\description{
  Draw arrows between pairs of points.
}
\details{
  For each \code{i}, an arrow is drawn between the point \code{(x0[i],
    y0[i])} and the point \code{(x1[i],y1[i])}.

  If \code{code=2} an arrowhead is drawn at \code{(x0[i],y0[i])} and if
  \code{code=1} an arrowhead is drawn at \code{(x1[i],y1[i])}.  If
  \code{code=3} a head is drawn at both ends of the arrow.  Unless
  \code{length = 0}, when no head is drawn.

  The graphical parameters \code{col} and \code{lty} can be used
  to specify a color and line texture for the line segments which
  make up the arrows (\code{col} may be a vector).

  The direction of a zero-length arrow is indeterminate, and hence so is
  the direction of the arrowheads.  To allow for rounding error,
  arrowheads are omitted (with a warning) on any arrow of length less
  than 1/1000 inch.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{segments}} to draw segments.
}
\examples{
x <- runif(12); y <- rnorm(12)
i <- order(x,y); x <- x[i]; y <- y[i]
plot(x,y, main="arrows(.) and segments(.)")
## draw arrows from point to point :
s <- seq(length(x)-1)# one shorter than data
arrows(x[s], y[s], x[s+1], y[s+1], col= 1:3)
s <- s[-length(s)]
segments(x[s], y[s], x[s+2], y[s+2], col= 'pink')
}
\keyword{aplot}
\eof
\name{as.POSIX*}
\alias{as.POSIXct}
\alias{as.POSIXct.default}
\alias{as.POSIXct.POSIXlt}
\alias{as.POSIXct.date}
\alias{as.POSIXct.dates}
\alias{as.POSIXlt}

\title{Date-time Conversion Functions}
\description{
  Functions to manipulate objects of classes \code{"POSIXlt"} and
  \code{"POSIXct"} representing calendar dates and times (to the nearest
  second). 
}
\usage{
as.POSIXct(x, tz = "")
as.POSIXlt(x, tz = "")

}
\arguments{
  \item{x}{An object to be converted.}
  \item{tz}{A timezone specification to be used for the conversion,
    \emph{if one is required}.  System-specific, but \code{""}
    is the current timezone, and \code{"GMT"} is UTC
    (Coordinated Universal Time, in French).}
}
\details{
  The \code{as.POSIX*} functions convert an object to one of the two
  classes used to represent date/times (calendar dates plus time to the
  nearest second).  They can take convert a wide variety of objects,
  including objects of the other class and of classes \code{"date"}
  (from package \pkg{\link[date:as.date]{date}} or
  \pkg{\link[date:as.date]{survival}}), \code{"chron"} and
  \code{"dates"} (from package \pkg{\link[chron]{chron}}) to these
  classes.  They can also convert character strings of the formats
  \code{"2001-02-03"} and \code{"2001/02/03"} optionally followed by
  white space and a time in the format \code{"14:52"} or
  \code{"14:52:03"}.  (Formats such as \code{"01/02/03"} are ambiguous
  but can be converted via a format specification by
  \code{\link{strptime}}.)

  Logical \code{NA}s can be converted to either of the classes, but no
  other logical vectors can be.
}
\value{
  \code{as.POSIXct} and \code{as.POSIXlt} return an object of the
  appropriate class.  If \code{tz} was specified, \code{as.POSIXlt}
  will give an appropriate \code{"tzone"} attribute.
}
\note{
  If you want to extract specific aspects of a time (such as the day of
  the week) just convert it to class \code{"POSIXlt"} and extract the
  relevant component(s) of the list, or if you want a character
  representation (such as a named day of the week) use
  \code{\link{format.POSIXlt}} or \code{\link{format.POSIXct}}.

  If a timezone is needed and that specified is invalid on your system,
  what happens is system-specific but it will probably be ignored. 
}
\seealso{
  \link{DateTimeClasses} for details of the classes;
  \code{\link{strptime}} for conversion to and from character
  representations.
}
\examples{
(z <- Sys.time())             # the current date, as class "POSIXct"
unclass(z)                    # a large integer
floor(unclass(z)/86400)       # the number of days since 1970-01-01
(z <- as.POSIXlt(Sys.time())) # the current date, as class "POSIXlt"
unlist(unclass(z))            # a list shown as a named vector

as.POSIXlt(Sys.time(), "GMT") # the current time in GMT
}
\keyword{utilities}
\keyword{chron}
\eof
\name{as.data.frame}
\alias{as.data.frame}
\alias{is.data.frame}
\alias{as.data.frame.AsIs}
\alias{as.data.frame.character}
\alias{as.data.frame.complex}
\alias{as.data.frame.data.frame}
\alias{as.data.frame.default}
\alias{as.data.frame.factor}
\alias{as.data.frame.integer}
\alias{as.data.frame.list}
\alias{as.data.frame.logical}
\alias{as.data.frame.matrix}
\alias{as.data.frame.model.matrix}
\alias{as.data.frame.numeric}
\alias{as.data.frame.ordered}
\alias{as.data.frame.ts}
\alias{as.data.frame.vector}

\title{
  Coerce to a Data Frame
}
\description{
  Functions to check if an object is a data frame, or coerce it if possible.
}
\usage{
as.data.frame(x, row.names = NULL, optional = FALSE)
is.data.frame(x)
}
\arguments{
  \item{x}{any \R object.}
  \item{row.names}{\code{NULL} or a character vector giving the row
    names for the data frame.  Missing values are not allowed.}
  \item{optional}{logical. If \code{TRUE}, setting row names and
    converting column names (to syntactic names) is optional.}
}
\value{
  \code{as.data.frame} returns a data frame, normally with all row names
  \code{""} if \code{optional = TRUE}.

  \code{is.data.frame} returns \code{TRUE} if its argument is a data
  frame (that is, has \code{"data.frame"} amongst its classes)
  and \code{FALSE} otherwise.
}
\details{
  \code{as.data.frame} is a generic function with many methods, and
  users and packages can supply further methods.

  If a list is supplied, each element is converted to a column in the
  data frame.  Similarly, each column of a matrix is converted separately.
  This can be overridden if the object has a class which has
  a method for \code{as.data.frame}: two examples are
  matrices of class \code{"\link{model.matrix}"} (which are included as a
  single column) and list objects of class \code{"\link{POSIXlt}"} which are
  coerced to class \code{"\link{POSIXct}"}

  Character variables are converted to factor columns unless protected
  by \code{\link{I}}.

  If a data frame is supplied, all classes preceding \code{"data.frame"}
  are stripped, and the row names are changed if that argument is supplied.
  
  If \code{row.names = NULL}, row names are constructed from the names
  or dimnames of \code{x}, otherwise are the integer sequence
  starting at one.  Few of the methods check for duplicated row names.
}
\note{
  In versions of \R prior to 1.4.0 logical columns were converted to
  factors (as in S3 but not S4).
}
\references{
  Chambers, J. M. (1992)
  \emph{Data for models.}
  Chapter 3 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{data.frame}}
}
\keyword{classes}
\keyword{methods}
\eof
\name{as.environment}
\alias{as.environment}
\title{ Coerce to an Environment Object }
\description{
  Converts a number or a character string to the corresponding
  environment on the search path.
}
\usage{
as.environment(object)
}
\arguments{
  \item{object}{the object to convert.  If it is already an
    environment, just return it.  If it is a number, return the
    environment corresponding to that position on the search list.  If
    it is a character string, match the string to the names on the
    search list.}
}
\value{
  The corresponding environment object.
}
\author{ John Chambers }
\seealso{\code{\link{environment}} for creation and manipulation,
  \code{\link{search}}.}
\examples{
as.environment(1) ## the global environment
identical(globalenv(), as.environment(1)) ## is TRUE
try(as.environment("package:ctest"))      ## ctest need not be loaded
}
\keyword{data}
\keyword{environment}
\eof
\name{as.function}
\title{Convert Object to Function}
\usage{
as.function(x, \dots)

\method{as.function}{default}(x, envir = parent.frame(), \dots)
}
\alias{as.function}
\alias{as.function.default}
\arguments{
  \item{x}{object to convert, a list for the default method.}
  \item{\dots}{additional arguments, depending on object}

  \item{envir}{environment in which the function should be defined}
}
\description{
  \code{as.function} is a generic function which is used to convert
  objects to functions.

  \code{as.function.default} works on a list \code{x}, which should contain the
  concatenation of a formal argument list and an expression or an
  object of mode \code{"\link{call}"} which will become the function body.
  The function will be defined in a specified environment, by default
  that of the caller.
}
\value{
  The desired function.
}
\author{Peter Dalgaard}
\seealso{
  \code{\link{function}};
  \code{\link{alist}} which is handy for the construction of
  argument lists, etc.
}
\examples{
as.function(alist(a=,b=2,a+b))
as.function(alist(a=,b=2,a+b))(3)
}
\keyword{programming}
\eof
\name{assign}
\alias{assign}
\title{Assign a Value to a Name}
\description{
  Assign a value to a name in an environment.
}
\usage{
assign(x, value, pos = -1, envir = as.environment(pos),
       inherits = FALSE, immediate = TRUE)
}
\arguments{
  \item{x}{a variable name (given as a quoted string in the function call).}
  \item{value}{a value to be assigned to \code{x}.}
  \item{pos}{where to do the assignment.  By default, assigns into the
    current environment.  See the details for other possibilities.}
  \item{envir}{the \code{\link{environment}} to use. See the details section.}
  \item{inherits}{should the enclosing frames of the environment be
    inspected?}
  \item{immediate}{an ignored compatibility feature.}
}
\details{
  The \code{pos} argument can specify the  environment in which to assign
  the object in any of several ways:
  as an integer (the position in the \code{\link{search}} list); as
  the character string name of an element in the search list; or as an
  \code{\link{environment}} (including using \code{\link{sys.frame}} to
  access the currently active function calls).
  The \code{envir} argument is an alternative way to specify an
  environment, but is primarily there for back compatibility.

  \code{assign} does not dispatch assignment methods, so it cannot be
  used to set elements of vectors, names, attributes, etc.

  Note that assignment to an attached list or data frame changes the
  attached copy and not the orginal object: see \code{\link{attach}}.
}
\value{
  This function is invoked for its side effect, which is assigning
  \code{value} to the variable \code{x}.  If no \code{envir} is
  specified, then the assignment takes place in the currently active
  environment.

  If \code{inherits} is \code{TRUE}, enclosing environments of the supplied
  environment are searched until the variable \code{x} is encountered.
  The value is then assigned in the environment in which the variable is
  encountered.  If the symbol is not encountered then assignment takes
  place in the user's workspace (the global environment).

  If \code{inherits} is \code{FALSE}, assignment takes place in the
  initial frame of \code{envir}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}

\seealso{
  \code{\link{<-}},
  \code{\link{get}},
  \code{\link{exists}},
  \code{\link{environment}}.
}
\examples{
for(i in 1:6) { #-- Create objects  'r1', 'r2', ... 'r6' --
 nam <- paste("r",i, sep=".")
 assign(nam, 1:i)
}
ls(pat="^r..$")

##-- Global assignment within a function:
myf <- function(x) {
 innerf <- function(x) assign("Global.res", x^2, env = .GlobalEnv)
 innerf(x+1)
}
myf(3)
Global.res # 16

a <- 1:4
assign("a[1]", 2)
a[1] == 2          #FALSE
get("a[1]") == 2   #TRUE

}
\keyword{data}
\eof
\name{assignOps}
\alias{<-}
\alias{=}
\alias{<<-}
\alias{->}
\alias{->>}
\title{Assignment Operators}
\description{
  Assign a value to a name.
}
\usage{
x <- value
x <<- value
value -> x
value ->> x

x = value
}
\arguments{
  \item{x}{a variable name (possibly quoted).}
  \item{value}{a value to be assigned to \code{x}.}
}
\details{
  There are three different assignment operators: two of them
  have leftwards and rightwards forms.

  The operators \code{<-} and \code{=} assign into the
  environment in which they are evaluated.  The \code{<-} can be used
  anywhere, but the \code{=} is only allowed at the top level (that
  is, in the complete expression typed by the user) or as one of the
  subexpressions in a braced list of expressions.

  The operators \code{<<-} and \code{->>} cause a search to made through
  the environment for an existing definition of the variable being
  assigned.  If such a variable is found then its value is redefined,
  otherwise assignment takes place globally. Note that their semantics
  differ from that in the S language, but is useful in conjunction with
  the scoping rules of \R.

  In all the assignment operator expressions, \code{x} can be a name
  or an expression defining a part of an object to be replaced (e.g.,
  \code{z[[1]]}).  The name does not need to be quoted, though it can
  be.

  The leftwards forms of assignment \code{<- = <<-} group right to left,
  the other from left to right.
}
\value{
  \code{value}.  Thus one can use \code{a <- b <- c <- 6}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Chamber, J. M. (1998)
  \emph{Programming with Data. A Guide to the S Language}.
  Springer (for \code{=}).
}

\seealso{
  \code{\link{assign}},
  \code{\link{environment}}.
}
\keyword{data}
\eof
\name{assocplot}
\alias{assocplot}
\title{Association Plots}
\description{
  Produce a Cohen-Friendly association plot indicating deviations from
  independence of rows and columns in a 2-dimensional contingency
  table.
}
\usage{
assocplot(x, col = c("black", "red"), space = 0.3,
          main = NULL, xlab = NULL, ylab = NULL)
}
\arguments{
  \item{x}{a two-dimensional contingency table in matrix form.}
  \item{col}{a character vector of length two giving the colors used for
    drawing positive and negative Pearson residuals, respectively.}
  \item{space}{the amount of space (as a fraction of the average
    rectangle width and height) left between each rectange.}
  \item{main}{overall title for the plot.}
  \item{xlab}{a label for the x axis.  Defaults to the name of the row
    variable in \code{x} if non-\code{NULL}.}
  \item{ylab}{a label for the y axis.  Defaults to the column names of
    the column variable in \code{x} if non-\code{NULL}.}
}
\details{
  For a two-way contingency table, the signed contribution to Pearson's
  \eqn{\chi^2}{chi^2} for cell \eqn{i, j} is \eqn{d_{ij} = (f_{ij} -
    e_{ij}) / \sqrt{e_{ij}}}{d_{ij} = (f_{ij} - e_{ij}) / sqrt(e_{ij})},
  where \eqn{f_{ij}} and \eqn{e_{ij}} are the observed and expected
  counts corresponding to the cell.  In the Cohen-Friendly association
  plot, each cell is represented by a rectangle that has (signed) height
  proportional to \eqn{d_{ij}} and width proportional to
  \eqn{\sqrt{e_{ij}}}{sqrt(e_{ij})}, so that the area of the box is
  proportional to the difference in observed and expected frequencies.
  The rectangles in each row are positioned relative to a baseline
  indicating independence (\eqn{d_{ij} = 0}).  If the observed frequency
  of a cell is greater than the expected one, the box rises above the
  baseline and is shaded in the color specified by the first element of
  \code{col}, which defaults to black; otherwise, the box falls below
  the baseline and is shaded in the color specified by the second
  element of \code{col}, which defaults to red.
}
\seealso{
  \code{\link{mosaicplot}};
  \code{\link[ctest]{chisq.test}}.
}
\references{
  Cohen, A. (1980),
  On the graphical display of the significant components in a two-way
  contingency table.
  \emph{Communications in Statistics---Theory and Methods}, \bold{A9},
  1025--1041.

  Friendly, M. (1992),
  Graphical methods for categorical data.
  \emph{SAS User Group International Conference Proceedings}, \bold{17},
  190--200.
  \url{http://www.math.yorku.ca/SCS/sugi/sugi17-paper.html}
}
\examples{
data(HairEyeColor)
## Aggregate over sex:
x <- margin.table(HairEyeColor, c(1, 2))
x
assocplot(x, main = "Relation between hair and eye color")
}
\keyword{hplot}
\eof
\name{attach}
\title{Attach Set of R Objects to Search Path}
\usage{
attach(what, pos = 2, name = deparse(substitute(what)))
}
\alias{attach}
\arguments{
  \item{what}{\dQuote{database}.  This may currently be a
    \code{data.frame} or \code{list} or a \R data file created with
    \code{\link{save}}.}
  \item{pos}{integer specifying position in \code{\link{search}()} where
    to attach.}
  \item{name}{alternative way to specify the database to be attached.}
}
\description{
  The database is attached to the \R search path.  This means that the
  database is searched by \R when evaluating a variable, so objects in
  the database can be accessed by simply giving their names.}

\details{
  When evaluating a variable or function name \R searches for
  that name in the databases listed by \code{\link{search}}. The first
  name of the appropriate type is used.

  By attaching a data frame to the search path it is possible to refer
  to the variables in the data frame by their names alone, rather than
  as components of the data frame (eg in the example below,
  \code{height} rather than \code{women$height}).

  By default the database is attached in position 2 in the search path,
  immediately after the user's workspace and before all previously
  loaded packages and previously attached databases. This can be altered
  to attach later in the search path with the \code{pos} option, but you
  cannot attach at \code{pos=1}.

  Note that by default assignment is not performed in an attached
  database. Attempting to modify a variable or function in an attached
  database will actually create a modified version in the user's
  workspace (the \R global environment).  If you use
  \code{\link{assign}} to assign to an attached list or data frame, you
  only alter the attached copy, not the original object.
  For this reason \code{attach} can lead to confusion.
}
\value{
  The \code{\link{environment}} is returned invisibly with a
  \code{"name"} attribute.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{library}}, \code{\link{detach}}, \code{\link{search}},
  \code{\link{objects}}, \code{\link{environment}}, \code{\link{with}}.
}
\examples{
data(women)
summary(women$height) ## refers to variable 'height' in the data frame
attach(women)
summary(height)      ## The same variable now available by name
height <- height*2.54  ## Don't do this. It creates a new variable
detach("women")
summary(height)      ## The new variable created by modifying 'height'
rm(height)
}
\keyword{data}
\eof
\name{attenu}
\docType{data}
\alias{attenu}
\title{The Joyner--Boore Attenuation Data}
\description{
  This data gives peak accelerations measured at various observation
  stations for 23 earthquakes in California.  The data have been used
  by various workers to estimate the attenuating affect of distance
  on ground acceleration.
}
\usage{data(attenu)}
\format{
  A data frame with 182 observations on 5 variables.
  \tabular{rlll}{
    [,1] \tab event   \tab numeric \tab Event Number\cr
    [,2] \tab mag     \tab numeric \tab Moment Magnitude\cr
    [,3] \tab station \tab factor  \tab Station Number\cr
    [,4] \tab dist    \tab numeric \tab Station-hypocenter distance (km)\cr
    [,5] \tab accel   \tab numeric \tab Peak acceleration (g)}
}
\source{
  Joyner, W.B., D.M. Boore and R.D. Porcella (1981).  Peak horizontal
  acceleration and velocity from strong-motion records including
  records from the 1979 Imperial Valley, California earthquake.  USGS
  Open File report 81-365. Menlo Park, Ca.
}
\references{
  Boore, D. M. and Joyner, W.B.(1982)
  The empirical prediction of ground motion,
  \emph{Bull. Seism. Soc. Am.}, \bold{72}, S269--S268.

  Bolt, B. A. and Abrahamson, N. A. (1982)
  New attenuation relations for peak and expected accelerations of
  strong ground motion,
  \emph{Bull. Seism. Soc. Am.}, \bold{72}, 2307--2321.

  Bolt B. A. and Abrahamson, N. A. (1983)
  Reply to W. B. Joyner & D. M. Boore's \dQuote{Comments on: New
    attenuation relations for peak and expected accelerations for peak
    and expected accelerations of strong ground motion},
  \emph{Bull. Seism. Soc. Am.}, \bold{73}, 1481--1483. 

  Brillinger, D. R. and Preisler, H. K. (1984)
  An exploratory analysis of the Joyner-Boore attenuation data,
  \emph{Bull. Seism. Soc. Am.}, \bold{74}, 1441--1449.

  Brillinger, D. R. and Preisler, H. K. (1984)
  \emph{Further analysis of the Joyner-Boore attenuation data}.
  Manuscript.
}
\examples{
data(attenu)
## check the data class of the variables
sapply(attenu, data.class)
summary(attenu)
pairs(attenu, main = "attenu data")
coplot(accel ~ dist | as.factor(event), data = attenu, show = FALSE)
coplot(log(accel) ~ log(dist) | as.factor(event),
       data = attenu, panel = panel.smooth, show.given = FALSE)
}
\keyword{datasets}
\eof
\name{attitude}
\docType{data}
\alias{attitude}
\title{The Chatterjee--Price Attitude Data}
\description{
  From a survey of the clerical employees of a large financial
  organization, the data are aggregated from the questionnaires of the
  approximately 35 employees for each of 30 (randomly selected)
  departments.  The numbers give the percent proportion of favourable
  responses to seven questions in each department.}
\usage{data(attitude)}
\format{
  A dataframe with 30 observations on 7 variables. The first column are
  the short names from the reference, the second one the variable names
  in the data frame:
  \tabular{rlll}{
     Y   \tab rating    \tab numeric  \tab Overall rating \cr
    X[1] \tab complaints\tab numeric \tab Handling of employee complaints \cr
    X[2] \tab privileges\tab numeric \tab Does not allow special privileges \cr
    X[3] \tab learning \tab numeric  \tab Opportunity to learn \cr
    X[4] \tab raises   \tab numeric  \tab Raises based on performance \cr
    X[5] \tab critical \tab numeric  \tab Too critical \cr
    X[6] \tab advancel \tab numeric  \tab Advancement}
}
\source{
  Chatterjee, S. and Price, B. (1977)
  \emph{Regression Analysis by Example}.
  New York: Wiley.
  (Section 3.7, p.68ff of 2nd ed.(1991).)
}
\examples{
data(attitude)
pairs(attitude, main = "attitude data")
summary(attitude)
summary(fm1 <- lm(rating ~ ., data = attitude))
opar <- par(mfrow = c(2, 2), oma = c(0, 0, 1.1, 0),
            mar = c(4.1, 4.1, 2.1, 1.1))
plot(fm1)
summary(fm2 <- lm(rating ~ complaints, data = attitude))
plot(fm2)
par(opar)
}
\keyword{datasets}
\eof
\name{attr}
\alias{attr}
\alias{attr<-}
\title{Object Attributes}
\description{
  Get or set specific attributes of an object.
}
\usage{
attr(x, which)
attr(x, which) <- value
}
\arguments{
  \item{x}{an object whose attributes are to be accessed.}
  \item{which}{a character string specifying which attribute is to be
    accessed.}
  \item{value}{an object, the new value of the attribute.}
}
\value{
  This function provides access to a single object attribute.  The
  simple form above returns the value of the named attribute.  The
  assignment form causes the named attribute to take the value on the
  right of the assignment symbol.

  The first form first looks for an exact match to \code{code} amongst the
  attributed of \code{x}, then a partial match.  If no exact match is
  found and more than one partial match is found, the result is \code{NULL}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{attributes}}
}
\examples{
# create a 2 by 5 matrix
x <- 1:10
attr(x,"dim") <- c(2, 5)
}
\keyword{attribute}
\eof
\name{attributes}
\title{Object Attribute Lists}
\usage{
attributes(obj)
attributes(obj) <- value
mostattributes(obj) <- value
}
\alias{attributes}
\alias{attributes<-}
\alias{mostattributes<-}
\description{
  These functions access an object's attribute list.
  The first form above returns the an object's attribute list.
  The assignment forms make the list on the right-hand
  side of the assignment the object's attribute list (if appropriate).
}
\arguments{
  \item{obj}{an object}
  \item{value}{an appropriate attribute list, or \code{NULL}.}
}
\details{
  The \code{mostattributes} assignment takes special care for the
  \code{\link{dim}}, \code{\link{names}} and \code{\link{dimnames}}
  attributes, and assigns them only when that is valid whereas as
  \code{attributes} assignment would give an error in that case.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{\code{\link{attr}}.
}
\examples{
x <- cbind(a=1:3, pi=pi) # simple matrix w/ dimnames
str(attributes(x))

## strip an object's attributes:
attributes(x) <- NULL
x # now just a vector of length 6

mostattributes(x) <- list(mycomment = "really special", dim = 3:2,
   dimnames = list(LETTERS[1:3], letters[1:5]), names = paste(1:6))
x # dim(), but not {dim}names
}
\keyword{attribute}
\eof
\name{autoload}
\title{On-demand Loading of Packages}
\usage{
autoload(name, package, \dots)
autoloader(name, package, \dots)
.AutoloadEnv
}
\alias{autoload}
\alias{autoloader}
\alias{.AutoloadEnv}
\arguments{
\item{name}{string giving the name of an object.}
\item{package}{string giving the name of a package containing the object.}
\item{\dots}{other arguments to \code{\link{library}}.}
}
\description{
  \code{autoload} creates a promise-to-evaluate \code{autoloader} and stores it with name \code{name} in
  \code{.AutoloadEnv} environment.  When \R attempts to evaluate
\code{name}, \code{autoloader} is run,
  the package is loaded and \code{name} is re-evaluated in the
  new package's environment.  The result is that \R behaves as if
  \code{file} was loaded but it does not occupy memory.
}
\value{
This function is invoked for its side-effect. It has no return value as
of \R 1.7.0.
}
\seealso{
\code{\link{delay}}, \code{\link{library}}
}
\examples{
autoload("line","eda")
search()
ls("Autoloads")

data(cars)
plot(cars)
z<-line(cars)
abline(coef(z))
search()
detach("package:eda")
search()
z<-line(cars)
search()
}
\keyword{data}
\keyword{programming}

\eof
\name{ave}
\title{Group Averages Over Level Combinations of Factors}
\usage{
ave(x, \dots, FUN = mean)
}
\alias{ave}
\arguments{
  \item{x}{A numeric.}
  \item{\dots}{Grouping variables, typically factors, all of the same
    \code{length} as \code{x}.}
  \item{FUN}{Function to apply for each factor level combination.}
}
\description{
  Subsets of \code{x[]} are averaged, where each subset consist of those
  observations with the same factor levels.
}
\value{
  A numeric vector, say \code{y} of length \code{length(x)}.
  If \code{\dots} is \code{g1,g2}, e.g.,
  \code{y[i]} is equal to \code{FUN(x[j]}, for all \code{j} with
  \code{g1[j]==g1[i]} and \code{g2[j]==g2[i])}.
}
\seealso{\code{\link{mean}}, \code{\link{median}}.}
\examples{
ave(1:3)# no grouping -> grand mean

data(warpbreaks)
attach(warpbreaks)
ave(breaks, wool)
ave(breaks, tension)
ave(breaks, tension, FUN = function(x)mean(x, trim=.1))
plot(breaks, main =
     "ave( Warpbreaks )  for   wool  x  tension  combinations")
lines(ave(breaks, wool, tension            ), type='s', col = "blue")
lines(ave(breaks, wool, tension, FUN=median), type='s', col = "green")
legend(40,70, c("mean","median"), lty=1,col=c("blue","green"), bg="gray90")
detach()
}
\keyword{univar}

\eof
\name{axTicks}
\alias{axTicks}
\title{Compute Axis Tickmark Locations}
\description{
  Compute tickmark locations, the same way as \R does internally.
  This is only non-trivial when \bold{log} coordinates are active.
  By default, gives the \code{at} values which
  \code{\link{axis}(side)} would use.
}
\usage{
axTicks(side, axp = NULL, usr = NULL, log = NULL)
}
\arguments{
  \item{side}{integer in 1:4, as for \code{\link{axis}}.}
  \item{axp}{numeric vector of length three, defaulting to
    \code{\link{par}("Zaxp")} where \dQuote{Z} is \dQuote{x} or
    \dQuote{y} depending on the \code{side} argument.}
  \item{usr}{numeric vector of length four, defaulting to
    \code{\link{par}("usr")} giving horizontal (\sQuote{x}) and vertical
    (\sQuote{y}) user coordinate limits.}
  \item{log}{logical indicating if log coordinates are active; defaults
    to \code{\link{par}("Zlog")} where \sQuote{Z} is as for the
    \code{axp} argument above.}
}
\details{
  The \code{axp}, \code{usr}, and \code{log} arguments must be consistent
  as their default values (the \code{par(..)} results) are.
  Note that the meaning of \code{axp} alters very much when \code{log}
  is \code{TRUE}, see the documentation on \code{\link{par}(xaxp=.)}.

  \code{axTicks()} can be regarded as an \R implementation  of the
  C function \code{CreateAtVector()} in \file{..../src/main/graphics.c}
  which is called by \code{\link{axis}(side,*)} when no argument
  \code{at} is specified.
}
\value{
  numeric vector of coordinate values at which axis tickmarks can be
  drawn.  By default, when only the first argument is specified,
  these values should be identical to those that
  \code{\link{axis}(side)} would use or has used.
}
\seealso{\code{\link{axis}}, \code{\link{par}}.  \code{\link{pretty}}
  uses the same algorithm but is independent of the graphics
  environment and has more options.
}
\examples{
 plot(1:7, 10*21:27)
 axTicks(1)
 axTicks(2)
 stopifnot(identical(axTicks(1), axTicks(3)),
           identical(axTicks(2), axTicks(4)))

## Show how axTicks() and axis() correspond :
op <- par(mfrow = c(3,1))
for(x in 9999*c(1,2,8)) {
    plot(x,9, log = "x")
    cat(formatC(par("xaxp"),wid=5),";",T <- axTicks(1),"\n")
    rug(T, col="red")
}
par(op)
}
\keyword{dplot}

\eof
\name{axis.POSIXct}
\alias{axis.POSIXct}
\alias{plot.POSIXct}
\alias{plot.POSIXlt}
\title{Date-time Plotting Functions}
\description{
  Functions to plot objects of classes \code{"POSIXlt"} and
  \code{"POSIXct"} representing calendar dates and times. 
}
\usage{
axis.POSIXct(side, x, at, format, \dots)

\method{plot}{POSIXct}(x, y, xlab = "", \dots)

\method{plot}{POSIXlt}(x, y, xlab = "", \dots)
}
\synopsis{
plot.POSIXct(x, y, xlab = "", axes = TRUE, frame.plot = axes, xaxt = par("xaxt"), ...)
plot.POSIXlt(x, y, xlab = "", axes = TRUE, frame.plot = axes, xaxt = par("xaxt"), ...)
axis.POSIXct(side, x, at, format, ...)
}
\arguments{
  \item{x, at}{A date-time object.}
  \item{y}{numeric values to be plotted against \code{x}.}
  \item{xlab}{a character string giving the label for the x axis.}
  \item{side}{See \code{\link{axis}}.}
  \item{format}{See \code{\link{strptime}}.}
  \item{\dots}{Further arguments to be passed from or to other methods,
    typically graphical parameters or arguments of
    \code{\link{plot.default}}.}
}
\details{
  The functions plot against an x-axis of date-times.
  \code{axis.POSIXct} works quite hard to choose suitable time units
  (years, months, days, hours, minutes or seconds) and a sensible
  output format, but this can be overridden by supplying a \code{format}
  specification.

  If \code{at} is supplied for \code{axis.POSIXct} it specifies the
  locations of the ticks and labels: if \code{x} is specified a
  suitable grid of labels is chosen. 
}
\seealso{
  \link{DateTimeClasses} for details of the classes.
}
\examples{
res <- try(data(beav1, package = MASS))
if(!inherits(res, "try-error")) {
attach(beav1)
time <- strptime(paste(1990, day, time \%/\% 100, time \%\% 100),
                 "\%Y \%j \%H \%M")
plot(time, temp, type="l") # axis at 4-hour intervals.
# now label every hour on the time axis
plot(time, temp, type="l", xaxt="n")
r <- as.POSIXct(round(range(time), "hours"))
axis.POSIXct(1, at=seq(r[1], r[2], by="hour"), format="\%H")
rm(time)
detach(beav1)
}

plot(.leap.seconds, 1:22, type="n", yaxt="n",
     xlab="leap seconds", ylab="", bty="n")
rug(.leap.seconds)
}
\keyword{utilities}
\keyword{chron}
\eof
\name{axis}
\alias{axis}
\title{Add an Axis to a Plot}
\description{Adds an axis to the current plot, allowing the
  specification of the side, position, labels, and other options.
}
\usage{
axis(side, at = NULL, labels = TRUE, tick = TRUE, line = NA,
     pos = NA, outer = FALSE, font = NA, vfont = NULL,
     lty = "solid", lwd = 1, col = NULL, \dots)
}
\arguments{
  \item{side}{an integer specifying which side of the plot the axis is
    to be drawn on.  The axis is placed as follows: 1=below,
  2=left, 3=above and 4=right.}
  \item{at}{the points at which tick-marks are to be drawn.  Non-finite
    (infinite, \code{NaN} or \code{NA}) values are omitted.  By default,
  when \code{NULL}, tickmark locations are computed, see Details below.}
  \item{labels}{this can either be a logical value specifying whether
    (numerical) annotations are to be made at the tickmarks, or a vector
    of character strings to be placed at the tickpoints.}
  \item{tick}{a logical value specifying whether tickmarks should be
    drawn}.
  \item{line}{the number of lines into the margin which the axis will
    be drawn.  This overrides the value of the graphical parameter
    \code{mgp[3]}.  The relative placing of tickmarks and tick labels
    is unchanged.}
  \item{pos}{the coordinate at which the axis line is to be drawn.
    this overrides the value of both \code{line} and \code{mgp[3]}.}
  \item{outer}{a logical value indicating whether the axis should be
    drawn in the outer plot margin, rather than the standard plot
    margin.}
  \item{font}{font for text.}
  \item{vfont}{vector font for text.}
  \item{lty, lwd}{line type, width for the axis line and the tick marks.}
  \item{col}{color for the axis line and the tick marks.  The default
    \code{NULL} means to use \code{par("fg")}.}
  \item{\dots}{other graphical parameters may also be passed as arguments to
    this function, e.g., \code{las} for vertical/horizontal label
    orientation, or \code{fg} instead of \code{col}, see
    \code{\link{par}} on these.}%\code{las} and \code{fg}. 
}
\value{
  This function is invoked for its side effect, which is to add an axis
  to an already existing plot.
}
\details{
  The axis line is drawn from the lowest to the highest value of
  \code{at}, but will be clipped at the plot region. Only ticks which
  are drawn from points within the plot region (up to a tolerance for
  rounding error) are plotted, but the ticks and their labels may well
  extend outside the plot region.

  When \code{at = NULL}, pretty tick mark locations are computed internally,
  the same \code{\link{axTicks}(side)} would, from
  \code{\link{par}("usr","lab")}, and \code{\link{par}("xlog")} (or
  \code{ylog} respectively).
}
\seealso{\code{\link{axTicks}} returns the axis tick locations
  corresponding to \code{at=NULL}; \code{\link{pretty}} is more flexible
  for computing pretty tick coordinates and does \emph{not} depend on
  (nor adapt to) the coordinate system in use.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
plot(1:4, rnorm(4), axes=FALSE)
axis(1, 1:4, LETTERS[1:4])
axis(2)
box() #- to make it look "as usual"

plot(1:7, rnorm(7), main = "axis() examples",
     type = "s", xaxt="n", frame = FALSE, col = "red")
axis(1, 1:7, LETTERS[1:7], col.axis = "blue")
# unusual options:
axis(4, col = "violet", col.axis="dark violet",lwd = 2)
axis(3, col = "gold", lty = 2, lwd = 0.5)
}
\keyword{aplot}
\eof
\name{backsolve}
\alias{backsolve}
\alias{forwardsolve}
\title{Solve an Upper or Lower Triangular System}
\description{
  Solves a system of linear equations where the coefficient matrix is
  upper or lower triangular.
}
\usage{
   backsolve(r, x, k= ncol(r), upper.tri = TRUE, transpose = FALSE)
forwardsolve(l, x, k= ncol(l), upper.tri = FALSE, transpose = FALSE)
}
\arguments{
  % Name 'r' is not really making sense for upper.tri = FALSE
  % Name 'x' is also a  misnomer,  should rather be  'b'. -- is this S ??
  \item{r,l}{an upper (or lower) triangular matrix giving the
    coefficients for the system to be solved.  Values below (above)
    the diagonal are ignored.}
  \item{x}{a matrix whose columns give \dQuote{right-hand sides} for
    the equations.}
  \item{k}{The number of columns of \code{r} and rows of \code{x} to use.}
  \item{upper.tri}{logical; if \code{TRUE} (default), the \emph{upper}
    \emph{tri}angular part of \code{r} is used.  Otherwise, the lower one.}
  \item{transpose}{logical; if \code{TRUE}, solve \eqn{r' * y = x} for
    \eqn{y}, i.e., \code{t(r) \%*\% y == x}.}
}
\value{
  The solution of the triangular system.  The result will be a vector if
  \code{x} is a vector and a matrix if \code{x} is a matrix.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Dongarra, J. J., Bunch,J. R.,  Moler, C. B. and  Stewart, G. W. (1978)
  \emph{LINPACK Users Guide.}  Philadelphia: SIAM Publications.
}
\seealso{
  \code{\link{chol}},
  \code{\link{qr}},
  \code{\link{solve}}.
}
\examples{
## upper triangular matrix 'r':
r <- rbind(c(1,2,3),
           c(0,1,1),
           c(0,0,2))
( y <- backsolve(r, x <- c(8,4,2)) ) # -1 3 1
r \%*\% y # == x = (8,4,2)
backsolve(r, x, transpose = TRUE) # 8 -12 -5
}
\keyword{algebra}
\keyword{array}
\eof
\name{bandwidth}
\alias{bw.nrd0}
\alias{bw.nrd}
\alias{bw.ucv}
\alias{bw.bcv}
\alias{bw.SJ}
\title{Bandwidth Selectors for Kernel Density Estimation}
\synopsis{
bw.nrd0(x)
bw.nrd(x)
bw.ucv(x, nb = 1000, lower = 0.1 * hmax, upper = hmax)
bw.bcv(x, nb = 1000, lower = 0.1 * hmax, upper = hmax)
bw.SJ(x, nb = 1000, lower = 0.1 * hmax, upper = hmax, method=c("ste", "dpi"))
}
\usage{
bw.nrd0(x)
bw.nrd(x)
bw.ucv(x, nb = 1000, lower, upper)
bw.bcv(x, nb = 1000, lower, upper)
bw.SJ(x, nb = 1000, lower, upper, method = c("ste", "dpi"))
}
\arguments{
  \item{x}{A data vector.}
  \item{nb}{number of bins to use.}
  \item{lower, upper}{Range over which to minimize.  The default is
    almost always satisfactory.}
  \item{method}{Either \code{"ste"} ("solve-the-equation") or
    \code{"dpi"} ("direct plug-in").}
}
\description{
  Bandwidth selectors for gaussian windows in \code{\link{density}}.
}

\details{
  \code{bw.nrd0} implements a rule-of-thumb for
  choosing the bandwidth of a Gaussian kernel density estimator.
  It defaults to 0.9 times the
  minimum of the standard deviation and the interquartile range divided by
  1.34 times the sample size to the negative one-fifth power
  (= Silverman's \dQuote{rule of thumb}, Silverman (1986, page 48, eqn (3.31))
  \emph{unless} the quartiles coincide when a positive result
  will be guaranteed.

  \code{bw.nrd} is the more common variation given by Scott (1992),
  using factor 1.06.

  \code{bw.ucv} and \code{bw.bcv} implement unbiased and
  biased cross-validation respectively.

  \code{bw.SJ} implements the methods of Sheather & Jones (1991)
  to select the bandwidth using pilot estimation of derivatives.
}
\value{
  A bandwidth on a scale suitable for the \code{bw} argument
  of \code{density}.
}
\seealso{
  \code{\link{density}}.

  \code{\link[MASS]{bandwidth.nrd}}, \code{\link[MASS]{ucv}},
  \code{\link[MASS]{bcv}} and \code{\link[MASS]{width.SJ}} in
  package \pkg{MASS}, which are all scaled to the \code{width} argument
  of \code{density} and so give answers four times as large.
}
\references{
  Scott, D. W. (1992)
  \emph{Multivariate Density Estimation: Theory, Practice, and
    Visualization.}
  Wiley.

  Sheather, S. J. and Jones, M. C. (1991)
  A reliable data-based bandwidth selection method for kernel density
  estimation.
  \emph{Journal of the Royal Statistical Society series B},
  \bold{53}, 683--690.

  Silverman, B. W. (1986)
  \emph{Density Estimation}.
  London: Chapman and Hall.

  Venables, W. N. and Ripley, B. D. (2002)
  \emph{Modern Applied Statistics with S}.
  Springer.
}
\examples{
data(precip)
plot(density(precip, n = 1000))
rug(precip)
lines(density(precip, bw="nrd"), col = 2)
lines(density(precip, bw="ucv"), col = 3)
lines(density(precip, bw="bcv"), col = 4)
lines(density(precip, bw="SJ-ste"), col = 5)
lines(density(precip, bw="SJ-dpi"), col = 6)
legend(55, 0.035,
       legend = c("nrd0", "nrd", "ucv", "bcv", "SJ-ste", "SJ-dpi"),
       col = 1:6, lty = 1)
}
\keyword{distribution}
\keyword{smooth}
\eof
\name{barplot}
\alias{barplot}
\alias{barplot.default}
\title{Bar Plots}
\usage{
\method{barplot}{default}(height, width = 1, space = NULL,
        names.arg = NULL, legend.text = NULL, beside = FALSE,
        horiz = FALSE, density = NULL, angle = 45,
        col = heat.colors(NR), border = par("fg"),
        main = NULL, sub = NULL, xlab = NULL, ylab = NULL,
        xlim = NULL, ylim = NULL, xpd = TRUE,
        axes = TRUE, axisnames = TRUE,
        cex.axis = par("cex.axis"), cex.names = par("cex.axis"),
        inside = TRUE, plot = TRUE, axis.lty = 0, \dots)
}
\arguments{
  \item{height}{either a vector or matrix of values describing the
    bars which make up the plot.  If \code{height} is a vector, the
    plot consists of a sequence of rectangular bars with heights
    given by the values in the vector.  If \code{height} is a matrix
    and \code{beside} is \code{FALSE} then each bar of the plot
    corresponds to a column of \code{height}, with the values in the
    column giving the heights of stacked \dQuote{sub-bars} making up the
    bar.  If \code{height} is a matrix and \code{beside} is
    \code{TRUE}, then the values in each column are juxtaposed
    rather than stacked.}
  \item{width}{optional vector of bar widths. Re-cycled to length the
    number of bars drawn.  Specifying a single value will no visible
    effect unless \code{xlim} is specified.}
  \item{space}{the amount of space (as a fraction of the average bar
    width) left before each bar.  May be given as a single number or
    one number per bar.  If \code{height} is a matrix and
    \code{beside} is \code{TRUE}, \code{space} may be specified by
    two numbers, where the first is the space between bars in the
    same group, and the second the space between the groups.  If not
    given explicitly, it defaults to \code{c(0,1)} if \code{height}
    is a matrix and \code{beside} is \code{TRUE}, and to 0.2
    otherwise.}
  \item{names.arg}{a vector of names to be plotted below each bar or
    group of bars.  If this argument is omitted, then the names are
    taken from the \code{names} attribute of \code{height} if this
    is a vector, or the column names if it is a matrix.}
  \item{legend.text}{a vector of text used to construct a legend for
    the plot, or a logical indicating whether a legend should be
    included.  This is only useful when \code{height} is a matrix.
    In that case given legend labels should correspond to the rows of
    \code{height}; if \code{legend.text} is true, the row names of
    \code{height} will be used as labels if they are non-null.}
  \item{beside}{a logical value.  If \code{FALSE}, the columns of
    \code{height} are portrayed as stacked bars, and if \code{TRUE}
    the columns are portrayed as juxtaposed bars.}
  \item{horiz}{a logical value.  If \code{FALSE}, the bars are drawn
    vertically with the first bar to the left.  If \code{TRUE}, the
    bars are drawn horizontally with the first at the bottom.}
  \item{density}{a vector giving the the density of shading lines, in
    lines per inch, for the bars or bar components.
    The default value of \code{NULL} means that no shading lines
    are drawn. Non-positive values of \code{density} also inhibit the
    drawing of shading lines.}
  \item{angle}{the slope of shading lines, given as an angle in
    degrees (counter-clockwise), for the bars or bar components.}
  \item{col}{a vector of colors for the bars or bar components.}
  \item{border}{the color to be used for the border of the bars.}
  \item{main,sub}{overall and sub title for the plot.}
  \item{xlab}{a label for the x axis.}
  \item{ylab}{a label for the y axis.}
  \item{xlim}{limits for the x axis.}
  \item{ylim}{limits for the y axis.}
  \item{xpd}{logical. Should bars be allowed to go outside region?}
  \item{axes}{logical.  If \code{TRUE}, a vertical (or horizontal, if
    \code{horiz} is true) axis is drawn.}
  \item{axisnames}{logical.  If \code{TRUE}, and if there are
    \code{names.arg} (see above), the
    other axis is drawn (with \code{lty=0}) and labeled.}
  \item{cex.axis}{expansion factor for numeric axis labels.}
  \item{cex.names}{expansion factor for axis names (bar labels).}
  \item{inside}{logical.  If \code{TRUE}, the lines which divide
    adjacent (non-stacked!) bars will be drawn.  Only applies when
    \code{space = 0} (which it partly is when \code{beside = TRUE}).}
%MM: we still have "NotYetUsed" -- the above describe's S-plus 6.1 (not
% precisely documented!) behavior!
  \item{plot}{logical.  If \code{FALSE}, nothing is plotted.}
  \item{axis.lty}{the graphics parameter \code{lty} applied to the axis
    and tick marks of the categorical (default horzontal) axis.  Note
    that by default the axis is suppressed.}
  \item{\dots}{further graphical parameters (\code{\link{par}}) are
    passed to \code{\link{plot.window}()}, \code{\link{title}()} and
    \code{\link{axis}}.}
}
\description{
  Creates a bar plot with vertical or horizontal bars.
}
\details{
  This is a generic function, it currently only has a default method.
  A formula interface may be added eventually.
}
\value{
  A numeric vector (or matrix, when \code{beside = TRUE}), say
  \code{mp}, giving the coordinates of \emph{all} the bar midpoints
  drawn, useful for adding to the graph.

  If \code{beside} is true, use \code{colMeans(mp)} for the
  midpoints of each \emph{group} of bars, see example.
}
\note{
  Prior to \R 1.6.0, \code{barplot} behaved as if \code{axis.lty = 1},
  unintentionally.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{plot}(\dots, type="h")}, \code{\link{dotchart}},
  \code{\link{hist}}.
}
\examples{
tN <- table(Ni <- rpois(100, lambda=5))
r <- barplot(tN, col='gray')
#- type = "h" plotting *is* 'bar'plot
lines(r, tN, type='h', col='red', lwd=2)

barplot(tN, space = 1.5, axisnames=FALSE,
        sub = "barplot(..., space= 1.5, axisnames = FALSE)")

data(VADeaths, package = "base")
barplot(VADeaths, plot = FALSE)
barplot(VADeaths, plot = FALSE, beside = TRUE)

mp <- barplot(VADeaths) # default
tot <- colMeans(VADeaths)
text(mp, tot + 3, format(tot), xpd = TRUE, col = "blue")
barplot(VADeaths, beside = TRUE,
        col = c("lightblue", "mistyrose", "lightcyan",
                "lavender", "cornsilk"),
        legend = rownames(VADeaths), ylim = c(0, 100))
title(main = "Death Rates in Virginia", font.main = 4)

hh <- t(VADeaths)[, 5:1]
mybarcol <- "gray20"
mp <- barplot(hh, beside = TRUE,
        col = c("lightblue", "mistyrose",
                "lightcyan", "lavender"),
        legend = colnames(VADeaths), ylim= c(0,100),
        main = "Death Rates in Virginia", font.main = 4,
        sub = "Faked upper 2*sigma error bars", col.sub = mybarcol,
        cex.names = 1.5)
segments(mp, hh, mp, hh + 2*sqrt(1000*hh/100), col = mybarcol, lwd = 1.5)
stopifnot(dim(mp) == dim(hh))# corresponding matrices
mtext(side = 1, at = colMeans(mp), line = -2,
      text = paste("Mean", formatC(colMeans(hh))), col = "red")

# Bar shading example
barplot(VADeaths, angle = 15+10*1:5, density = 20, col = "black",
        legend = rownames(VADeaths))
title(main = list("Death Rates in Virginia", font = 4))

# border :
barplot(VADeaths, border = "dark blue") % lwd = 2 << not passed
%notyet barplot(VADeaths, inside = FALSE, main = "barplot(*, inside=FALSE)")
}
\keyword{hplot}
\eof
\name{basename}
\alias{basename}
\alias{dirname}
\title{Manipulate File Paths}
\description{
  \code{basename} removes all of the path up to the last path separator
  (if any).

  \code{dirname} returns the part of the \code{path} up to (but
  excluding) the last path separator, or \code{"."} if there is no path
  separator. 
}
\usage{
basename(path)
dirname(path)
}
\arguments{
  \item{path}{character vector, containing path names.}
}
\details{
  For \code{dirname} tilde expansion is done: see the description of
  \code{\link{path.expand}}.
  
  Trailing file separators are removed before dissecting the path,
  and for \code{dirname} any trailing file separators are removed
  from the result.
}
\value{
  A character vector of the same length as \code{path}.  A zero-length
  input will give a zero-length output with no error (unlike \R < 1.7.0). 
}
\seealso{
  \code{\link{file.path}}, \code{\link{path.expand}}.
}
\examples{
basename(file.path("","p1","p2","p3", c("file1", "file2")))
dirname(file.path("","p1","p2","p3","filename"))
}
\keyword{file}
\eof
\name{bindenv}
\title{Binding and Environment Adjustments}
\usage{
lockEnvironment(env, bindings = FALSE)
environmentIsLocked(env)
lockBinding(sym, env)
unlockBinding(sym, env)
bindingIsLocked(sym, env)
makeActiveBinding(sym, fun, env)
bindingIsActive(sym, env)
}
\alias{bindenv}
\alias{lockEnvironment}
\alias{environmentIsLocked}
\alias{lockBinding}
\alias{unlockBinding}
\alias{makeActiveBinding}
\alias{bindingIsLocked}
\alias{bindingIsActive}
\arguments{
  \item{env}{an environment.}
  \item{bindings}{logical specifying whether bindings should be locked.}
  \item{sym}{a name object or character string}
  \item{fun}{a function taking zero or one arguments}
}
\description{
  These functions represent an experimental interface for adjustments
  to environments and bindings within environments.  They allow for
  locking environments as well as individual bindings, and for linking
  a variable to a function.
}
\details{
  The function \code{lockEnvironment} locks its environment argument,
  which must be a proper environment, not NULL.  Locking the NULL
  (base) environment may be supported later.  Locking the environment
  prevents adding or removing variable bindings from the environment.
  Changing the value of a variable is still possible unless the binding
  has been locked.

  \code{lockBinding} locks individual bindings in the specified
  environment.  The value of a locked binding cannot be changed.
  Locked bindings may be removed from an environment unless the
  environment is locked.

  \code{makeActiveBinding} installs \code{fun} so that getting the
  value of \code{sym} calls \code{fun} with no arguments, and assigning
  to \code{sym} calls \code{fun} with one argument, the value to be
  assigned.  This allows things like C variables linked to R variables
  and variables linked to data bases to be implemented.  It may also
  be useful for making thread-safe versions of some system globals.
}
\examples{
# locking environments
e<-new.env()
assign("x",1, env=e)
get("x",env=e)
lockEnvironment(e)
get("x",env=e)
assign("x",2, env=e)
try(assign("y",2, env=e)) # error

# locking bindings
e<-new.env()
assign("x",1, env=e)
get("x",env=e)
lockBinding("x", e)
try(assign("x",2, env=e)) # error
unlockBinding("x", e)
assign("x",2, env=e)
get("x",env=e)

# active bindings
f<-local({
    x <- 1
    function(v) {
       if (missing(v))
           cat("get\n")
       else {
           cat("set\n")
           x <<- v
       }
       x
    }
})
makeActiveBinding("fred", f, .GlobalEnv)
bindingIsActive("fred", .GlobalEnv)
fred
fred<-2
fred
}
\keyword{internal}
\author{Luke Tierney}
\eof
\name{birthday}
\alias{qbirthday}
\alias{pbirthday}
\title{Probability of coincidences}
\description{
  Computes approximate answers to a generalised \dQuote{birthday paradox}
  problem. \code{pbirthday} computes the probability of a coincidence
  and \code{qbirthday} computes the number of observations needed to
  have a specified probability of coincidence.
}
\usage{
qbirthday(prob = 0.5, classes = 365, coincident = 2)
pbirthday(n, classes = 365, coincident = 2)
}
\arguments{
  \item{classes}{How many distinct categories the people could fall into}
  \item{prob}{The desired probability of coincidence}
  \item{n}{The number of people}
  \item{coincident}{The number of people to fall in the same category}
}
\value{
  \item{qbirthday}{
    Number of people needed for a probability \code{prob} that \code{k} of 
    them have the same one out of \code{classes} equiprobable labels.
  }

  \item{pbirthday}{Probability of the specified coincidence}  
}
\details{
 The birthday paradox is that a very small number of people, 23,
 suffices to have  a 50-50 chance that two of them have the same
 birthday.  This function generalises the calculation to probabilities
 other than 0.5, numbers of coincident events other than 2, and numbers
 of classes other than 365.

 This formula is approximate, as the example below shows.  For
 \code{coincident=2} the exact computation is straightforward and may be
 preferable. 
}
\references{
  Diaconis P, Mosteller F., \dQuote{Methods for studying coincidences}.
  JASA 84:853-861}
\examples{
 ## the standard version
qbirthday() 
 ## same 4-digit PIN number 
qbirthday(classes=10^4)
 ## 0.9 probability of three coincident birthdays
qbirthday(coincident=3,prob=0.9)
## Chance of 4 coincident birthdays in 150 people
pbirthday(150,coincident=4)
## Accuracy compared to exact calculation 
x1<- sapply(10:100, pbirthday)
x2<-1-sapply(10:100, function(n)prod((365:(365-n+1))/rep(365,n)))
par(mfrow=c(2,2))
plot(x1,x2,xlab="approximate",ylab="exact")
abline(0,1)
plot(x1,x1-x2,xlab="approximate",ylab="error")
abline(h=0)
plot(x1,x2,log="xy",xlab="approximate",ylab="exact")
abline(0,1)
plot(1-x1,1-x2,log="xy",xlab="approximate",ylab="exact")
abline(0,1)
}
\keyword{distribution}
\eof
\name{body}
\alias{body}
\alias{body<-}
\title{Access to and Manipulation of the Body of a Function}
\description{
  Get or set the body of a function.
}
\usage{
body(fun = sys.function(sys.parent()))
body(fun, envir = parent.frame()) <- value
}
\arguments{
  \item{fun}{a function object, or see Details.}
  \item{envir}{environment in which the function should be defined.}
  \item{value}{an expression or a list of \R expressions.}
}
\value{
  \code{body} returns the body of the function specified.

  The assignment form sets the body of a function to the list on the
  right hand side.
}
\details{
  For the first form, \code{fun} can be a character string
  naming the function to be manipulated, which is searched for from the
  parent environment.
  If it is not specified, the function calling \code{body} is used.
}
\seealso{
  \code{\link{alist}},
  \code{\link{args}},
  \code{\link{function}}.
}
\examples{
body(body)
f <- function(x) x^5
body(f) <- expression(5^x)
## or equivalently  body(f) <- list(quote(5^x))
f(3) # = 125
str(body(f))
}
\keyword{programming}
\eof
\name{box}
\title{Draw a Box around a Plot}
\usage{
box(which="plot", lty="solid", \dots)
}
\alias{box}
\arguments{
\item{which}{character, one of \code{"plot"}, \code{"figure"},
  \code{"inner"} and \code{"outer"}.}
\item{lty}{line type of the box.}
\item{\dots}{further graphical parameters, such as
  \code{bty}, \code{col}, or \code{lwd}, see \code{\link{par}}.}
}
\description{
This function draws a box around the current plot in the given color
and linetype.  The \code{bty} parameter determines
the type of box drawn.  See \code{\link{par}} for details.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
\code{\link{rect}} for drawing of arbitrary rectangles.
}
\examples{
plot(1:7,abs(rnorm(7)), type='h', axes = FALSE)
axis(1, labels = letters[1:7])
box(lty='1373', col = 'red')
}
\keyword{aplot}
\eof
\name{boxplot}
\alias{boxplot}
\alias{boxplot.default}
\alias{boxplot.formula}
\title{Box Plots}
\description{
  Produce box-and-whisker plot(s) of the given (grouped) values.
}
\usage{
boxplot(x, \dots)

\method{boxplot}{formula}(formula, data = NULL, \dots, subset)

\method{boxplot}{default}(x, \dots, range = 1.5, width = NULL, varwidth = FALSE,
        notch = FALSE, outline = TRUE, names, boxwex = 0.8, plot = TRUE,
        border = par("fg"), col = NULL, log = "", pars = NULL,
        horizontal = FALSE, add = FALSE, at = NULL)
}
\arguments{
  \item{formula}{a formula, such as \code{y ~ x}.}
  \item{data}{a data.frame (or list) from which the variables in
    \code{formula} should be taken.}
  \item{subset}{an optional vector specifying a subset of observations
    to be used for plotting.}
  \item{x}{for specifying data from which the boxplots are to be
    produced as well as for giving graphical parameters.  Additional
    unnamed  arguments specify further data, either
    as separate vectors (each corresponding to a component boxplot) or
    as a single list containing such vectors.  \code{\link{NA}}s are
    allowed in the data.}
  \item{\dots}{For the \code{formula} method, arguments to the
    default method and graphical parameters.

    For the default method, unnamed arguments are additional data
    vectors, and named arguments are graphical parameters in addition
    to the ones given by argument \code{pars}.
  }
  \item{range}{this determines how far the plot whiskers extend out
    from the box.  If \code{range} is positive, the whiskers extend
    to the most extreme data point which is no more than
    \code{range} times the interquartile range from the box. A value
    of zero causes the whiskers to extend to the data extremes.}
  \item{width}{a vector giving the relative widths of the boxes making
    up the plot.}
  \item{varwidth}{if \code{varwidth} is \code{TRUE}, the boxes are
    drawn with widths proportional to the square-roots of the number
    of observations in the groups.}
  \item{notch}{if \code{notch} is \code{TRUE}, a notch is drawn in
    each side of the boxes.  If the notches of two plots do not
    overlap then the medians are significantly different at the 5
    percent level.}
  \item{outline}{if \code{outline} is not true, the boxplot lines are
    not drawn.}% the argument name is most ugly but S+ compatible
  \item{names}{group labels which will be printed under each boxplot.}
  \item{boxwex}{a scale factor to be applied to all boxes.  When there
    are only a few groups, the appearance of the plot can be improved
    by making the boxes narrower.}
  \item{plot}{if \code{TRUE} (the default) then a boxplot is
    produced.  If not, the summaries which the boxplots are based on
    are returned.}
  \item{border}{an optional vector of colors for the outlines of the
    boxplots.  The values in \code{border} are recycled if the
    length of \code{border} is less than the number of plots.}
  \item{col}{if \code{col} is non-null it is assumed to contain colors
    to be used to col the bodies of the box plots.}
  \item{log}{character indicating if x or y or both coordinates should
    be plotted in log scale.}
  \item{pars}{a list of graphical parameters; these are passed to
    \code{\link{bxp}} (if \code{plot} is true).}
  \item{horizontal}{logical indicating if the boxplots should be
    horizontal; default \code{FALSE} means vertical boxes.}
  \item{add}{logical, if true \emph{add} boxplot to current plot.}
  \item{at}{numeric vector giving the locations where the boxplots should
    be drawn, particularly when \code{add = TRUE};
    defaults to \code{1:n} where \code{n} is the number of boxes.}
}
\details{
  The generic function \code{boxplot} currently has a default method
  (\code{boxplot.default}) and a formula interface
  (\code{\link{boxplot.formula}}).
}
\value{
  List with the following components:
  \item{stats}{a matrix, each column contains the extreme of the lower
    whisker, the lower hinge, the median, the upper hinge and the
    extreme of the upper whisker for one group/plot.}
  \item{n}{a vector with the number of observations in each group.}
  \item{conf}{a matrix where each column contains the lower and upper
    extremes of the notch.}
  \item{out}{the values of any data points which lie beyond the
    extremes of the whiskers.}
  \item{group}{a vector of the same length as \code{out} whose elements
    indicate which group the outlier belongs to}
  \item{names}{a vector of names for the groups}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  See also \code{\link{boxplot.stats}}.
}
\seealso{
  \code{\link{boxplot.stats}} which does the computation,
  \code{\link{bxp}} for the plotting;
  and \code{\link{stripchart}} for an alternative (with small data
  sets).
}
\examples{
## boxplot on a formula:
data(InsectSprays)
boxplot(count ~ spray, data = InsectSprays, col = "lightgray")
# *add* notches (somewhat funny here):
boxplot(count ~ spray, data = InsectSprays,
        notch = TRUE, add = TRUE, col = "blue")

data(OrchardSprays)
boxplot(decrease ~ treatment, data = OrchardSprays,
        log = "y", col="bisque")

rb <- boxplot(decrease ~ treatment, data = OrchardSprays, col="bisque")
title("Comparing boxplot()s and non-robust mean +/- SD")

mn.t <- tapply(OrchardSprays$decrease, OrchardSprays$treatment, mean)
sd.t <- tapply(OrchardSprays$decrease, OrchardSprays$treatment, sd)
xi <- 0.3 + seq(rb$n)
points(xi, mn.t, col = "orange", pch = 18)
arrows(xi, mn.t - sd.t, xi, mn.t + sd.t,
       code = 3, col = "pink", angle = 75, length = .1)

## boxplot on a matrix:
mat <- cbind(Uni05 = (1:100)/21, Norm = rnorm(100),
             T5 = rt(100, df = 5), Gam2 = rgamma(100, shape = 2))
boxplot(data.frame(mat), main = "boxplot(data.frame(mat), main = ...)")
par(las=1)# all axis labels horizontal
boxplot(data.frame(mat), main = "boxplot(*, horizontal = TRUE)",
        horizontal = TRUE)

## Using 'at = ' and adding boxplots -- example idea by Roger Bivand :

data(ToothGrowth)
boxplot(len ~ dose, data = ToothGrowth,
        boxwex = 0.25, at = 1:3 - 0.2,
        subset= supp == "VC", col="yellow",
        main="Guinea Pigs' Tooth Growth",
        xlab="Vitamin C dose mg",
        ylab="tooth length", ylim=c(0,35))
boxplot(len ~ dose, data = ToothGrowth, add = TRUE,
        boxwex = 0.25, at = 1:3 + 0.2,
        subset= supp == "OJ", col="orange")
legend(2, 9, c("Ascorbic acid", "Orange juice"),
       fill = c("yellow", "orange"))
}
\keyword{hplot}
\eof
\name{boxplot.stats}
\title{Box Plot Statistics}
\usage{
boxplot.stats(x, coef = 1.5, do.conf=TRUE, do.out=TRUE)
}
\alias{boxplot.stats}
\arguments{
  \item{x}{a numeric vector for which the boxplot will
    be constructed (\code{\link{NA}}s and \code{\link{NaN}}s are allowed
    and omitted).}
  \item{coef}{this determines how far the plot \dQuote{whiskers} extend out
    from the box.  If \code{coef} is positive, the whiskers extend to the
    most extreme data point which is no more than \code{coef} times
    the length of the box away from the box. A value of zero causes
    the whiskers
    to extend to the data extremes (and no outliers be returned).}
  \item{do.conf,do.out}{logicals; if \code{FALSE}, the \code{conf} or
    \code{out} component respectively will be empty in the result.}
}
\description{
  This function is typically called by \code{\link{boxplot}} to
  gather the statistics necessary for producing box plots,
  but may be invoked separately.
}
\value{
  List with named components as follows:
  \item{stats}{a vector of length 5, containing the extreme of the
    lower whisker, the lower \dQuote{hinge}, the median, the upper \dQuote{hinge}
    and the extreme of the upper whisker.}
  \item{n}{the number of of non-\code{NA} observations in the sample.}
  \item{conf}{the lower and upper extremes of the \dQuote{notch} (\code{if(do.conf)}).}
  \item{out}{the values of any data points which lie beyond the
    extremes of the whiskers (\code{if(do.out)}).}

  Note that \code{$stats} and \code{$conf} are sorted in \emph{in}creasing
  order, unlike S, and that \code{$n} and \code{$out} include any
  \code{+- Inf} values.
}
\details{
  The two \dQuote{hinges} are versions of the first and third quartile,
  i.e., close to \code{\link{quantile}(x, c(1,3)/4)}.  The hinges equal
  the quartiles for odd \eqn{n} (where \code{n <- length(x)}) and
  differ for even \eqn{n}. Where the quartiles only equal observations
  for \code{n \%\% 4 == 1} (\eqn{n\equiv 1 \bmod 4}{n = 1 mod 4}),
  the hinges do so \emph{additionally} for \code{n \%\% 4 == 2}
  (\eqn{n\equiv 2 \bmod 4}{n = 2 mod 4}), and are in the middle of
  two observations otherwise.
}
\references{
  Tukey, J. W. (1977) \emph{Exploratory Data Analysis.} Section 2C.

  McGill, R., Tukey, J. W. and Larsen, W. A. (1978) Variations of box
  plots. \emph{The American Statistician} \bold{32}, 12--16.
  
  Velleman, P. F. and Hoaglin, D. C. (1981) \emph{Applications, Basics
    and Computing of Exploratory Data Analysis.}  Duxbury Press.
  
  Emerson, J. D and Strenio, J. (1983). Boxplots and batch comparison.
  Chapter 3 of \emph{Understanding Robust and Exploratory Data
    Analysis}, eds. D. C. Hoaglin, F. Mosteller and J. W. Tukey.  Wiley.

}
\seealso{
  \code{\link{fivenum}}, \code{\link{boxplot}}, \code{\link{bxp}}.
}
\examples{
x <- c(1:100, 1000)
str(b1 <- boxplot.stats(x))
str(b2 <- boxplot.stats(x, do.conf=FALSE, do.out=FALSE))
stopifnot(b1 $ stats == b2 $ stats) # do.out=F is still robust
str(boxplot.stats(x, coef = 3, do.conf=FALSE))
## no outlier treatment:
str(boxplot.stats(x, coef = 0))

str(boxplot.stats(c(x, NA))) # slight change : n + 1
str(r <- boxplot.stats(c(x, -1:1/0)))
stopifnot(r$out == c(1000, -Inf, Inf))

%% extended example (for the NG of Rdoc):
\dontshow{
 ## Difference between quartiles and hinges :
 nn <- 1:17 ;  n4 <- nn \%\% 4
 hin <- sapply(sapply(nn, seq), function(x) boxplot.stats(x)$stats[c(2,4)])
 q13 <- sapply(sapply(nn, seq), quantile, probs = c(1,3)/4, names = FALSE)
 m <- t(rbind(q13,hin))[, c(1,3,2,4)]
 dimnames(m) <- list(paste(nn), c("q1","lH", "q3","uH"))
 stopifnot(m[n4==1, 1:2] == (nn[n4==1] + 3)/4,# quart. = hinge
           m[n4==1, 3:4] == (3*nn[n4==1]+1)/4,
           m[,"lH"] == ( (nn+3) \%/\% 2) / 2,
           m[,"uH"] == ((3*nn+2)\%/\% 2) / 2)
 cm <- noquote(format(m))
 cm[m[,2] == m[,1], 2] <- " = "
 cm[m[,4] == m[,3], 4] <- " = "
 cm
}

}
\keyword{dplot}
\eof
\name{bquote}
\alias{bquote}
%- Also NEED an '\alias' for EACH other topic documented here.
\title{Partial substitution in expressions}
\description{
  An analogue of the LISP backquote macro.  \code{bquote} quotes its
  argument except that terms wrapped in \code{.()} are evaluated in the
  specified \code{where} environment.
}
\usage{
bquote(expr, where = parent.frame())
}
%- maybe also 'usage' for other objects documented here.
\arguments{
  \item{expr}{An expression }
  \item{where}{ An environment }
}

\value{
 An expression
}
\seealso{\code{\link{quote}}, \code{\link{substitute}} }
\examples{
a<-2

bquote(a==a)
quote(a==a)

bquote(a==.(a))
substitute(a==A, list(A=a))

plot(1:10,a*(1:10), main=bquote(a==.(a)))
}
\keyword{programming}
\keyword{data}
\eof
\name{browseEnv}
\alias{browseEnv}
\alias{wsbrowser}
\title{Browse Objects in Environment}
\description{
  The \code{browseEnv} function opens a browser with list of objects
  currently in \code{sys.frame()} environment.
}
\usage{
browseEnv(envir = .GlobalEnv, pattern, excludepatt = "^last\\.warning",
          html = .Platform$OS.type != "mac",
          expanded = TRUE, properties = NULL,
          main = NULL, debugMe = FALSE)
}
\arguments{
  \item{envir}{an \code{\link{environment}} the objects of which are to
    be browsed.}
  \item{pattern}{a regular expression for object subselection is passed
    to the internal \code{\link{ls}()} call.}
  \item{excludepatt}{a regular expression for \emph{dropping} objects
    with matching names.}
  \item{html}{is used on non Macintosh machines to display the workspace
    on a HTML page in your favorite browser.}
  \item{expanded}{whether to show one level of recursion.  It can be useful
    to switch it to \code{FALSE} if your workspace is large.  This
    option is ignored if \code{html} is set to \code{FALSE}.}
  \item{properties}{a named list of global properties (of the objects chosen)
    to be showed in the browser;  when \code{NULL} (as per default),
    user, date, and machine information is used.}
  \item{main}{a title string to be used in the browser; when \code{NULL}
    (as per default) a title is constructed.}
  \item{debugMe}{logical switch; if true, some diagnostic output is produced.}
}

\details{
  Very experimental code.  Only allows one level of recursion into
  object structures. The HTML version is not dynamic.

  It can be generalized.  See sources
  (\file{..../library/base/R/databrowser.R}) for details.

  \code{wsbrowser()} is currently just an internally used function;
  its argument list will certainly change.

  Most probably, this should rather work through using the \file{tkWidget}
  package (from \url{www.Bioconductor.org}).
}
\seealso{
  \code{\link{str}}, \code{\link{ls}}.
}
\examples{
if(interactive()) {
   ## create some interesting objects :
   ofa <- ordered(4:1)
   ex1 <- expression(1+ 0:9)
   ex3 <- expression(u,v, 1+ 0:9)
   example(factor, echo = FALSE)
   example(table, echo = FALSE)
   example(ftable, echo = FALSE)
   example(lm, echo = FALSE)
   example(str, echo = FALSE)

   ## and browse them:
   browseEnv()

   ## a (simple) function's environment:
   af12 <- approxfun(1:2, 1:2, method = "const")
   browseEnv(envir = environment(af12))
 }
}
\keyword{interface}
\eof
\name{browseURL}
\alias{browseURL}
\title{Load URL into a WWW Browser}
\description{
  Load a given URL into a WWW browser.
}
\usage{
browseURL(url, browser = getOption("browser"))
}
\arguments{
  \item{url}{a non-empty character string giving the URL to be loaded.}
  \item{browser}{a non-empty character string giving the name of the
    program to be used as hypertext browser.  It should be in the PATH,
    or a full path specified.
#ifdef windows
    
    Under Windows \code{NULL} is also allowed (and is the default), and
    implies that the file association mechanism will be used.
#endif
  }
}
#ifdef unix
\details{
  If \code{browser} supports remote control and \R knows how to perform
  it, the URL is opened in any already running browser or a new one if
  necessary.  This mechanism currently is available for browsers which
  support the \code{"-remote openURL(...)"} interface (which includes
  Netscape 4.x, 6.2.x (but not 6.0/1), Opera 5/6 and Mozilla >= 0.9.5),
  Galeon, KDE konqueror (via kfmclient) and the GNOME interface to
  Mozilla.  Netscape 7.0 behaves slightly differently, and you will need
  to open it first.  Note that the type of browser is determined from
  its name, so this mechanism will only be used if the browser is
  installed under its canonical name.

  Because \code{"-remote"} will use any browser displaying on the X
  server (whatever machine it is running on), the remote control
  mechanism is only used if \code{DISPLAY} points to the local host.
  This may not allow displaying more than one URL at a time from a
  remote host.
}
#endif
#ifdef windows
\examples{
\dontrun{browseURL("http://www.r-project.org")
browseURL("file://c|/R/rw1060/doc/html/index.html",
          browser="C:/Program Files/Netscape/Netscape/netscp.exe")
}}
#endif
\keyword{file}
\eof
\name{browser}
\alias{browser}
\title{Environment Browser}
\description{
  Interrupt the execution of an expression and allow the inspection of
  the environment where \code{browser} was called from.
}
\usage{
browser()
}
\details{
  A call to \code{browser} causes a pause in the execution of the
  current expression and runs a copy of the \R interpreter which has
  access to variables local to the environment where the call took
  place.

  Local variables can be listed with \code{ls}, and manipulated with \R
  expressions typed to this sub-interpreter.  The interpreter copy is
  exited by typing \code{c}.  Execution then resumes at the statement
  following the call to \code{browser}.

  Typing \code{n} causes the step-through-debugger, to start and it is
  possible to step through the remainder of the function one line at a
  time.

  Typing \code{Q} quits the current execution and returns you to the
  top-level prompt.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Chambers, J. M. (1998)
  \emph{Programming with Data. A Guide to the S Language}.
  Springer.
}
\seealso{
  \code{\link{debug}}, and
  \code{\link{traceback}} for the stack on error.
}
\keyword{programming}
\keyword{environment}
\eof
\name{bug.report}
\alias{bug.report}
\title{Send a Bug Report}
\usage{
bug.report(subject = "", ccaddress = Sys.getenv("USER"),
           method = getOption("mailer"), address = "r-bugs@r-project.org",
#ifdef windows
           file = "R.bug.report", wait = TRUE)
#endif
#ifdef unix
           file = "R.bug.report")
#endif
}
\arguments{
  \item{subject}{Subject of the email. Please do not use single quotes
    (\code{'}) in the subject! File separate bug reports for multiple bugs}
  \item{ccaddress}{Optional email address for copies (default is current
    user).  Use \code{ccaddress = FALSE} for no copies.}
  \item{method}{Submission method, one of \code{"mailx"},
    \code{"gnudoit"}, \code{"none"}, or \code{"ess"}.}
  \item{address}{Recipient's email address.}
  \item{file}{File to use for setting up the email (or storing it when
    method is \code{"none"} or sending mail fails).}
#ifdef windows
  \item{wait}{logical. Should \R wait for the editor to return?}
#endif
}
\description{
  Invokes an editor to write a bug report and optionally mail it to the
  automated r-bugs repository at \email{r-bugs@r-project.org}.  Some standard
  information on the current version and configuration of \R are 
  included automatically.
}
\details{
  Currently direct submission of bug reports works only on Unix systems.
  If the submission method is \code{"mailx"}, then the default editor is
  used to write the bug report. Which editor is used can be controlled
  using \code{\link{options}}, type \code{getOption("editor")} to see what
  editor is currently defined. Please use the help pages of the
  respective editor for details of usage. After saving the bug report
  (in the temporary file opened) and exiting the editor
  the report is mailed using a Unix command line mail utility such as
  \code{mailx}.  A copy of the mail is sent to the current user.

  If method is \code{"gnudoit"}, then an emacs mail buffer is opened
  and used for sending the email.

  If method is \code{"none"} or \code{NULL} (which is the default on
  Windows systems), then only an editor is opened to help writing the
  bug report.  The report can then be copied to your favorite email
  program and be sent to the r-bugs list.

  If method is \code{"ess"} the body of the mail is simply sent to
  stdout.
}
\value{Nothing useful.}
\section{When is there a bug?}{
  If \R executes an illegal instruction, or dies with an operating
  system error message that indicates a problem in the program (as
  opposed to something like \dQuote{disk full}), then it is certainly a
  bug.

  Taking forever to complete a command can be a bug, but you must make
  certain that it was really \R's fault.  Some commands simply take a
  long time.  If the input was such that you KNOW it should have been
  processed quickly, report a bug.  If you don't know whether the
  command should take a long time, find out by looking in the manual or
  by asking for assistance.

  If a command you are familiar with causes an \R error message in a
  case where its usual definition ought to be reasonable, it is probably
  a bug.  If a command does the wrong thing, that is a bug.  But be sure
  you know for certain what it ought to have done.  If you aren't
  familiar with the command, or don't know for certain how the command
  is supposed to work, then it might actually be working right.  Rather
  than jumping to conclusions, show the problem to someone who knows for
  certain.

   Finally, a command's intended definition may not be best for
   statistical analysis.  This is a very important sort of problem, but
   it is also a matter of judgment.  Also, it is easy to come to such a
   conclusion out of ignorance of some of the existing features.  It is
   probably best not to complain about such a problem until you have
   checked the documentation in the usual ways, feel confident that you
   understand it, and know for certain that what you want is not
   available. The mailing list \code{r-devel@r-project.org} is a better
   place for discussions of this sort than the bug list.

   If you are not sure what the command is supposed to do
   after a careful reading of the manual this indicates a bug in the
   manual.  The manual's job is to make everything clear.  It is just as
   important to report documentation bugs as program bugs.

   If the online argument list of a function disagrees with the manual,
   one of them must be wrong, so report the bug.
}
\section{How to report a bug}{
  When you decide that there is a bug, it is important to report it and
  to report it in a way which is useful.  What is most useful is an
  exact description of what commands you type, from when you start \R
  until the problem happens.  Always include the version of \R, machine,
  and operating system that you are using; type \kbd{version} in \R to
  print this.  To help us keep track of which bugs have been fixed and
  which are still open please send a separate report for each bug.

  The most important principle in reporting a bug is to report FACTS,
  not hypotheses or categorizations.  It is always easier to report the
  facts, but people seem to prefer to strain to posit explanations and
  report them instead.  If the explanations are based on guesses about
  how \R is implemented, they will be useless; we will have to try to 
  figure out what the facts must have been to lead to such
  speculations.  Sometimes this is impossible.  But in any case, it is
  unnecessary work for us.

  For example, suppose that on a data set which you know to be quite
  large the command \code{data.frame(x, y, z, monday, tuesday)} never
  returns.  Do not report that \code{data.frame()} fails for large data
  sets.  Perhaps it fails when a variable name is a day of the week.  If
  this is so then when we got your report we would try out the
  \code{data.frame()} command on a large data set, probably with no day
  of the week variable name, and not see any problem. There is no way in
  the world that we could guess that we should try a day of the week
  variable name.

  Or perhaps the command fails because the last command you used was a
  \code{[} method that had a bug causing \R's internal data structures
  to be corrupted and making the \code{data.frame()} command fail from
  then on.  This is why we need to know what other commands you have
  typed (or read from your startup file).

  It is very useful to try and find simple examples that produce
  apparently the same bug, and somewhat useful to find simple examples
  that might be expected to produce the bug but actually do not.  If you
  want to debug the problem and find exactly what caused it, that is
  wonderful.  You should still report the facts as well as any
  explanations or solutions.

  Invoking \R with the \option{--vanilla} option may help in isolating a
  bug.  This ensures that the site profile and saved data files are not
  read.

  A bug report can be generated using the
  \code{bug.report()} function.  This automatically includes the version
  information and sends the bug to the correct address.  Alternatively
  the bug report can be emailed to \email{r-bugs@r-project.org} or
  submitted to the Web page at \url{http://bugs.r-project.org}.

  Bug reports on \strong{contributed packages} should perhaps be sent to the
  package maintainer rather than to r-bugs.
}
\seealso{R FAQ} 
\author{This help page is adapted from the Emacs manual and the R FAQ}
\keyword{utilities}
\keyword{error}
\eof
\name{builtins}
\alias{builtins}
\title{Returns the names of all built-in objects}
\description{
  Return the names of all the built-in objects.  These are fetched
  directly from the symbol table of the \R interpreter.
}
\usage{builtins(internal = FALSE)}
\arguments{
  \item{internal}{a logical indicating whether only \dQuote{internal}
    functions (which can be called via \code{\link{.Internal}}) should
    be returned.}
}
\keyword{utilities}
\eof
\name{bxp}
\alias{bxp}
\title{Box Plots from Summaries}
\description{
  \code{bxp} draws box plots based on the given summaries in \code{z}.
  It is usually called from within \code{\link{boxplot}}, but can be
  invoked directly.
}
\usage{
bxp(z, notch = FALSE, width = NULL, varwidth = FALSE, outline = TRUE,
    notch.frac = 0.5, boxwex = 0.8, border = par("fg"), col = NULL,
    log = "", pars = NULL, frame.plot = axes, horizontal = FALSE,
    add = FALSE, at = NULL, show.names=NULL, \dots)
}
\arguments{
  \item{z}{a list containing data summaries to be used in constructing
    the plots.  These are usually the result of a call to
    \code{\link{boxplot}}, but can be generated in any fashion.}
  \item{notch}{if \code{notch} is \code{TRUE}, a notch is drawn in each
    side of the boxes.  If the notches of two plots do not overlap then
    the medians are significantly different at the 5 percent level.}
  \item{width}{a vector giving the relative widths of the boxes making
    up the plot.}
  \item{varwidth}{if \code{varwidth} is \code{TRUE}, the boxes are drawn
    with widths proportional to the square-roots of the number of
    observations in the groups.}
  \item{outline}{if \code{outline} is not true, the boxplot lines are
    not drawn.}
  \item{boxwex}{a scale factor to be applied to all boxes.  When there
    are only a few groups, the appearance of the plot can be improved by
    making the boxes narrower.}
  \item{notch.frac}{numeric in (0,1). When \code{notch=TRUE}, the
    fraction of the box width that the notches should use.}
  \item{border}{character, the color of the box borders.  Is recycled for
    multiple boxes.}
  \item{col}{character; the color within the box.  Is recycled for
    multiple boxes}
  \item{log}{character, indicating if any axis should be drawn in
    logarithmic scale, as in \code{\link{plot.default}}.}
  \item{frame.plot}{logical, indicating if a \dQuote{frame}
    (\code{\link{box}}) should be drawn; defaults to \code{TRUE}, unless
    \code{axes = FALSE} is specified.}
  \item{horizontal}{logical indicating if the  boxplots should be
    horizontal; default \code{FALSE} means vertical boxes.}
  \item{add}{logical, if true \emph{add} boxplot to current plot.}
  \item{at}{numeric vector giving the locations where the boxplots
    should be drawn, particularly when \code{add = TRUE}; defaults to
    \code{1:n} where \code{n} is the number of boxes.}
  \item{show.names}{Set to \code{TRUE} or \code{FALSE} to override the
    defaults on whether an x-axis label is printed for each group.}
  \item{pars,\dots}{graphical parameters can be passed as arguments to
    this function, either as a list (\code{pars}) or
    normally(\code{\dots}).

    Currently, \code{pch}, \code{cex}, and \code{bg} are passed to
    \code{\link{points}},\cr
    \code{ylim} and \code{axes} to the main plot
    (\code{\link{plot.default}}), \code{xaxt}, \code{yaxt}, \code{las}
    to \code{\link{axis}} and the others to \code{\link{title}}.
  }
}
\value{
  An invisible vector, actually identical to the \code{at} argument,
  with the coordinates ("x" if horizontal is false, "y" otherwise) of
  box centers, useful for adding to the plot.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
set.seed(753)
str(bx.p <- boxplot(split(rt(100, 4), gl(5,20))))
op <- par(mfrow= c(2,2))
bxp(bx.p, xaxt = "n")
bxp(bx.p, notch = TRUE, axes = FALSE, pch = 4)
bxp(bx.p, notch = TRUE, col= "lightblue", frame= FALSE, outl= FALSE,
    main = "bxp(*, frame= FALSE, outl= FALSE)")
bxp(bx.p, notch = TRUE, col= "lightblue", border="red", ylim = c(-4,4),
    pch = 22, bg = "green", log = "x", main = "... log='x', ylim=*")
par(op)
op <- par(mfrow= c(1,2))
data(PlantGrowth)
## single group -- no label
boxplot(weight~group,data=PlantGrowth,subset=group=="ctrl")
bx<-boxplot(weight~group,data=PlantGrowth,subset=group=="ctrl",plot=FALSE)
## with label
bxp(bx,show.names=TRUE)
par(op)
}
\keyword{aplot}
\eof
\name{by}
\alias{by}
\alias{by.default}
\alias{by.data.frame}
\alias{print.by}
\title{Apply a Function to a Data Frame split by Factors}
\description{
  Function \code{by} is an object-oriented wrapper for
  \code{\link{tapply}} applied to data frames.
}
\usage{
by(data, INDICES, FUN, \dots)
}
\arguments{
 \item{data}{an \R object, normally a data frame, possibly a matrix.}
 \item{INDICES}{a factor or a list of factors, each of length \code{nrow(x)}.}
 \item{FUN}{a function to be applied to data frame subsets of \code{x}.}
 \item{\dots}{further arguments to \code{FUN}.}
}
\details{
  A data frame is split by row into data frames
  subsetted by the values of one or more factors, and function
  \code{FUN} is applied to each subset in term.

  Object \code{data} will be coerced to a data frame by default.
}
\value{
  A list of class \code{"by"}, giving the results for each subset.
}
\seealso{\code{\link{tapply}}}

\examples{
data(warpbreaks)
attach(warpbreaks)
by(warpbreaks[, 1:2], tension, summary)
by(warpbreaks[, 1], list(wool=wool, tension=tension), summary)
by(warpbreaks, tension, function(x) lm(breaks ~ wool, data=x))

## now suppose we want to extract the coefficients by group
tmp <- by(warpbreaks, tension, function(x) lm(breaks ~ wool, data=x))
sapply(tmp, coef)

detach("warpbreaks")
}
\keyword{iteration}
\keyword{category}
\eof
\name{c}
\title{Combine Values into a Vector or List}
\usage{
c(\dots, recursive=FALSE)
}
\alias{c}
\description{
  This is a generic function which combines its arguments.

  The default method combines its arguments to form a vector.
  All arguments are coerced to a common type which is the type
  of the returned value.
}
\arguments{
  \item{\dots}{objects to be concatenated.}
  \item{recursive}{logical. If \code{recursive=TRUE}, the function
    recursively descends through lists combining all their elements
    into a vector.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{unlist}} and \code{\link{as.vector}} to produce
  attribute-free vectors.
}
\examples{
c(1,7:9)
c(1:5, 10.5, "next")

## append to a list:
ll <- list(A = 1, c="C")
## do *not* use
c(ll, d = 1:3) # which is == c(ll, as.list(c(d=1:3))
## but rather
c(ll, d = list(1:3))# c() combining two lists

c(list(A=c(B=1)), recursive=TRUE)

c(options(), recursive=TRUE)
c(list(A=c(B=1,C=2), B=c(E=7)), recursive=TRUE)
}
\keyword{manip}
\eof
\name{call}
\alias{call}
\alias{is.call}
\alias{as.call}
\title{Function Calls}
\description{
  Create or test for objects of mode \code{"call"}.
}
\usage{
call(name, \dots)
is.call(x)
as.call(x)
}
\arguments{
  \item{name}{a character string naming the function to be called.}
  \item{\dots}{arguments to be part of the call.}
  \item{x}{an arbitrary \R object.}
}
\details{
  \code{call} returns an unevaluated function call, that is, an
  unevaluated expression which consists of the named function applied to
  the given arguments (\code{name} must be a quoted string which gives
  the name of a function to be called).

  \code{is.call} is used to determine whether \code{x} is a call (i.e.,
  of mode \code{"call"}).
  %NO We don't differentiate between expressions and function calls.
  %NO So \code{is.call} is the same as \code{is.expression}.
  It is generic: you can write methods to handle
  of specific classes of objects, see \link{InternalMethods}.
  
  Objects of mode \code{"list"} can be coerced to mode \code{"call"}.
  The first element of the list becomes the function part of the call,
  so should be a function or the name of one (as a symbol; a quoted
  string will not do).  
}
\seealso{
  \code{\link{do.call}} for calling a function by name and argument
  list;
  \code{\link{Recall}} for recursive calling of functions;
  further
  \code{\link{is.language}},
  \code{\link{expression}},
  \code{\link{function}}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
is.call(call) #-> FALSE: Functions are NOT calls

# set up a function call to round with argument 10.5
cl <- call("round", 10.5)
is.call(cl)# TRUE
cl
# such a call can also be evaluated.
eval(cl)# [1] 10
}
\keyword{programming}
\keyword{attribute}
\eof
\name{capabilities}
\alias{capabilities}
\title{Report Capabilities of this Build of R}
\description{
  Report on the optional features which have been compiled into this
  build of \R.
}
\usage{
capabilities(what = NULL)
}
\arguments{
  \item{what}{character vector or \code{NULL}, specifying
    required components.  \code{NULL} implies that all are required.}
}
\value{
  A named logical vector. Current components are
    \item{jpeg}{Is the \code{\link{jpeg}} function operational?}
    \item{png}{Is the \code{\link{png}} function operational?}
    \item{tcltk}{Is the \pkg{tcltk} package operational?}
    \item{X11}{(Unix)  Are \code{X11} and the data editor available?}
    \item{GNOME}{(Unix)  Is the GNOME GUI in use and are \code{GTK} and
      \code{GNOME} graphics devices available?}
    \item{libz}{Is \code{\link{gzfile}} available?  From \R 1.5.0 this
      will always be true.}
    \item{http/ftp}{Are \code{\link{url}} and the internal method for
      \code{\link{download.file}} available?}
    \item{sockets}{Are \code{\link{make.socket}} and related functions
      available?}
    \item{libxml}{Is there support for integrating \code{libxml} with
      the \R event loop?}
    \item{cledit}{Is command-line editing available in the current \R
      session?  This is false in non-interactive sessions.
#ifdef unix
      It will be true if \code{readline} supported has been compiled in
      and \option{--no-readline} was \emph{not} invoked.
#endif
      }
    \item{IEEE754}{Does this platform have IEEE 754 arithmetic?  Note
      that this is more correctly known by the international standard
      IEC 60559.}
    \item{bzip2}{Is \code{\link{bzfile}} available?}
    \item{PCRE}{Is the Perl-Compatible Regular Expression library
      available?  This is needed for the \code{perl = TRUE} option to
      \code{\link{grep}} are related function.}
    }
}
\seealso{\code{\link{.Platform}}}

\examples{
capabilities()

if(!capabilities("http/ftp"))
   warning("internal download.file() is not available")

## See also the examples for 'connections'.
}
\keyword{utilities}
\eof
\name{capture.output}
\alias{capture.output}
\title{Send output to a character string or file}
\description{
  Evaluates its arguments with the output being returned as a character
  string or sent to a file. Related to \code{\link{sink}} in the same
  way that \code{\link{with}} is related to \code{\link{attach}}.
}
\usage{
capture.output(\dots, file = NULL, append = FALSE)
}
\arguments{
  \item{\dots}{Expressions to be evaluated}
  \item{file}{A file name or a connection, or \code{NULL} to return
    the output as a string. If the connnection is not open it will be
    opened and then closed on exit.}
  \item{append}{Append or overwrite the file? }
}
\value{
 A character string, or \code{NULL} if a \code{file} argument was
 supplied.  
}

\seealso{ \code{\link{sink}}, \code{\link{textConnection}} }

\examples{
glmout<-capture.output(example(glm))
glmout[1:5]
capture.output(1+1,2+2)
capture.output({1+1;2+2})
\dontrun{
## on Unix with enscript available
ps<-pipe("enscript -o tempout.ps","w")
capture.output(example(glm), file=ps)
close(ps)
}
}
\keyword{utilities}% at least one, from doc/KEYWORDS

\eof
\name{cars}
\docType{data}
\alias{cars}
\title{Speed and Stopping Distances of Cars}
\description{
  The data give the speed of cars and the distances taken to stop.
  Note that the data were recorded in the 1920s.
}
\usage{data(cars)}
\format{
  A data frame with 50 observations on 2 variables.
  \tabular{rlll}{
    [,1]  \tab speed  \tab numeric  \tab Speed (mph)\cr
    [,2]  \tab dist   \tab numeric  \tab Stopping distance (ft)
  }
}
\source{
  Ezekiel, M. (1930)
  \emph{Methods of Correlation Analysis}.
  Wiley.
}
\references{
  McNeil, D. R. (1977)
  \emph{Interactive Data Analysis}.
  Wiley.
}
\examples{
data(cars)
plot(cars, xlab = "Speed (mph)", ylab = "Stopping distance (ft)",
     las = 1)
lines(lowess(cars$speed, cars$dist, f = 2/3, iter = 3), col = "red")
title(main = "cars data")
plot(cars, xlab = "Speed (mph)", ylab = "Stopping distance (ft)",
     las = 1, log = "xy")
title(main = "cars data (logarithmic scales)")
lines(lowess(cars$speed, cars$dist, f = 2/3, iter = 3), col = "red")
summary(fm1 <- lm(log(dist) ~ log(speed), data = cars))
opar <- par(mfrow = c(2, 2), oma = c(0, 0, 1.1, 0),
            mar = c(4.1, 4.1, 2.1, 1.1))
plot(fm1)
par(opar)

## An example of polynomial regression
plot(cars, xlab = "Speed (mph)", ylab = "Stopping distance (ft)",
    las = 1, xlim = c(0, 25))
d <- seq(0, 25, len = 200)
for(degree in 1:4) {
  fm <- lm(dist ~ poly(speed, degree), data = cars)
  assign(paste("cars", degree, sep="."), fm)
  lines(d, predict(fm, data.frame(speed=d)), col = degree)
}
anova(cars.1, cars.2, cars.3, cars.4)
}
\keyword{datasets}
\eof
\name{case/variable.names}
\alias{case.names}
\alias{case.names.lm}
\alias{case.names.default}
\alias{variable.names}
\alias{variable.names.lm}
\alias{variable.names.default}
\title{Case and Variable Names of Fitted Models}
\description{
  Simple utilities returning (non-missing) case names, and
  (non-eliminated) variable names.
}
\usage{
case.names(object, \dots)
\method{case.names}{lm}(object, full = FALSE, \dots)

variable.names(object, \dots)
\method{variable.names}{lm}(object, full = FALSE, \dots)
}
\arguments{
 \item{object}{an \R object, typically a fitted model.}
 \item{full}{logical; if \code{TRUE}, all names (including zero weights,
   \dots) are returned.}
 \item{\dots}{further arguments passed to or from other methods.}
}
\value{
  A character vector.
}
\seealso{\code{\link{lm}}}
\examples{
x <- 1:20
y <-  x + (x/4 - 2)^3 + rnorm(20, s=3)
names(y) <- paste("O",x,sep=".")
ww <- rep(1,20); ww[13] <- 0
summary(lmxy <- lm(y ~ x + I(x^2)+I(x^3) + I((x-10)^2),
                   weights = ww), cor = TRUE)
variable.names(lmxy)
variable.names(lmxy, full= TRUE)# includes the last
case.names(lmxy)
case.names(lmxy, full = TRUE)# includes the 0-weight case
}
\keyword{regression}
\keyword{models}
\eof
\name{cat}
\title{Concatenate and Print}
\usage{
cat(\dots , file = "", sep = " ", fill = FALSE, labels = NULL,
    append = FALSE)
}
\alias{cat}
\description{
  Prints the arguments, coercing them if necessary to character mode first.
}
\arguments{
  \item{\dots}{\R objects which are coerced to character strings,
    concatenated, and printed, with the remaining arguments
    controlling the output.}
  \item{file}{A connection, or a character string naming the file
    to print to.  If
    \code{""} (the default), \code{cat} prints to the standard output
    connection, the console unless redirected by \code{\link{sink}}.
#ifdef unix
    If it is \code{"|cmd"}, the output is piped to the command given
    by \file{cmd}, by opening a pipe connection.
#endif
  }
  \item{sep}{character string to insert between the objects to print.}
  \item{fill}{a logical or numeric controlling how the output is
    broken into successive lines.  If \code{FALSE} (default), only newlines
    created explicitly by \samp{\\n} are printed.  Otherwise, the
    output is broken into lines with print width equal to the option
    \code{width} if \code{fill} is \code{TRUE}, or the value of
    \code{fill} if this is numeric.}
  \item{labels}{character vector of labels for the lines printed.
    Ignored if \code{fill} is \code{FALSE}.}
  \item{append}{logical. Only used if the argument \code{file} is the
    name of file (and not a connection or \code{"|cmd"}).
    If \code{TRUE} output will be appended to
    \code{file}; otherwise, it will overwrite the contents of
    \code{file}.}
}
\details{
  \code{cat} converts its arguments to character strings, concatenates
  them, separating them by the given \code{sep=} string, and then
  prints them.

  No linefeeds are printed unless explicitly requested by \samp{\\n}
  or if generated by filling (if argument \code{fill} is \code{TRUE} or
  numeric.)

  \code{cat} is useful for producing output in user-defined functions.
}
\value{
  None (invisible \code{NULL}).
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{print}}, \code{\link{format}}, and \code{\link{paste}}
  which concatenates into a string.
}
\examples{
iter <- rpois(1, lambda=10)
## print an informative message
cat("iteration = ", iter <- iter + 1, "\n")

## 'fill' and label lines:
cat(paste(letters, 100* 1:26), fill = TRUE,
    labels = paste("{",1:10,"}:",sep=""))
}
\keyword{print}
\keyword{file}
\keyword{connection}
\eof
\name{cbind}
\alias{cbind}%%--do C-internal method dispatching !!
\alias{rbind}
\alias{cbind.data.frame}
\alias{rbind.data.frame}
\title{Combine R Objects by Rows or Columns}
\description{
  Take a sequence of vector, matrix or data frames arguments and combine
  by \emph{c}olumns or \emph{r}ows, respectively.  These are generic
  functions with methods for other \R classes.
}
\usage{
cbind(\dots, deparse.level = 1)
rbind(\dots, deparse.level = 1)
}
\arguments{
  \item{\dots}{vectors or matrices.  These can be given as named arguments.}
  \item{deparse.level}{integer controlling the construction of labels;
    currently, \code{1} is the only possible value.}
}
\details{
  The functions \code{cbind} and \code{rbind} are generic, with methods
  for data frames.  The data frame method will be used if an argument is
  a data frame and the rest are vectors or matrices.  There can be other
  methods; in particular, there is one for time series objects.

  The \code{rbind} data frame method takes the classes of the columns
  from the first
  data frame.  Factors are have their levels expanded as necessary (in
  the order of the levels of the levelsets of the factors encountered)
  and the result is an ordered factor if and only if all the components
  were ordered factors.  (The last point differs from S-PLUS.)

  If there are several matrix arguments, they must all have the same
  number of columns (or rows) and this will be the number of columns (or
  rows) of the result.  If all the arguments are vectors, the number of
  columns (rows) in the result is equal to the length of the longest
  vector.  Values in shorter arguments are recycled to achieve this
  length (with a \code{\link{warning}} if they are recycled only
  \emph{fractionally}).

  When the arguments consist of a mix of matrices and vectors the number
  of columns (rows) of the result is determined by the number of columns
  (rows) of the matrix arguments.  Any vectors have their values
  recycled or subsetted to achieve this length.

  For \code{cbind} (\code{rbind}), vectors of zero length (including
  \code{NULL}) are ignored unless the result would have zero rows
  (columns),  for S compatibility.
  (Zero-extent matrices do not occur in S3 and are not ignored in \R.)
}
\value{
  A matrix or data frame combining the \code{\dots} arguments
  column-wise or row-wise.

  For \code{cbind} (\code{rbind}) the column (row) names are taken from
  the names of the arguments, or where those are not supplied by
  deparsing the expressions given (if that gives a sensible name).
  The names will depend on whether data frames are included:
  see the examples.
}
\note{
  The method dispatching is \emph{not} done via
  \code{\link{UseMethod}()}, but by C-internal dispatching.
  Therefore, there is no need for, e.g., \code{rbind.default}.

  The dispatch algorithm is described in the source file
  (\file{.../src/main/bind.c}) as

  \enumerate{
    \item For each argument we get the list of possible class
    memberships from the class attribute.

    \item We inspect each class in turn to see if there is an
    an applicable method.

    \item If we find an applicable method we make sure that it is
     identical to any method determined for prior arguments.
     If it is identical, we proceed, otherwise we immediately
     drop through to the default code.
   }
   If you want to combine other objects with data frames, it may be
   necessary to coerce them to data frames first.  (Note that this
   algorithm can result in calling the data frame method if the
   arguments are all either data frames or vectors, and this will result in
   the coercion of character vectors to factors.)
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{c}} to combine vectors (and lists) as vectors,
  \code{\link{data.frame}} to combine vectors and matrices as a data
  frame.
}
\examples{
cbind(1, 1:7) # the '1' (= shorter vector) is recycled
cbind(1:7, diag(3))# vector is subset -> warning

cbind(0, rbind(1, 1:3))
cbind(I=0, X=rbind(a=1, b=1:3))  # use some names
xx <- data.frame(I=rep(0,2))
cbind(xx, X=rbind(a=1, b=1:3))   # named differently

cbind(0, matrix(1, nrow=0, ncol=4))#> Warning (making sense)
dim(cbind(0, matrix(1, nrow=2, ncol=0)))#-> 2 x 1
}
\keyword{array}
\keyword{manip}
\eof
\name{char.expand}
\alias{char.expand}
\title{Expand a String with Respect to a Target Table}
\usage{char.expand(input, target, nomatch = stop("no match"))}
\description{Seeks a unique match of its first argument among the
  elements of its second.  If successful, it returns this element;
  otherwise, it performs an action specified by the third argument.}
\arguments{
  \item{input}{a character string to be expanded.}
  \item{target}{a character vector with the values to be matched
    against.}
  \item{nomatch}{an \R expression to be evaluated in case expansion was
    not possible.}
}
\details{
  This function is particularly useful when abbreviations are allowed in
  function arguments, and need to be uniquely expanded with respect to a
  target table of possible values.
}
\seealso{
  \code{\link{charmatch}} and \code{\link{pmatch}} for performing
  partial string matching.
}
\examples{
locPars <- c("mean", "median", "mode")
char.expand("me", locPars, warning("Could not expand!"))
char.expand("mo", locPars)
}
\keyword{character}
\eof
\name{character}
\alias{character}
\alias{as.character}
\alias{as.character.default}
\alias{as.character.factor}
\alias{is.character}
\title{Character Vectors}
\description{
  Create or test for objects of type \code{"character"}.
}
\usage{
character(length = 0)
as.character(x, \dots)
is.character(x)
}
\arguments{
  \item{length}{desired length.}
  \item{x}{object to be coerced or tested.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\details{
  \code{as.character} and \code{is.character} are generic: you can
  write methods to handle specific classes of objects,
  see \link{InternalMethods}.
}
\value{
  \code{character} creates a character vector of the specified length.
  The elements of the vector are all equal to \code{""}.

  \code{as.character} attempts to coerce its argument to character type;
  like \code{\link{as.vector}} it strips attributes including names.

  \code{is.character} returns \code{TRUE} or \code{FALSE} depending on
  whether its argument is of character type or not.
}
\note{
  \code{as.character} truncates components of language objects to 500
  characters (was about 70 before 1.3.1).
}
\seealso{
  \code{\link{paste}}, \code{\link{substr}} and \code{\link{strsplit}}
  for character concatenation and splitting,
  \code{\link{chartr}} for character translation and casefolding (e.g.,
  upper to lower case) and \code{\link{sub}}, \code{\link{grep}} etc for
  string matching and substitutions.  Note that
  \code{help.search(keyword = "character")} gives even more links.
%
  \code{\link{deparse}}, which is normally preferable to
  \code{as.character} for language objects.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
form <- y ~ a + b + c
as.character(form)  ## length 3
deparse(form)       ## like the input
}
\keyword{character}
\keyword{classes}
\eof
\name{charmatch}
\title{Partial String Matching}
\usage{
charmatch(x, table, nomatch = NA)
}
\alias{charmatch}
\arguments{
  \item{x}{the values to be matched.}
  \item{table}{the values to be matched against.}
  \item{nomatch}{the value returned at non-matching positions.}
}
\description{
  \code{charmatch} seeks matches for the elements of its first argument
  among those of its second.
}
\details{
  Exact matches are preferred to partial matches (those where the value
  to be matched has an exact match to the initial part of the target,
  but the target is longer).

  If there is a single exact match or no exact match and a unique
  partial match then the index of the matching value is returned; if
  multiple exact or multiple partial matches are found then \code{0} is
  returned and if no match is found then \code{NA} is returned.
}
\author{
  This function is based on a C function written by Terry Therneau.
}
\seealso{
  \code{\link{pmatch}}, \code{\link{match}}.

  \code{\link{grep}} or \code{\link{regexpr}} for more general (regexp)
  matching of strings.
}
\examples{
charmatch("", "")                             # returns 1
charmatch("m",   c("mean", "median", "mode")) # returns 0
charmatch("med", c("mean", "median", "mode")) # returns 2
}
\keyword{character}

\eof
\name{chartr}
\alias{chartr}
\alias{tolower}
\alias{toupper}
\alias{casefold}
\title{Character Translation and Casefolding}
\description{
  Translate characters in character vectors, in particular from upper to
  lower case or vice versa.
}
\usage{
chartr(old, new, x)
tolower(x)
toupper(x)
casefold(x, upper = FALSE)
}
\arguments{
  \item{x}{a character vector.}
  \item{old}{a character string specifying the characters to be
    translated.}
  \item{new}{a character string specifying the translations.}
  \item{upper}{logical: translate to upper or lower case?.}
}
\details{
  \code{chartr} translates each character in \code{x} that is specified
  in \code{old} to the corresponding character specified in \code{new}.
  Ranges are supported in the specifications, but character classes and
  repreated characters are not.  If \code{old} contains more characters
  than new, an error is signaled; if it contains fewer characters, the
  extra characters at the end of \code{new} are ignored.

  \code{tolower} and \code{toupper} convert upper-case characters in a
  character vector to lower-case, or vice versa.  Non-alphabetic
  characters are left unchanged.

  \code{casefold} is a wrapper for \code{tolower} and \code{toupper}
  provided for compatibility with S-PLUS.
}
\seealso{\code{\link{sub}} and \code{\link{gsub}} for other
  substitutions in strings.}
\examples{
x <- "MiXeD cAsE 123"
chartr("iXs", "why", x)
chartr("a-cX", "D-Fw", x)
tolower(x)
toupper(x)
}
\keyword{character}
\eof
\name{check.options}
\alias{check.options}
\title{Set Options with Consistency Checks}
\usage{
check.options(new, name.opt, reset = FALSE, assign.opt = FALSE,
              envir = .GlobalEnv, check.attributes = c("mode", "length"),
              override.check = FALSE)
}
\description{
  Utility function for setting options with some consistency checks.
  The \code{\link{attributes}} of the new settings in \code{new} are
  checked for consistency with the \emph{model} (often default)
  list in \code{name.opt}.}
}
\arguments{
  \item{new}{a \emph{named} list}
  \item{name.opt}{character with the name of \R object containing the
    \dQuote{model} (default) list.}
  \item{reset}{logical; if \code{TRUE}, reset the options from
    \code{name.opt}.  If there is more than one \R object with name
    \code{name.opt}, remove the first one in the \code{\link{search}()} path.}
  \item{assign.opt}{logical; if \code{TRUE}, assign the \ldots}
  \item{envir}{the \code{\link{environment}} used for \code{\link{get}}
    and \code{\link{assign}}.}
  \item{check.attributes}{character containing the attributes which
    \code{check.options} should check.}
  \item{override.check}{logical vector of length \code{length(new)} (or 1
    which entails recycling).
    For those \code{new[i]} where \code{override.check[i] == TRUE}, the
    checks are overriden and the changes made anyway.}
}
%% Source in ../R/postscript.R
\value{
  A list of components with the same names as the one called
  \code{name.opt}.
  The values of the components are changed from the \code{new} list,
  as long as these pass the checks (when these are not overridden
  according to \code{override.check}).
}
\author{Martin Maechler}
\seealso{\code{\link{ps.options}} which uses \code{check.options}.}
% 
\examples{
L1 <- list(a=1:3, b=pi, ch="CH")
str(L2 <- check.options(list(a=0:2), name.opt = "L1"))
str(check.options(NULL, reset = TRUE, name.opt = "L1"))
}
\keyword{utilities}
\keyword{programming}
\eof
\name{chickwts}
\docType{data}
\alias{chickwts}
\title{Chicken Weights by Feed Type}
\description{
  An experiment was conducted to measure and compare the effectiveness
  of various feed supplements on the growth rate of chickens.
}
\usage{data(chickwts)}
\format{
  A data frame with 71 observations on 2 variables.
  \describe{
    \item{weight}{a numeric variable giving the chick weight.}
    \item{feed}{a factor giving the feed type.}
  }
}
\source{
  Anonymous (1948)
  \emph{Biometrika}, \bold{35}, 214.
} 
\details{
  Newly hatched chicks were randomly allocated into six groups, and each
  group was given a different feed supplement.  Their weights in grams
  after six weeks are given along with feed types.
}
\references{
  McNeil, D. R. (1977)
  \emph{Interactive Data Analysis}.
  New York: Wiley.
}
\examples{
data(chickwts)
boxplot(weight ~ feed, data = chickwts, col = "lightgray",
    varwidth = TRUE, notch = TRUE, main = "chickwt data",
    ylab = "Weight at six weeks (gm)")
anova(fm1 <- lm(weight ~ feed, data = chickwts))
opar <- par(mfrow = c(2, 2), oma = c(0, 0, 1.1, 0),
            mar = c(4.1, 4.1, 2.1, 1.1))
plot(fm1)
par(opar)
}
\keyword{datasets}
\eof
\name{chol}
\alias{chol}
\alias{La.chol}
\title{The Choleski Decomposition}
\description{
  Compute the Choleski factorization of a real symmetric
  positive-definite square matrix.
}
\usage{
chol(x, pivot = FALSE,  LINPACK = pivot)
La.chol(x)
}
\arguments{
  \item{x}{a real symmetric, positive-definite matrix}
  \item{pivot}{Should pivoting be used?}
  \item{LINPACK}{logical. Should LINPACK be used (for compatibility with
    \R < 1.7.0)?}
}
\value{
  The upper triangular factor of the Choleski decomposition, i.e., the
  matrix \eqn{R} such that \eqn{R'R = x} (see example).

  If pivoting is used, then two additional attributes
  \code{"pivot"} and \code{"rank"} are also returned.
}
\details{
  \code{chol(pivot = TRUE)} provides an interface to the LINPACK routine DCHDC.
  \code{La.chol} provides an interface to the LAPACK routine DPOTRF.

  Note that only the upper triangular part of \code{x} is used, so
  that \eqn{R'R = x} when \code{x} is symmetric.

  If \code{pivot = FALSE} and \code{x} is not non-negative definite an
  error occurs.  If \code{x} is positive semi-definite (i.e., some zero
  eigenvalues) an error will also occur, as a numerical tolerance is used.

  If \code{pivot = TRUE}, then the Choleski decomposition of a positive
  semi-definite \code{x} can be computed.  The rank of \code{x} is
  returned as \code{attr(Q, "rank")}, subject to numerical errors.
  The pivot is returned as \code{attr(Q, "pivot")}.  It is no longer
  the case that \code{t(Q) \%*\% Q} equals \code{x}.  However, setting
  \code{pivot <- attr(Q, "pivot")} and \code{oo <- order(pivot)}, it
  is true that \code{t(Q[, oo]) \%*\% Q[, oo]} equals \code{x},
  or, alternatively, \code{t(Q) \%*\% Q} equals \code{x[pivot,
  pivot]}.  See the examples.
}

\section{Warning}{
  The code does not check for symmetry.

  If \code{pivot = TRUE} and \code{x} is not non-negative
  definite then there will be no error message but a meaningless
  result will occur.  So only use \code{pivot = TRUE} when \code{x} is
  non-negative definite by construction.
}

\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Dongarra, J. J., Bunch, J. R., Moler, C. B. and Stewart, G. W. (1978)
  \emph{LINPACK Users Guide.}  Philadelphia: SIAM Publications.

  Anderson. E. and ten others (1999)
  \emph{LAPACK Users' Guide}. Third Edition. SIAM.\cr
  Available on-line at
  \url{http://www.netlib.org/lapack/lug/lapack_lug.html}.
}

\seealso{
  \code{\link{chol2inv}} for its \emph{inverse} (without pivoting),
  \code{\link{backsolve}} for solving linear systems with upper
  triangular left sides.

  \code{\link{qr}}, \code{\link{svd}} for related matrix factorizations.
}

\examples{
( m <- matrix(c(5,1,1,3),2,2) )
( cm <- chol(m) )
t(cm) \%*\% cm  #-- = 'm'
crossprod(cm)  #-- = 'm'

# now for something positive semi-definite
x <- matrix(c(1:5, (1:5)^2), 5, 2)
x <- cbind(x, x[, 1] + 3*x[, 2])
m <- crossprod(x)
qr(m)$rank # is 2, as it should be

# chol() may fail, depending on numerical rounding:
# chol() unlike qr() does not use a tolerance.
try(chol(m))

(Q <- chol(m, pivot = TRUE)) # NB wrong rank here ... see Warning section.
## we can use this by
pivot <- attr(Q, "pivot")
oo <- order(pivot)
t(Q[, oo]) \%*\% Q[, oo] # recover m
}
\keyword{algebra}
\keyword{array}
\eof
\name{chol2inv}
\alias{chol2inv}
\alias{La.chol2inv}
\title{Inverse from Choleski Decomposition}
\description{
  Invert a symmetric, positive definite square matrix from its Choleski
  decomposition.
}
\usage{
chol2inv(x, size = NCOL(x), LINPACK = FALSE)
La.chol2inv(x, size = ncol(x))
}
\arguments{
  \item{x}{a matrix.  The first \code{nc} columns of the upper triangle
    contain the Choleski decomposition of the matrix to be inverted.}
  \item{size}{the number of columns of \code{x} containing the
    Choleski decomposition.}
  \item{LINPACK}{logical. Should LINPACK be used (for compatibility with
    \R < 1.7.0)?}
}
\value{
  The inverse of the decomposed matrix.
}
\details{
  \code{chol2inv(LINPACK=TRUE)} provides an interface to the LINPACK
  routine DPODI.
  \code{La.chol2inv} provides an interface to the LAPACK routine DPOTRI.
}
\references{
  Dongarra, J. J., Bunch, J. R., Moler, C. B. and Stewart, G. W. (1978)
  \emph{LINPACK Users Guide}.
  Philadelphia: SIAM Publications.

  Anderson. E. and ten others (1999)
  \emph{LAPACK Users' Guide}. Third Edition.
  SIAM.
  Available on-line at
  \url{http://www.netlib.org/lapack/lug/lapack_lug.html}.
}
\seealso{
  \code{\link{chol}},
  \code{\link{solve}}.
}
\examples{
cma <- chol(ma  <- cbind(1, 1:3, c(1,3,7)))
ma \%*\% chol2inv(cma)
}
\keyword{algebra}
\keyword{array}
\eof
\name{chull}
\alias{chull}
\title{Compute Convex Hull of a Set of Points}
\usage{
chull(x, y=NULL)
}
\arguments{
  \item{x, y}{coordinate vectors of points. This can be specified as two
    vectors \code{x} and \code{y}, a 2-column matrix \code{x}, a list
    \code{x} with two components, etc, see \code{\link{xy.coords}}.}
}
\description{
  Computes the subset of points which lie on the convex hull of the
  set of points specified.
}
\details{
  \code{\link{xy.coords}} is used to interpret the specification of the
  points. The algorithm is that given by Eddy (1977).

  \sQuote{Peeling} as used in the S function \code{chull} can be
  implemented by calling \code{chull} recursively.
}
\value{
  An integer vector giving the indices of the points lying on the
  convex hull, in clockwise order.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Eddy, W. F. (1977) A new convex hull algorithm for planar sets.
  \emph{ACM Transactions on Mathematical Software}, \bold{3}, 398--403.

  Eddy, W. F. (1977) Algorithm 523. CONVEX, A new convex hull
  algorithm for planar sets[Z]. \emph{ACM Transactions on
    Mathematical Software}, \bold{3}, 411--412.
}
\seealso{\code{\link{xy.coords}},\code{\link{polygon}}}

\examples{
X <- matrix(rnorm(2000), ncol=2)
plot(X, cex=0.5)
hpts <- chull(X)
hpts <- c(hpts, hpts[1])
lines(X[hpts, ])
}
\keyword{hplot}
\eof
\name{class}
\title{Object Classes}
\alias{class}
\alias{class<-}
\alias{oldClass}
\alias{oldClass<-}
\alias{unclass}
\alias{inherits}
\description{
  \R possesses a simple generic function mechanism which can be used for
  an object-oriented style of programming.  Method dispatch takes place
  based on the class of the first argument to the generic function.
}
\usage{
class(x)
class(x) <- value
unclass(x)
inherits(x, what, which = FALSE)

oldClass(x)
oldClass(x) <- value
}
\arguments{
  \item{x}{a \R object}
  \item{what, value}{a character vector naming classes.}
  \item{which}{logical affecting return value: see Details.}
}

\details{
  Many \R objects have a \code{class} attribute, a character vector
  giving the names of the classes which the object \dQuote{inherits}
  from.  If the object does not have a class attribute, it has an
  implicit class, \code{"matrix"}, \code{"array"} or the result of
  \code{\link{mode}(x)}.  (Functions \code{oldClass} and
  \code{oldClass<-} get and set the attribute, which can also be done
  directly.)

  When a generic
  function \code{fun} is applied to an object with class attribute
  \code{c("first", "second")}, the system searches for a function called
  \code{fun.first} and, if it finds it, applies it to the object.  If no
  such function is found, a function called \code{fun.second} is tried.
  If no class name produces a suitable function, the function
  \code{fun.default} is used (if it exists).
  If there is no class attribute, the implicit class is tried, then the
  default method.

  The function \code{class} prints the vector of names of classes an
  object inherits from.  Correspondingly, \code{class<-} sets the
  classes an object inherits from.

  \code{unclass} returns (a copy of) its argument with its class
  attribute removed.

  \code{inherits} indicates whether its first argument inherits from any
  of the classes specified in the \code{what} argument.  If \code{which}
  is \code{TRUE} then an integer vector of the same length as
  \code{what} is returned. Each element indicates the position in the
  \code{class(x)} matched by the element of \code{what}; zero indicates
  no match. If \code{which} is \code{FALSE} then \code{TRUE} is 
  returned by \code{inherits} if any of the names in \code{what} match
  with any \code{class}.
}

\note{
  Functions \code{oldClass} and \code{oldClass<-} behave in the same way
  as functions of those names in S-PLUS 5/6, \emph{but} in \R
  \code{\link{UseMethod}} dispatches on the class as returned by
  \code{class} rather than \code{oldClass}.
}

\section{Formal classes}{
  An additional mechanism of \emph{formal} classes has been available in
  packages \pkg{methods} since \R 1.4.0, and as from \R 1.7.0 this
  is attached by default.  For objects which have a formal class, its name
  is returned by \code{class} as a character vector of length one.

  The replacement version of the function sets the class to the value
  provided.  For classes that have a formal definition, directly
  replacing the class this way is strongly deprecated.  The expression
  \code{\link[modreg]{as}(object, value)} is the way to coerce an object to a
  particular class.
}
\seealso{
  \code{\link{UseMethod}}, \code{\link{NextMethod}}.
}
\examples{
  x <- 10
  inherits(x, "a") #FALSE
  class(x)<-c("a", "b")
  inherits(x,"a") #TRUE
  inherits(x, "a", TRUE) # 1
  inherits(x, c("a", "b", "c"), TRUE) # 1 2 0
}
\keyword{methods}
\keyword{classes}
\eof
\name{close.socket}
\title{Close a Socket}
\usage{
close.socket(socket, \dots)
}
\alias{close.socket}
\arguments{
  \item{socket}{A \code{socket} object}
  \item{\dots}{further arguments passed to or from other methods.}
}
\description{
  Closes the socket and frees the space in the file descriptor table.  The
  port may not be freed immediately.
}
\value{
  logical indicating success or failure
}
\author{Thomas Lumley}
\seealso{
  \code{\link{make.socket}}, \code{\link{read.socket}}
}

\keyword{misc}
\eof
\name{co2}
\docType{data}
\alias{co2}
\title{Mauna Loa Atmospheric CO2 Concentration}
\description{
  Atmospheric concentrations of CO\eqn{_2}{2} are expressed in parts per
  million (ppm) and reported in the preliminary 1997 SIO manometric mole
  fraction scale.
}
\usage{data(co2)}
\format{
  A time series of 468 observations; monthly from 1959 to 1997.
}
\details{
  The values for February, March and April of 1964 were missing and have
  been obtained by interpolating linearly between the values for January
  and May of 1964.
}
\source{
  Keeling, C. D. and  Whorf, T. P.,
  Scripps Institution of Oceanography (SIO),
  University of California,
  La Jolla, California USA 92093-0220.

  \url{ftp://cdiac.esd.ornl.gov/pub/maunaloa-co2/maunaloa.co2}.
}
\references{
  Cleveland, W. S. (1993)
  \emph{Visualizing Data}.
  New Jersey: Summit Press.
}
\examples{
data(co2)
plot(co2, ylab = expression("Atmospheric concentration of CO"[2]),
     las = 1)
title(main = "co2 data set")
}
\keyword{datasets}
\eof
\name{codes-deprecated}
\alias{codes-deprecated}
\title{Factor Codes}
\description{
  This (generic) function returns a numeric coding of a factor.  It can
  also be used to assign to a factor using the coded form.

  It is now \code{\link{Deprecated}}.
}
\usage{
codes(x, \dots)
codes(x, \dots) <- value
}
\arguments{
  \item{x}{an object from which to extract or set the codes.}
  \item{\dots}{further arguments passed to or from other methods.}
  \item{value}{replacement value.}
}
\value{
  For an ordered factor, it returns the internal coding (1 for the
  lowest group, 2 for the second lowest, etc.).

  For an unordered factor, an alphabetical ordering of the levels is
  assumed, i.e., the level that is coded 1 is the one whose name is
  sorted first according to the prevailing collating sequence.
  \bold{Warning:} the sort order may well depend on the locale, and
  should not be assumed to be ASCII.
}
\note{
  Normally \code{codes} is not the appropriate function to use with an
  unordered factor.  Use \code{\link{unclass}} or
  \code{\link{as.numeric}} to extract the codes used in the internal
  representation of the factor, as these do not assume that the codes
  are sorted.

  The behaviour for unordered factors is dubious, but compatible with S
  version 3.  To get the internal coding of a factor, use
  \code{\link{as.integer}}.  Note in particular that the codes may not
  be the same in different language locales because of collating
  differences.
}
\seealso{
  \code{\link{factor}}, \code{\link{levels}}, \code{\link{nlevels}}.
}
\examples{\dontrun{
codes(rep(factor(c(20,10)),3))

x <- gl(3,5)
codes(x)[3] <- 2
x

data(esoph)
( ag <- esoph$alcgp[12:1] )
codes(ag)

codes(factor(1:10)) # BEWARE!
}}
\keyword{category}
\keyword{classes}


\eof
\name{coef}
\title{Extract Model Coefficients}
\usage{
coef(object, \dots)
coefficients(object, \dots)
}
\alias{coef}
\alias{coefficients}
\alias{coef.default}
\alias{coef.lm}
\alias{coef.glm}
\alias{coef.aov}
\alias{coef.listof}
\arguments{
  \item{object}{an object for which the extraction of model coefficients is
    meaningful.}
  \item{\dots}{other arguments.}
}
\value{
  Coefficients extracted from the model object \code{object}.
}
\description{
  \code{coef} is a generic function which extracts model coefficients
  from objects returned by modeling functions.  \code{coefficients} is
  an \emph{alias} for it.
}
\details{
  All object classes which are returned by model fitting functions
  should provide a \code{coef} method.  (Note that the method is
  \code{coef} and not \code{coefficients}.)
}
\seealso{
  \code{\link{fitted.values}} and \code{\link{residuals}} for related methods;
  \code{\link{glm}}, \code{\link{lm}} for model fitting.
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S}.
  Wadsworth \& Brooks/Cole.
}
\examples{
x <- 1:5; coef(lm(c(1:3,7,6) ~ x))
}
\keyword{regression}
\keyword{models}
\eof
\name{col}
\alias{col}
\title{Column Indexes}
\description{
  Returns a matrix of integers indicating their column number in the
  matrix.
}
\usage{
col(x, as.factor=FALSE)
}
\arguments{
  \item{x}{a matrix.}
  \item{as.factor}{a logical value indicating whether the value should
    be returned as a factor rather than as numeric.}
}
\value{
  An integer matrix with the same dimensions as \code{x} and whose
  \code{ij}-th element is equal to \code{j}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{row}} to get rows.
}
\examples{
# extract an off-diagonal of a matrix
ma <- matrix(1:12, 3, 4)
ma[row(ma) == col(ma) + 1]

# create an identity 5-by-5 matrix
x <- matrix(0, nr = 5, nc = 5)
x[row(x) == col(x)] <- 1
}
\keyword{array}
\eof
\name{col2rgb}
\alias{col2rgb}
\title{Color to RGB Conversion}
\description{
  \dQuote{Any \R color} to RGB (red/green/blue) conversion.
}
\usage{
col2rgb(col)
}
\arguments{
  \item{col}{vector of any of the three kind of \R colors, i.e., either
    a color name (an element of \code{\link{colors}()}), a hexadecimal
    string of the form \code{"#rrggbb"}, or an integer \code{i} meaning
    \code{palette()[i]}.}
}
\details{
  For integer colors, \code{0} is shorthand for the current
  \code{par("bg")}, and \code{\link{NA}} means \dQuote{nothing} which
  effectively does not draw the corresponding item.

  For character colors, \code{"NA"} is equivalent to \code{NA} above.
}
\value{
  an integer matrix with three rows and number of columns the length
  (and names if any) as \code{col}.
}
\author{Martin Maechler}
\seealso{\code{\link{rgb}}, \code{\link{colors}}, \code{\link{palette}}, etc.}
\examples{
col2rgb("peachpuff")
col2rgb(c(blu = "royalblue", reddish = "tomato")) # names kept

col2rgb(1:8)# the ones from the palette() :

col2rgb(paste("gold", 1:4, sep=""))

col2rgb("#08a0ff")
## all three kind of colors mixed :
col2rgb(c(red="red", palette= 1:3, hex="#abcdef"))

##-- NON-INTRODUCTORY examples --

grC <- col2rgb(paste("gray",0:100,sep=""))
table(print(diff(grC["red",])))# '2' or '3': almost equidistant
## The 'named' grays are in between {"slate gray" is not gray, strictly}
col2rgb(c(g66="gray66", darkg= "dark gray", g67="gray67",
          g74="gray74", gray =      "gray", g75="gray75",
          g82="gray82", light="light gray", g83="gray83"))

crgb <- col2rgb(cc <- colors())
colnames(crgb) <- cc
t(crgb)## The whole table

ccodes <- c(256^(2:0) \%*\% crgb)## = internal codes
## How many names are 'aliases' of each other:
table(tcc <- table(ccodes))
length(uc <- unique(sort(ccodes))) # 502
## All the multiply named colors:
mult <- uc[tcc >= 2]
cl <- lapply(mult, function(m) cc[ccodes == m])
names(cl) <- apply(col2rgb(sapply(cl, function(x)x[1])),
                   2, function(n)paste(n, collapse=","))
str(cl)
\dontrun{
 if(require(xgobi)) { ## Look at the color cube dynamically :
   tc <- t(crgb[, !duplicated(ccodes)])
   table(is.gray <- tc[,1] == tc[,2] & tc[,2] == tc[,3])# (397, 105)
   xgobi(tc, color = c("gold", "gray")[1 + is.gray])
 }
}
}
\keyword{color}
\keyword{dplot}
\eof
\name{colSums}
\alias{colSums}
\alias{rowSums}
\alias{colMeans}
\alias{rowMeans}
\title{Form Row and Column Sums and Means}
\description{
  Form row and column sums and means for numeric arrays.
}
\usage{
colSums (x, na.rm = FALSE, dims = 1)
rowSums (x, na.rm = FALSE, dims = 1)
colMeans(x, na.rm = FALSE, dims = 1)
rowMeans(x, na.rm = FALSE, dims = 1)
}
\arguments{
  \item{x}{an array of two or more dimensions, containing numeric,
    complex, integer or logical values, or a numeric data frame.}
  \item{na.rm}{logical. Should missing values (including \code{NaN})
    be omitted from the calculations?}
  \item{dims}{Which dimensions are regarded as \dQuote{rows} or
    \dQuote{columns} to sum over.  For \code{row*}, the sum or mean is
    over dimensions \code{dims+1, \dots}; for \code{col*} it is over
    dimensions \code{1:dims}.}
}
\details{
  These functions are equivalent to use of \code{\link{apply}} with
  \code{FUN = mean} or \code{FUN = sum} with appropriate margins, but
  are a lot faster.  As they are written for speed, they blur over some
  of the subtleties of \code{NaN} and \code{NA}.  If \code{na.rm =
    FALSE} and either \code{NaN} or \code{NA} appears in a sum, the
  result will be one of \code{NaN} or \code{NA}, but which might be
  platform-dependent.
}
\value{
  A numeric or complex array of suitable size, or a vector if the result is
  one-dimensional.  The \code{dimnames} (or \code{names} for a vector
  result) are taken from the original array.

  If there are no values in a range to be summed over (after removing
  missing values with \code{na.rm = TRUE}), that
  component of the output is set to \code{0} (\code{*Sums}) or \code{NA}
  (\code{*Means}), consistent with \code{\link{sum}} and \code{\link{mean}}.
}
\seealso{
  \code{\link{apply}}, \code{\link{rowsum}}
}
\examples{
## Compute row and column sums for a matrix:
x <- cbind(x1 = 3, x2 = c(4:1, 2:5))
rowSums(x); colSums(x)
dimnames(x)[[1]] <- letters[1:8]
rowSums(x); colSums(x); rowMeans(x); colMeans(x)
x[] <- as.integer(x)
rowSums(x); colSums(x)
x[] <- x < 3
rowSums(x); colSums(x)
x <- cbind(x1 = 3, x2 = c(4:1, 2:5))
x[3, ] <- NA; x[4, 2] <- NA
rowSums(x); colSums(x); rowMeans(x); colMeans(x)
rowSums(x, na.rm = TRUE); colSums(x, na.rm = TRUE)
rowMeans(x, na.rm = TRUE); colMeans(x, na.rm = TRUE)

## an array
data(UCBAdmissions)
dim(UCBAdmissions)
rowSums(UCBAdmissions); rowSums(UCBAdmissions, dims = 2)
colSums(UCBAdmissions); colSums(UCBAdmissions, dims = 2)

## complex case
x <- cbind(x1 = 3 + 2i, x2 = c(4:1, 2:5) - 5i)
x[3, ] <- NA; x[4, 2] <- NA
rowSums(x); colSums(x); rowMeans(x); colMeans(x)
rowSums(x, na.rm = TRUE); colSums(x, na.rm = TRUE)
rowMeans(x, na.rm = TRUE); colMeans(x, na.rm = TRUE)
}
\keyword{array}
\keyword{algebra}
\eof
\name{row/colnames}
\title{Row and Column Names}
\alias{rownames}
\alias{rownames<-}
\alias{colnames}
\alias{colnames<-}
\usage{
rownames(x, do.NULL = TRUE, prefix = "row")
rownames(x) <- value

colnames(x, do.NULL = TRUE, prefix = "col")
colnames(x) <- value
}
\description{
  Retrieve or set the row or column names of a matrix-like object.
}
\arguments{
  \item{x}{a matrix-like \R object, with at least two dimensions for
    \code{colnames}.}
  \item{do.NULL}{logical.  Should this create names if they are
    \code{NULL}?}
  \item{prefix}{for created names.}
  \item{value}{a valid value for that component of
    \code{\link{dimnames}(x)}.  For a matrix or array this is either
    \code{NULL} or a character vector of length the appropriate
    dimension.}
}
\details{
  The extractor functions try to do something sensible for any
  matrix-like object \code{x}.  If the object has \code{\link{dimnames}}
  the first component is used as the row names, and the second component
  (if any) is used for the col names.  For a data frame, \code{rownames}
  and \code{colnames} are equivalent to \code{\link{row.names}} and
  \code{\link{names}} respectively.

  If \code{do.NULL} is \code{FALSE}, a character vector (of length
  \code{\link{NROW}(x)} or \code{\link{NCOL}(x)}) is returned in any
  case, prepending \code{prefix} to simple numbers, if there are no
  dimnames or the corresponding component of the dimnames is \code{NULL}.

  For a data frame, \code{value} for \code{rownames} should be a
  character vector of unique names, and for \code{colnames} a character
  vector of unique syntactically-valid names.  (Note: uniqueness and
  validity are not enforced.)
}
\seealso{
  \code{\link{dimnames}},
  \code{\link{case.names}},
  \code{\link{variable.names}}.
}
\examples{
m0 <- matrix(NA, 4, 0)
rownames(m0)

m2 <- cbind(1,1:4)
colnames(m2, do.NULL = FALSE)
colnames(m2) <- c("x","Y")
rownames(m2) <- rownames(m2, do.NULL = FALSE, prefix = "Obs.")
m2
}
\keyword{array}
\keyword{manip}
\eof
\name{colors}
\alias{colors}
\alias{colours}
\title{Color Names}
\description{
  Returns the built-in color names which \R knows about.
}
\usage{
colors()
}
\details{
  These color names can be used with a \code{col=} specification in
  graphics functions.

  An even wider variety of colors can be created with primitives
  \code{rgb} and \code{hsv} or the derived \code{rainbow},
  \code{heat.colors}, etc.
}
\value{
  A character vector containing all the built-in color names.
}
\seealso{
  \code{\link{palette}} for setting the \dQuote{palette} of colors for
  \code{par(col=}\emph{<num>}\code{)};
  \code{\link{rgb}}, \code{\link{hsv}}, \code{\link{gray}};
  \code{\link{rainbow}} for a nice example;
  and \code{\link{heat.colors}}, \code{\link{topo.colors}} for images.

  \code{\link{col2rgb}} for translating to RGB numbers and extended
  examples.
}
\examples{
str(colors())
}
\keyword{color}
\keyword{dplot}
\keyword{sysdata}
\eof
\name{commandArgs}
\alias{commandArgs}
\title{Extract Command Line Arguments}
\description{
  Provides access to a copy of the command line arguments supplied when
  this \R session was invoked.
}
\usage{
commandArgs()
}
\details{
  These arguments are captured before the standard \R command line
  processing takes place.  This means that they are the unmodified
  values.  If it were useful, we could provide support an argument which
  indicated whether we want the unprocessed or processed values.

  This is especially useful with the \code{--args} command-line flag to
  \R, as all of the command line after than flag is skipped.
}
\value{
  A character vector containing the name of the executable and the
  user-supplied command line arguments.  The first element is the name
  of the executable by which \R was invoked.  As far as I am aware, the
  exact form of this element is platform dependent.  It may be the fully
  qualified name, or simply the last component (or basename) of the
  application.
}
%\author{DTL}
#ifdef unix
\seealso{\code{\link{BATCH}}}
#endif
\examples{
commandArgs()
## Spawn a copy of this  application as it was invoked.
## system(paste(commandArgs(), collapse=" "))
}
\keyword{environment}
\keyword{sysdata}
\keyword{programming}
\eof
\name{comment}
\title{Query or Set a `Comment' Attribute}
\usage{
comment(x)
comment(x) <- value
}
\alias{comment}
\alias{comment<-}
\arguments{
 \item{x}{any \R object}
 \item{value}{a \code{character} vector}
}
\description{
  These functions set and query a \emph{comment}
  attribute for any \R objects.  This is typically useful for
  \code{\link{data.frame}}s or model fits.

  Contrary to other \code{\link{attributes}}, the \code{comment} is not
  printed (by \code{\link{print}} or \code{\link{print.default}}).
}
\seealso{
  \code{\link{attributes}} and \code{\link{attr}} for \dQuote{normal}
  attributes.
}
\examples{
x <- matrix(1:12, 3,4)
comment(x) <- c("This is my very important data from experiment #0234",
                "Jun 5, 1998")
x
comment(x)
}
\keyword{attribute}
\eof
\name{complete.cases}
\alias{complete.cases}
\title{Find Complete Cases}
\description{
  Return a logical vector indicating which cases are complete, i.e.,
  have no missing values.
}
\usage{
complete.cases(\dots)
}
\arguments{
  \item{\dots}{a sequence of vectors, matrices and data frames.}
}
\value{
  A logical vector specifying which observations/rows have no missing
  values across the entire sequence.
}
\seealso{
  \code{\link{is.na}},
  \code{\link{na.omit}},
  \code{\link{na.fail}}.
}
\examples{
data(airquality)
x <- airquality[, -1] # x is a regression design matrix
y <- airquality[,  1] # y is the corresponding response

stopifnot(complete.cases(y) != is.na(y))
ok <- complete.cases(x,y)
sum(!ok) # how many are not "ok" ?
x <- x[ok,]
y <- y[ok]
}
\keyword{NA}
\keyword{logic}
\eof
\name{complex}
\title{Complex Vectors}
\alias{complex}
\alias{as.complex}
\alias{as.complex.default}
\alias{is.complex}
\alias{Re}
\alias{Im}
\alias{Mod}
\alias{Arg}
\alias{Conj}
\description{
  Basic functions which support complex arithmetic in R.
}
\usage{
complex(length.out = 0, real = numeric(), imaginary = numeric(),
        modulus = 1, argument = 0)
as.complex(x, \dots)
is.complex(x)

Re(x)
Im(x)
Mod(x)
Arg(x)
Conj(x)
}
\arguments{
  \item{length.out}{numeric.  Desired length of the output vector,
    inputs being recycled as needed.}
  \item{real}{numeric vector.}
  \item{imaginary}{numeric vector.}
  \item{modulus}{numeric vector.}
  \item{argument}{numeric vector.}
  \item{x}{an object, probably of mode \code{complex}.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\details{
  Complex vectors can be created with \code{complex}.  The vector can be
  specified either by giving its length, its real and imaginary parts, or
  modulus and argument. (Giving just the length generates a vector of
  complex zeroes.)
  
  \code{as.complex} attempts to coerce its argument to be of complex
  type: like \code{\link{as.vector}} it strips attributes including names.

  Note that \code{is.complex} and \code{is.numeric} are never both
  \code{TRUE}.

  The functions \code{Re}, \code{Im}, \code{Mod}, \code{Arg} and
  \code{Conj} have their usual interpretation as returning the real
  part, imaginary part, modulus, argument and complex conjugate for
  complex values. Modulus and argument are also called the \emph{polar
      coordinates}. If \eqn{z = x + i y} with real \eqn{x} and \eqn{y},
  \code{Mod}\eqn{(z) = \sqrt{x^2 + y^2}}, and for
  \eqn{\phi= Arg(z)}, \eqn{x = \cos(\phi)} and \eqn{y = \sin(\phi)}.

  In addition, the elementary trigonometric, logarithmic and exponential
  functions are available for complex values.

  \code{is.complex} is generic: you can write methods to handle
  of specific classes of objects, see \link{InternalMethods}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
0i ^ (-3:3)

matrix(1i^ (-6:5), nr=4)#- all columns are the same
0 ^ 1i # a complex NaN

## create a complex normal vector
z <- complex(real = rnorm(100), imag = rnorm(100))
## or also (less efficiently):
z2 <- 1:2 + 1i*(8:9)

## The Arg(.) is an angle:
zz <- (rep(1:4,len=9) + 1i*(9:1))/10
zz.shift <- complex(modulus = Mod(zz), argument= Arg(zz) + pi)
plot(zz, xlim=c(-1,1), ylim=c(-1,1), col="red", asp = 1,
     main = expression(paste("Rotation by "," ", pi == 180^o)))
abline(h=0,v=0, col="blue", lty=3)
points(zz.shift, col="orange")
}
\keyword{complex}
\eof
\name{conditions}
\alias{computeRestarts}
\alias{conditionCall}
\alias{conditionMessage}
\alias{findRestart}
\alias{invokeRestart}
\alias{invokeRestartInteractively}
\alias{isRestart}
\alias{restartDescription}
\alias{restartFormals}
\alias{signalCondition}
\alias{simpleCondition}
\alias{simpleError}
\alias{simpleWarning}
\alias{tryCatch}
\alias{withCallingHandlers}
\alias{withRestarts}

\alias{.signalSimpleWarning}
\alias{.handleSimpleError}

\alias{as.character.condition}
\alias{as.character.error}
\alias{conditionCall.condition}
\alias{conditionMessage.condition}
\alias{print.condition}
\alias{print.restart}

\title{Condition Handling and Recovery}
\description{
  These functions provide a mechanism for handling unusual conditions,
  including errors and warnings.
}

\usage{
tryCatch(expr, ..., finally)
withCallingHandlers(expr, ...)

signalCondition(cond)

simpleCondition(message, call = NULL)
simpleError(message, call = NULL)
simpleWarning(message, call = NULL)

\method{as.character}{condition}(x, ...)
\method{as.character}{error}(x, ...)
\method{print}{condition}(x, ...)
\method{print}{restart}(x, ...)

conditionCall(c)
\method{conditionCall}{condition}(c)
conditionMessage(c)
\method{conditionMessage}{condition}(c)

withRestarts(expr, ...)

computeRestarts(cond = NULL)
findRestart(name, cond = NULL)
invokeRestart(r, ...)
invokeRestartInteractively(r)

isRestart(x)
restartDescription(r)
restartFormals(r)

.signalSimpleWarning(msg, call)
.handleSimpleError(h, msg, call)

}

\arguments{
  \item{c}{a condition object.}
  \item{call}{call expression.}
  \item{cond}{a condition object.}
  \item{expr}{expression to be evaluated.}
  \item{finally}{expression to be evaluated before returning or exiting.}
  \item{h}{function.}
  \item{message}{character string.}
  \item{msg}{character string.}
  \item{name}{character string naming a restart.}
  \item{r}{restart object.}
  \item{x}{object.}
  \item{\dots}{additional arguments; see details below.}
}

\details{

   The condition system provides a mechanism for signaling and
   handling unusual conditions, including errors and warnings.
   Conditions are represented as objects that contain information
   about the condition that occurred, such as a message and the call in
   which the condition occurred.  Currently conditions are S3-style
   objects, though this may eventually change.

   Conditions are objects inheriting from the abstract class
   \code{condition}.  Errors and warnings are objects inheriting
   from the abstract subclasses \code{error} and \code{warning}.
   The class \code{simpleError} is the class used by \code{stop}
   and all internal error signals.  Similarly, \code{simpleWarning}
   is used by \code{warning}.  The constructors by the same names take
   a string describing the condition as argument and an optional call.
   The functions \code{conditionMessage} and \code{conditionCall} ae
   generic functions that return the message and call of a condition.

   Conditions are signaled by \code{signalCondition}.  In addition,
   the \code{stop} and \code{warning} functions have been modified to
   also accept condition arguments.  

   The function \code{tryCatch} evaluates its expression argument
   in a context where the handlers provided in the \code{\dots}
   argument are available.  The \code{finally} expression is then
   evaluated in the context in which \code{tryCatch} was called; that
   is, the handlers supplied to the current \code{tryCatch} call are
   not active when the \code{finally} expression is evaluated.

   Handlers provided in the \code{\dots} argument to \code{tryCatch}
   are established for the duration of the evaluation of \code{expr}.
   If no condition is signaled when evaluating \code{expr} then
   \code{tryCatch} returns the value of the expression.

   If a condition is signaled while evaluating \code{expr} then
   established handlers are checked, starting with the most recently
   established ones, for one matching the class of the condition.
   When several handlers are supplied in a single \code{tryCatch} then
   the first one is considered more recent than the second.  If a
   handler is found then control is transferred to the
   \code{tryCatch} call that established the handler, the handler
   found and all more recent handlers are disestablished, the handler
   is called with the condition as its argument, and the result
   returned by the handler is returned as the value of the
   \code{tryCatch} call.

   Calling handlers are established by \code{withCallingHandlers}.  If
   a condition is signaled and the applicable handler is a calling
   handler, then the handler is called by \code{signalCondition} in
   the context where the condition was signaled but with the available
   handlers restricted to those below the handler called in the
   handler stack.  If the handler returns, then the next handler is
   tried; once the last handler has been tried, \code{signalCondition}
   returns \code{NULL}.

   User interrupts signal a condition of class \code{interrupt} that
   inherits directly from class \code{condition} before executing the
   default interrupt action.

   Restarts are used for establishing recovery protocols.  They can be
   established using \code{withRestarts}.  One pre-established restart is
   an \code{abort} restart that represents a jump to top level.

   \code{findRestart} and \code{computeRestarts} find the available
   restarts.  \code{findRestart} returns the most recently established
   restart of the specified name.  \code{computeRestarts} returns a
   list of all restarts.  Both can be given a condition argument and
   will then ignore restarts that do not apply to the condition.

   \code{invokeRestart} transfers control to the point where the
   specified restart was established and calls the restart's handler with the
   arguments, if any, given as additional arguments to
   \code{invokeRestart}.  The restart argument to \code{invokeRestart}
   can be a character string, in which case \code{findRestart} is used
   to find the restart.
   
   New restarts for \code{withRestarts} can be specified in several ways.
   The simplest is in \code{name=function} form where the function is
   the handler to call when the restart is invoked.  Another simple
   variant is as \code{name=string} where the string is stored in the
   \code{description} field of the restart object returned by
   \code{findRestart}; in this case the handler ignores its arguments
   and returns \code{NULL}.  The most flexible form of a restart
   specification is as a list that can include several fields, including
   \code{hander}, \code{description}, and \code{test}.  The
   \code{test} field should contain a function of one argument, a
   condition, that returns \code{TRUE} if the restart applies to the
   condition and \code{FALSE} if it does not; the default function
   returns \code{TRUE} for all conditions.

   One additional field that can be specified for a restart is
   \code{interactive}.  This should be a function of no arguments that
   returns a list of arguments to pass to the restart handler.  The list
   could be obtained by interacting with the user if necessary.  The
   function \code{invokeRestartInteractively} calls this function to
   obtain the arguments to use when invoking the restart.  The default
   \code{interactive} method queries the user for values for the
   formal arguments of the handler function.

   \code{.signalSimpleWarning} and \code{.handleSimpleError}
   are used internally and should not be called directly.
}

\references{The \code{tryCatch} mechanism is similar to Java
  error handling.  Calling handlers are based on Common Lisp and
  Dylan.  Restarts are based on the Common Lisp restart mechanism.}

\seealso{\code{stop} and \code{warning} signal conditions, and
  \code{try} is essentially a simplified version of \code{tryCatch}.
}

\examples{
tryCatch(1, finally=print("Hello"))
e<-simpleError("test error")
\dontrun{stop(e)}
\dontrun{tryCatch(stop(e), finally=print("Hello"))}
\dontrun{tryCatch(stop("fred"), finally=print("Hello"))}
tryCatch(stop(e), error = function(e) e, finally=print("Hello"))
tryCatch(stop("fred"),  error = function(e) e, finally=print("Hello"))
withCallingHandlers({ warning("A"); 1+2 }, warning = function(w) {})
{ try(invokeRestart("tryRestart")); 1}
\dontrun{{ withRestarts(stop("A"), abort = function() {}); 1}}
withRestarts(invokeRestart("foo", 1, 2), foo = function(x, y) {x + y})
}
\keyword{programming}
\keyword{error}
\eof
\name{confint}
\alias{confint}
\alias{confint.lm}
\title{Confidence Intervals for Model Parameters}
\description{
  Computes confidence intervals for one or more parameters in a fitted
  model.  Base has a method for objects inheriting from class
  \code{"lm"}.
}
\usage{
confint(object, parm, level = 0.95, \dots)
}
\arguments{
\item{object}{
a fitted model object.
}
\item{parm}{
a specification of which parameters are to be given confidence
intervals, either a vector of numbers or a vector of names. If
missing, all parameters are considered.
}
\item{level}{
the confidence level required.
}
\item{\dots}{
additional argument(s) for methods
}}
\value{
A matrix (or vector) with columns giving lower and upper confidence
limits for each parameter. These will be labelled as (1-level)/2 and
1 - (1-level)/2 in \% (by default 2.5\% and 97.5\%).
}
\details{
  \code{confint} is a generic function with no default method.
  For objects of class \code{"lm"} the direct formulae based on t values
  are used.

  Package \pkg{MASS} contains methods for \code{"glm"} and \code{"nls"}
  objects.
}
\seealso{
  \code{\link[MASS]{confint.nls}}
}
\examples{
data(mtcars)
fit <- lm(100/mpg ~ disp + hp + wt + am, data=mtcars)
confint(fit)
confint(fit, "wt")
}
\keyword{models}
\eof
\name{conflicts}
\title{Search for Masked Objects on the Search Path}
\usage{
conflicts(where=search(), detail=FALSE)
}
\alias{conflicts}
\arguments{
 \item{where}{A subset of the search path, by default the whole search path.}
 \item{detail}{If \code{TRUE}, give the masked or masking functions for
   all members of the search path.}
}
\description{
    \code{conflicts} reports on objects that exist with the same name in
    two or more places on the \code{\link{search}} path, usually because
    an object in the user's workspace or a package is masking a system
    object of the same name.  This helps discover unintentional masking.
}
\value{
    If \code{detail=FALSE}, a character vector of masked objects.
    If \code{detail=TRUE}, a list of character vectors giving the masked or
    masking objects in that member of the search path.  Empty vectors are
    omitted.
}
\examples{
lm <- 1:3
conflicts(, TRUE)
## gives something like
# $.GlobalEnv
# [1] "lm"
#
# $package:base
# [1] "lm"

## Remove things from your "workspace" that mask others:
remove(list = conflicts(detail=TRUE)$.GlobalEnv)
}
\keyword{utilities}
\eof
\name{connections}
\alias{connections}
\alias{connection}
\alias{file}
\alias{pipe}
\alias{fifo}
\alias{gzfile}
\alias{unz}
\alias{bzfile}
\alias{url}
\alias{socketConnection}
\alias{open}
\alias{open.connection}
\alias{isOpen}
\alias{isIncomplete}
\alias{close}
\alias{close.connection}
\alias{flush}
\alias{flush.connection}
\alias{print.connection}
\alias{summary.connection}
\alias{ISOLatin1}
\alias{MacRoman}
\alias{WinAnsi}
\alias{native.enc}
\title{Functions to Manipulate Connections}
\description{
  Functions to create, open and close connections.
}
\usage{
file(description = "", open = "", blocking = TRUE,
     encoding = getOption("encoding"))
pipe(description, open = "", encoding = getOption("encoding"))
fifo(description = "", open = "", blocking = FALSE,
     encoding = getOption("encoding"))
gzfile(description, open = "", encoding = getOption("encoding"),
       compression = 6)
unz(description, filename, open = "", encoding = getOption("encoding"))
bzfile(description, open = "", encoding = getOption("encoding"))
url(description, open = "", blocking = TRUE,
    encoding = getOption("encoding"))
socketConnection(host = "localhost", port, server = FALSE,
                 blocking = FALSE, open = "a+",
                 encoding = getOption("encoding"))

open(con, \dots)
\method{open}{connection}(con, open = "r", blocking = TRUE, \dots)
close(con, \dots)
\method{close}{connection}(con, type = "rw", \dots)

flush(con)

isOpen(con, rw = "")
isIncomplete(con)
}
\arguments{
  \item{description}{character. A description of the connection. For
    \code{file} and \code{pipe} this is a path to the file to be opened.
    For \code{url} it is a complete URL, including schemes
    (\code{http://}, \code{ftp://} or \code{file://}).  \code{file} also
    accepts complete URLs.
  }
  \item{filename}{a filename within a zip file.}
  \item{con}{a connection.}
  \item{host}{character.  Host name for port.}
  \item{port}{integer.  The TCP port number.}
  \item{server}{logical.  Should the socket be a client or a server?}
  \item{open}{character.  A description of how to open the connection
    (if at all). See Details for possible values.}
  \item{blocking}{logical.  See \sQuote{Blocking} section below.}
  \item{encoding}{An integer vector of length 256.}
  \item{compression}{integer in 0--9.  The amount of compression to be
    applied when writing, from none to maximal.  The default is a good
    space/time compromise.}
  \item{type}{character. Currently ignored.}
  \item{rw}{character.  Empty or \code{"read"} or \code{"write"},
    partial matches allowed.}
  \item{\dots}{arguments passed to or from other methods.}
}
\details{
  The first eight functions create connections.  By default the
  connection is not opened (except for \code{socketConnection}), but may
  be opened by setting a non-empty value of argument \code{open}.

  \code{gzfile} applies to files compressed by \file{gzip}, and
  \code{bzfile} to those compressed by \file{bzip2}: such connections can
  only be binary.

  \code{unz} reads (only) single files within zip files, in binary mode.
  The description is the full path, with \file{.zip} extension if required.

  All platforms support (gz)file connections and \code{url("file://")}
  connections.  The other types may be partially implemented or
  not implemented at all.  (They do work on most Unix
  platforms, and all but \code{fifo} on Windows.)

  Proxies can be specified for \code{url} connections: see
  \code{\link{download.file}}.

  \code{open}, \code{close} and \code{seek} are generic functions: the
  following applies to the methods relevant to connections.

  \code{open} opens a connection.  In general functions using
  connections will open them if they are not open, but then close them
  again, so to leave a connection open call \code{open} explicitly.

  Possible values for the mode \code{open} to open a connection are
  \describe{
    \item{\code{"r"} or \code{"rt"}}{Open for reading in text mode.}
    \item{\code{"w"} or \code{"wt"}}{Open for writing in text mode.}
    \item{\code{"a"} or \code{"at"}}{Open for appending in text mode.}
    \item{\code{"rb"}}{Open for reading in binary mode.}
    \item{\code{"wb"}}{Open for writing in binary mode.}
    \item{\code{"ab"}}{Open for appending in binary mode.}
    \item{\code{"r+"}, \code{"r+b"}}{Open for reading and writing.}
    \item{\code{"w+"}, \code{"w+b"}}{Open for reading and writing,
      truncating file initially.}
    \item{\code{"a+"}, \code{"a+b"}}{Open for reading and appending.}
  }
  Not all modes are applicable to all connections: for example URLs can
  only be opened for reading.  Only file and socket connections can be
  opened for reading and writing/appending.
  For many connections there is little or no
  difference between text and binary modes, but there is for file-like
  connections on Windows, and \code{\link{pushBack}} is text-oriented and
  is only allowed on connections open for reading in text mode.

  \code{close} closes and destroys a connection.

  \code{flush} flushes the output stream of a connection open for
  write/append (where implemented).

  If for a \code{file} connection the description is \code{""}, the file
  is immediately opened in \code{"w+"} mode and unlinked from the file
  system.  This provides a temporary file to write to and then read from.
  
  The encoding vector is used to map the input from a file or pipe to
  the platform's native character set.  Supplied examples are
  \code{native.enc} as well as \code{MacRoman}, \code{WinAnsi} and
  \code{ISOLatin1}, whose actual encoding is platform-dependent.  Missing
  characters are mapped to a space in these encodings.
}
\value{
  \code{file}, \code{pipe}, \code{fifo}, \code{url}, \code{gzfile} and
  \code{socketConnection} return a connection object
  which inherits from class \code{"connection"} and has a first more
  specific class.

  \code{isOpen} returns a logical value, whether the connection is
  currently open.

  \code{isIncomplete} returns a logical value, whether last read attempt
  was blocked, or for an output text connection whether there is
  unflushed output.
}
\section{Blocking}{
  The default condition for all but fifo and socket connections is to be in
  blocking mode.  In that mode, functions do not return to the \R
  evaluator until they are complete.   In non-blocking mode, operations
  return as soon as possible, so on input they will return with whatever
  input is available (possibly none) and for output they will return
  whether or not the write succeeded.

  The function \code{\link{readLines}} behaves differently in respect of
  incomplete last lines in the two modes: see its help page.

  Even when a connection is in blocking mode, attempts are made to
  ensure that it does not block the event loop and hence the operation
  of GUI parts of \R.  These do not always succeed, and the whole
  process will be blocked during a DNS lookup on Unix, for example.

  Most blocking operations on URLs and sockets are subject to the
  timeout set by \code{options("timeout")}.  Note that this is a timeout
  for no response at all, not for the whole operation.
}
\section{Fifos}{
  Fifos default to non-blocking.  That follows Svr4 and it probably most
  natural, but it does have some implications.
  In particular, opening a non-blocking fifo connection for writing
  (only) will fail unless some other process is reading on the fifo.

  Opening a fifo for both reading and writing (in any mode: one can only
  append to fifos) connects both sides of the fifo to the \R process,
  and provides an similar facility to \code{file()}.
}
#ifdef windows
\section{Clipboard}{
  Under Windows, \code{file} can also be used with \code{description =
    "clipboard"} in mode \code{"w"} and \code{"w"} only.
  
  When the clipboard is opened for reading, the contents are immediately
  copied to internal storage in the connection.

  When writing to the clipboard, the output is
  copied to the clipboard only when the connection is closed or flushed.
  There is a 32Kb limit of the text to be written to the clipboard.
}
#endif
\note{
  \R's connections are modelled on those in S version 4 (see Chambers,
  1998). However \R goes well beyond the Svr4 model, for example
  in output text connections and URL, gzfile, bzfile and socket connections.

  The default mode in \R is \code{"r"} except for socket
  connections. This differs from Svr4, where it is the equivalent of
  \code{"r+"}, known as \code{"*"}.

  On platforms where \code{vsnprintf} does not return the needed length
  of output (e.g., Windows) there is a 100,000 character output limit on
  the length of line for \code{fifo}, \code{gzfile} and \code{bzfile}
  connections: longer lines will be truncated with a warning.
}
}
\references{
  Chambers, J. M. (1998)
  \emph{Programming with Data. A Guide to the S Language.} Springer.
}

\seealso{
  \code{\link{textConnection}}, \code{\link{seek}}, \code{\link{readLines}},
  \code{\link{readBin}}, \code{\link{writeLines}}, \code{\link{writeBin}},
  \code{\link{showConnections}}, \code{\link{pushBack}}.

  \code{\link{capabilities}} to see if \code{gzfile}, \code{url},
  \code{fifo} and \code{socketConnection} are supported by this build of \R.

#ifdef windows
  To flush output to the console, see \code{\link{flush.console}}.
#endif
}

\examples{
zz <- file("ex.data", "w")  # open an output file connection
cat("TITLE extra line", "2 3 5 7", "", "11 13 17", file = zz, sep = "\n")
cat("One more line\n", file = zz)
close(zz)
readLines("ex.data")
unlink("ex.data")

zz <- gzfile("ex.gz", "w")  # compressed file
cat("TITLE extra line", "2 3 5 7", "", "11 13 17", file = zz, sep = "\n")
close(zz)
readLines(gzfile("ex.gz"))
unlink("ex.gz")

if(capabilities("bzip2")) {
  zz <- bzfile("ex.bz2", "w")  # bzip2-ed file
  cat("TITLE extra line", "2 3 5 7", "", "11 13 17", file = zz, sep = "\n")
  close(zz)
  print(readLines(bzfile("ex.bz2")))
  unlink("ex.bz2")
}

## An example of a file open for reading and writing
Tfile <- file("test1", "w+")
c(isOpen(Tfile, "r"), isOpen(Tfile, "w")) # both TRUE
cat("abc\ndef\n", file=Tfile)
readLines(Tfile)
seek(Tfile, 0, rw="r") # reset to beginning
readLines(Tfile)
cat("ghi\n", file=Tfile)
readLines(Tfile)
close(Tfile)
unlink("test1")

## We can do the same thing with an anonymous file.
Tfile <- file()
cat("abc\ndef\n", file=Tfile)
readLines(Tfile)
close(Tfile)

if(capabilities("fifo")) {
  zz <- fifo("foo", "w+")
  writeLines("abc", zz)
  print(readLines(zz))
  close(zz)
  unlink("foo")
}

\dontrun{## Unix examples of use of pipes

# read listing of current directory
readLines(pipe("ls -1"))

# remove trailing commas. Suppose
\% cat data2
450, 390, 467, 654,  30, 542, 334, 432, 421,
357, 497, 493, 550, 549, 467, 575, 578, 342,
446, 547, 534, 495, 979, 479
# Then read this by
scan(pipe("sed -e s/,$// data2"), sep=",")

# convert decimal point to comma in output
# both R strings and (probably) the shell need \ doubled
zz <- pipe(paste("sed s/\\\\\\\\./,/ >", "outfile"), "w")
cat(format(round(rnorm(100), 4)), sep = "\n", file = zz)
close(zz)
file.show("outfile", delete.file=TRUE)}

\dontrun{## example for Unix machine running a finger daemon

con <- socketConnection(port = 79, blocking = TRUE)
writeLines(paste(system("whoami", intern=TRUE), "\r", sep=""), con)
gsub(" *$", "", readLines(con))
close(con)}

\dontrun{## two R processes communicating via non-blocking sockets
# R process 1
con1 <- socketConnection(port = 6011, server=TRUE)
writeLines(LETTERS, con1)
close(con1)

# R process 2
con2 <- socketConnection(Sys.info()["nodename"], port = 6011)
# as non-blocking, may need to loop for input
readLines(con2)
while(isIncomplete(con2)) {Sys.sleep(1); readLines(con2)}
close(con2)}
}
\keyword{file}
\keyword{connection}
\eof
\name{constrOptim}
\alias{constrOptim}
\title{Linearly constrained optimisation}
\description{
Minimise a function subject to linear inequality constraints using an
adaptive barrier algorithm.  
}
\usage{
constrOptim(theta, f, grad, ui, ci, mu = 1e-04, control = list(),
            method = if(is.null(grad)) "Nelder-Mead" else "BFGS",
            outer.iterations = 100, outer.eps = 1e-05, \dots)
}
\arguments{
  \item{theta}{Starting value: must be in the feasible region.}
  \item{f}{Function to minimise.}
  \item{grad}{Gradient of \code{f}.}
  \item{ui}{Constraints (see below).}
  \item{ci}{Constraints (see below).}
  \item{mu}{(Small) tuning parameter.}
  \item{control}{Passed to \code{\link{optim}}.}
  \item{method}{Passed to \code{\link{optim}}.}
  \item{outer.iterations}{Iterations of the barrier algorithm.}
  \item{outer.eps}{Criterion for relative convergence of the barrier
    algorithm.}
  \item{\dots}{ Other arguments passed to \code{\link{optim}} }
}
\details{
  The feasible region is defined by \code{ui \%*\% theta - ci >= 0}. The
  starting value must be in the interior of the feasible region, but the
  minimum may be on the boundary.
  
  A logarithmic barrier is added to enforce the constraints and then
  \code{\link{optim}} is called. The barrier function is chosen so that
  the objective function should decrease at each outer iteration. Minima
  in the interior of the feasible region are typically found quite
  quickly, but a substantial number of outer iterations may be needed
  for a minimum on the boundary.

 The tuning parameter \code{mu} multiplies the barrier term. Its precise
  value is often relatively unimportant. As \code{mu} increases the
  augmented objective function becomes closer to the original objective
  function but also less smooth near the boundary of the feasible
  region.

  Any \code{optim} method that permits infinite values for the objective
  function may be used (currently all but "L-BFGS-B").  The gradient
  function must be supplied except with \code{method="Nelder-Mead"}.
  
  As with \code{optim}, the default is to minimise and maximisation can
  be performed by setting \code{control$fnscale} to a negative value.
  
}
\value{
  As for \code{\link{optim}}, but with two extra components:
  \code{barrier.value} giving the value of the barrier function at the
  optimum and \code{outer.iterations} gives the
  number of outer iterations (calls to \code{optim})
}

\references{
  K. Lange \emph{Numerical Analysis for Statisticians.} Springer
  2001, p185ff
}

\seealso{
  \code{\link{optim}}, especially \code{method="L-BGFS-B"} which
  does box-constrained optimisation.
}

\examples{
## from optim
fr <- function(x) {   ## Rosenbrock Banana function
    x1 <- x[1]
    x2 <- x[2]
    100 * (x2 - x1 * x1)^2 + (1 - x1)^2
}
grr <- function(x) { ## Gradient of 'fr'
    x1 <- x[1]
    x2 <- x[2]
    c(-400 * x1 * (x2 - x1 * x1) - 2 * (1 - x1),
       200 *      (x2 - x1 * x1))
}

optim(c(-1.2,1), fr, grr)
#Box-constraint, optimum on the boundary
constrOptim(c(-1.2,0.9), fr, grr, ui=rbind(c(-1,0),c(0,-1)), ci=c(-1,-1))
#  x<=0.9,  y-x>0.1
constrOptim(c(.5,0), fr, grr, ui=rbind(c(-1,0),c(1,-1)), ci=c(-0.9,0.1))


## Solves linear and quadratic programming problems
## but needs a feasible starting value
#
# from example(solve.QP) in 'quadprog'
# no derivative
fQP <- function(b) {-sum(c(0,5,0)*b)+0.5*sum(b*b)}
Amat       <- matrix(c(-4,-3,0,2,1,0,0,-2,1),3,3)
bvec       <- c(-8,2,0)
constrOptim(c(2,-1,-1), fQP, NULL, ui=t(Amat),ci=bvec)
# derivative
gQP <- function(b) {-c(0,5,0)+b}
constrOptim(c(2,-1,-1), fQP, gQP, ui=t(Amat), ci=bvec)

## Now with maximisation instead of minimisation
hQP <- function(b) {sum(c(0,5,0)*b)-0.5*sum(b*b)}
constrOptim(c(2,-1,-1), hQP, NULL, ui=t(Amat), ci=bvec,
            control=list(fnscale=-1))
}
\keyword{optimize}

\eof
\name{contour}
\alias{contour}
\alias{contour.default}
\title{Display Contours}
\description{
  Create a contour plot, or add contour lines to an existing plot.
}
\usage{
contour(x, \dots)
\method{contour}{default}(x = seq(0, 1, len = nrow(z)), y = seq(0, 1, len = ncol(z)),
        z,
        nlevels = 10, levels = pretty(zlim, nlevels), labels = NULL,
        xlim = range(x, finite = TRUE),
        ylim = range(y, finite = TRUE),
        zlim = range(z, finite = TRUE),
        labcex = 0.6, drawlabels = TRUE, method = "flattest",
	vfont = c("sans serif", "plain"),
        axes = TRUE, frame.plot = axes,
        col = par("fg"), lty = par("lty"), lwd = par("lwd"),
	add = FALSE, \dots)
}
\arguments{
  \item{x,y}{locations of grid lines at which the values in \code{z} are
    measured.  These must be in ascending order.  By default, equally
    spaced values from 0 to 1 are used.  If \code{x} is a \code{list},
    its components \code{x$x} and \code{x$y} are used for \code{x}
    and \code{y}, respectively. If the list has component \code{z} this
    is used for \code{z}.}
  \item{z}{a matrix containing the values to be plotted (\code{NA}s are
    allowed).  Note that \code{x} can be used instead of \code{z} for
    convenience.}
  \item{nlevels}{number of contour levels desired \bold{iff}
    \code{levels} is not supplied.}
  \item{levels}{numeric vector of levels at which to draw contour
    lines.}
  \item{labels}{a vector giving the labels for the contour lines.  If
    \code{NULL} then the levels are used as labels.}
  \item{labcex}{\code{cex} for contour labelling.}
  \item{drawlabels}{logical.  Contours are labelled if \code{TRUE}.}
  \item{method}{character string specifying where the labels will be
    located. Possible values are \code{"simple"}, \code{"edge"} and
    \code{"flattest"} (the default). See the Details section.}
  \item{vfont}{if a character vector of length 2 is specified, then Hershey
    vector fonts are used for the contour labels.
    The first element of the vector
    selects a typeface and the second element selects a fontindex
    (see \code{\link{text}} for more information).}
  \item{xlim, ylim, zlim}{x-, y- and z-limits for the plot.}
  \item{axes, frame.plot}{logical indicating whether axes or a box
    should be drawn, see \code{\link{plot.default}}.}
  \item{col}{color for the lines drawn.}
  \item{lty}{line type for the lines drawn.}
  \item{lwd}{line width for the lines drawn.}
  \item{add}{logical. If \code{TRUE}, add to a current plot.}
  \item{\dots}{additional graphical parameters (see \code{\link{par}})
    and the arguments to \code{\link{title}} may also be supplied.}
}
\details{
  \code{contour} is a generic function with only a default method in
  base \R.
  
  There is currently no documentation about the algorithm.
  The source code is in \file{\$R\_HOME/src/main/plot3d.c}.

  The methods for positioning the labels on contours are \code{"simple"}
  (draw at the edge of the plot, overlaying the contour line),
  \code{"edge"} (draw at the edge of the plot, embedded in the contour
  line, with no labels overlapping) and \code{"flattest"}
  (draw on the flattest section of the contour, embedded in the
  contour line, with no labels overlapping).  The second and third may
  not draw a label on every contour line.

  For information about vector fonts, see the
  help for \code{\link{text}} and \code{\link{Hershey}}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{filled.contour}} for \dQuote{color-filled} contours,
  \code{\link{image}} and the graphics demo which can be invoked as
  \code{demo(graphics)}.
}
\examples{
x <- -6:16
op <- par(mfrow = c(2, 2))
contour(outer(x, x), method = "edge", vfont = c("sans serif", "plain"))
z <- outer(x, sqrt(abs(x)), FUN = "/")
## Should not be necessary:
z[!is.finite(z)] <- NA
image(x, x, z)
contour(x, x, z, col = "pink", add = TRUE, method = "edge",
	vfont = c("sans serif", "plain"))
contour(x, x, z, ylim = c(1, 6), method = "simple", labcex = 1)
contour(x, x, z, ylim = c(-6, 6), nlev = 20, lty = 2, method = "simple")
par(op)

## Persian Rug Art:
x <- y <- seq(-4*pi, 4*pi, len = 27)
r <- sqrt(outer(x^2, y^2, "+"))
opar <- par(mfrow = c(2, 2), mar = rep(0, 4))
for(f in pi^(0:3))
  contour(cos(r^2)*exp(-r/f),
          drawlabels = FALSE, axes = FALSE, frame = TRUE)

data("volcano")
rx <- range(x <- 10*1:nrow(volcano))
ry <- range(y <- 10*1:ncol(volcano))
ry <- ry + c(-1,1) * (diff(rx) - diff(ry))/2
tcol <- terrain.colors(12)
par(opar); opar <- par(pty = "s", bg = "lightcyan")
plot(x = 0, y = 0,type = "n", xlim = rx, ylim = ry, xlab = "", ylab = "")
u <- par("usr")
rect(u[1], u[3], u[2], u[4], col = tcol[8], border = "red")
contour(x, y, volcano, col = tcol[2], lty = "solid", add = TRUE,
	vfont = c("sans serif", "plain"))
title("A Topographic Map of Maunga Whau", font = 4)
abline(h = 200*0:4, v = 200*0:4, col = "lightgray", lty = 2, lwd = 0.1)
par(opar)
}
\keyword{hplot}
\keyword{aplot}
\eof
\name{contrast}
\alias{contr.helmert}
\alias{contr.poly}
\alias{contr.sum}
\alias{contr.treatment}
\title{Contrast Matrices}
\description{
  Return a matrix of contrasts.
}
\usage{
contr.helmert(n, contrasts = TRUE)
contr.poly(n, scores = 1:n, contrasts = TRUE)
contr.sum(n, contrasts = TRUE)
contr.treatment(n, base = 1, contrasts = TRUE)
}
\arguments{
  \item{n}{a vector of levels for a factor, or the number of levels.}
  \item{contrasts}{a logical indicating whether contrasts should be
    computed.}
  \item{scores}{the set of values over which orthogonal polynomials are
    to be computed.}
  \item{base}{an integer specifying which group is considered the
    baseline group. Ignored if \code{contrasts} is \code{FALSE}.}
}
\details{
  These functions are used for creating contrast matrices for use in
  fitting analysis of variance and regression models.  The columns of
  the resulting matrices contain contrasts which can be used for coding
  a factor with \code{n} levels.  The returned value contains the
  computed contrasts.  If the argument \code{contrasts} is \code{FALSE}
  then a square indicator matrix is returned.

  \code{cont.helmert} returns Helmert contrasts, which contrast the
  second level with the first, the third with the average of the first
  two, and so on.  \code{contr.poly} returns contrasts based on
  orthogonal polynomials. \code{contr.sum} uses \dQuote{sum to zero
  contrasts}.

  \code{contr.treatment} contrasts each level with the baseline level
  (specified by \code{base}): the baseline level is omitted.  Note that
  this does not produce \dQuote{contrasts} as defined in the standard
  theory for linear models as they are not orthogonal to the constant.
}
\value{
  A matrix with \code{n} rows and \code{k} columns, with \code{k=n-1} if
  \code{contrasts} is \code{TRUE} and \code{k=n} if \code{contrasts} is
  \code{FALSE}.
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical models.}
  Chapter 2 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{contrasts}},
  \code{\link{C}},
  and
  \code{\link{aov}},
  \code{\link{glm}},
  \code{\link{lm}}.
}
\examples{
(cH <- contr.helmert(4))
apply(cH, 2,sum) # column sums are 0!
crossprod(cH) # diagonal -- columns are orthogonal
contr.helmert(4, contrasts = FALSE) # just the 4 x 4 identity matrix

(cT <- contr.treatment(5))
all(crossprod(cT) == diag(4)) # TRUE: even orthonormal

(cP <- contr.poly(3)) # Linear and Quadratic
zapsmall(crossprod(cP), dig=15) # orthonormal up to fuzz
}
\keyword{design}
\keyword{regression}
\keyword{array}
\eof
\name{contrasts}
\alias{contrasts}
\alias{contrasts<-}
\title{Get and Set Contrast Matrices}
\description{
  Set and view the contrasts associated with a factor.
}
\usage{
contrasts(x, contrasts = TRUE)
contrasts(x, how.many) <- value
}
\arguments{
  \item{x}{a factor.}
  \item{contrasts}{logical. See Details.}
  \item{how.many}{How many contrasts should be made. Defaults to one
    less than the number of levels of \code{x}.  This need not be the
    same as the number of columns of \code{ctr}.}
  \item{value}{either a matrix whose columns give coefficients for
    contrasts in the levels of \code{x}, or the (quoted) name of a
    function which computes such matrices.}
}
\details{
  If contrasts are not set for a factor the default functions from
  \code{\link{options}("contrasts")} are used.

  The argument \code{contrasts} is ignored if \code{x} has a matrix
  \code{contrasts} attribute set. Otherwise if \code{contrasts = TRUE}
  it is passed to a contrasts function such as
  \code{\link{contr.treatment}} and if \code{contrasts = FALSE}
  an identity matrix is returned.
}
% \note{
%   Prior to \R version 1.2.0, \code{contrasts(, FALSE)} called a
%   contrasts function with \code{contrasts = FALSE}.  This normally gave
%   the same result, but not for \code{\link{contr.poly}}, the default for
%   ordered factors.
% }
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical models.}
  Chapter 2 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{C}},
  \code{\link{contr.helmert}},
  \code{\link{contr.poly}},
  \code{\link{contr.sum}},
  \code{\link{contr.treatment}};
  \code{\link{glm}},
  \code{\link{aov}},
  \code{\link{lm}}.
}
\examples{
example(factor)
fff <- ff[, drop=TRUE]  # reduce to 5 levels.
contrasts(fff) # treatment contrasts by default
contrasts(C(fff, sum))
contrasts(fff, contrasts = FALSE) # the 5x5 identity matrix

contrasts(fff) <- contr.sum(5); contrasts(fff)  # set sum contrasts
contrasts(fff, 2) <- contr.sum(5); contrasts(fff)  # set 2 contrasts
# supply 2 contrasts, compute 2 more to make full set of 4.
contrasts(fff) <- contr.sum(5)[,1:2]; contrasts(fff)
}
\keyword{design}
\keyword{regression}
\eof
\name{contributors}
\alias{contributors}
\title{R Project Contributors}
\description{
  The \R Who-is-who, describing who made significant contributions to
  the development of \R.
}
\usage{
contributors()
}
\keyword{misc}
\eof
\name{getNumCConverters}
\alias{getNumCConverters}
\alias{getCConverterDescriptions}
\alias{getCConverterStatus}
\alias{setCConverterStatus}
\alias{removeCConverter}

\title{Management of .C argument conversion list}
\description{
These functions provide facilities to manage the extensible
list of converters used to translate R objects to C
pointers for use in \code{\link{.C}} calls.
The number and a description of each element in the list 
can be retrieved. One can also query and set the activity
status of individual elements, temporarily ignoring them.
And one can remove individual elements.
}
\usage{
getNumCConverters()
getCConverterDescriptions()
getCConverterStatus()
setCConverterStatus(id, status)
removeCConverter(id)
}
\arguments{
\item{id}{either a number or a string identifying the element of interest in the converter
   list. A string sis matched against the description strings for each element to identify
   the element. Integers are specified starting at 1 (rather than 0).}

\item{status}{a logical value specifying whether the element is to be considered
   active (\code{TRUE}) or not (\code{FALSE}).}
}
\details{
 The internal list of converters is potentially used when converting
individual arguments in a \code{\link{.C}} call.  If an argument has a
non-trivial class attribute, we iterate over the list of converters
looking for the first that \dQuote{matches}.  If we find a matching
converter, we have it create the C-level pointer corresponding to the
R object.  When the call to the C routine is complete, we use the same
converter for that argument to reverse the conversion and create an R
object from the current value in the C pointer. This is done
separately for all the arguments.

The functions documented here provide R user-level capabilities
for investigating and managing the list of converters.
There is currently no mechanism for adding an element to the
converter list within the R language. This must be done in
C code using the routine \code{R_addToCConverter()}.
}
\value{
\code{getNumCConverters} returns an integer giving the number
of elements in the list, both active and inactive.

\code{getCConverterDescriptions} returns a character vector containing
the description string of each element of the converter list.

\code{getCConverterStatus} returns a logical vector with a value for
each element in the converter list. Each value indicates whether that
converter is active (\code{TRUE}) or inactive (\code{FALSE}).
The names of the elements are the description strings returned
by \code{getCConverterDescriptions}.

\code{setCConverterStatus} returns the logical value indicating the
activity status of the specified element before the call to change it
took effect.  This is \code{TRUE} for active and \code{FALSE} for
inactive.

\code{removeCConverter} returns \code{TRUE} if
an element in the converter list was identified and removed.
In the case that no such element was found, an error occurs.
}
\references{\url{http://developer.R-project.org/CObjectConversion.pdf}}
\author{Duncan Temple Lang}

\seealso{\code{\link{.C}}}

\examples{
 getNumCConverters()
 getCConverterDescriptions()
 getCConverterStatus()
\dontrun{
  old <- setCConverterStatus(1,FALSE)

  setCConverterStatus(1,old)
}
\dontrun{
  removeCConverter(1)
  removeCConverter(getCConverterDescriptions()[1])
}
}
\keyword{interface}
\keyword{programming}
\eof
\name{convolve}
\alias{convolve}
\title{Fast Convolution}
\description{
  Use the Fast Fourier Transform to compute the several kinds of
  convolutions of two sequences.
}
\usage{
convolve(x, y, conj = TRUE, type = c("circular", "open", "filter"))
}
\arguments{
  \item{x,y}{numeric sequences \emph{of the same length} to be
    convolved.}
  \item{conj}{logical; if \code{TRUE}, take the complex \emph{conjugate}
    before back-transforming (default, and used for usual convolution).}
  \item{type}{character; one of \code{"circular"}, \code{"open"},
    \code{"filter"} (beginning of word is ok).  For \code{circular}, the
    two sequences are treated as \emph{circular}, i.e., periodic.

    For \code{open} and \code{filter}, the sequences are padded with
    \code{0}s (from left and right) first; \code{"filter"} returns the
    middle sub-vector of \code{"open"}, namely, the result of running a
    weighted mean of \code{x} with weights \code{y}.}
}
\details{
  The Fast Fourier Transform, \code{\link{fft}}, is used for efficiency.

  The input sequences \code{x} and  \code{y} must have the same length if
  \code{circular} is true.

  Note that the usual definition of convolution of two sequences
  \code{x} and \code{y} is given by \code{convolve(x, rev(y), type = "o")}.
}
\value{
  If \code{r <- convolve(x,y, type = "open")}
  and \code{n <- length(x)}, \code{m <- length(y)}, then
  \deqn{r_k = \sum_{i} x_{k-m+i} y_{i}}{r[k] = sum(i; x[k-m+i] * y[i])}
  where the sum is over all valid indices \eqn{i}, for \eqn{k = 1,\dots, n+m-1}

  If \code{type == "circular"}, \eqn{n = m} is required, and the above is
  true for \eqn{i , k = 1,\dots,n} when
  \eqn{x_{j} := x_{n+j}}{x[j] := x[n+j]} for \eqn{j < 1}.
}
\references{
  Brillinger, D. R. (1981)
  \emph{Time Series: Data Analysis and Theory}, Second Edition.
  San Francisco: Holden-Day.
}
\seealso{\code{\link{fft}}, \code{\link{nextn}}, and particularly
  \code{\link[ts]{filter}} (from the \pkg{ts} package) which may be
  more appropriate.
}
\examples{
x <- c(0,0,0,100,0,0,0)
y <- c(0,0,1, 2 ,1,0,0)/4
zapsmall(convolve(x,y))         #  *NOT* what you first thought.
zapsmall(convolve(x, y[3:5], type="f")) # rather
x <- rnorm(50)
y <- rnorm(50)
# Circular convolution *has* this symmetry:
all.equal(convolve(x,y, conj = FALSE),
          rev(convolve(rev(y),x)))

n <- length(x <- -20:24)
y <- (x-10)^2/1000 + rnorm(x)/8

Han <- function(y) # Hanning
       convolve(y, c(1,2,1)/4, type = "filter")

plot(x,y, main="Using  convolve(.) for Hanning filters")
lines(x[-c(1  , n)      ], Han(y), col="red")
lines(x[-c(1:2, (n-1):n)], Han(Han(y)), lwd=2, col="dark blue")
}
\keyword{math}
\keyword{dplot}
\eof
\name{coplot}
\title{Conditioning Plots}
\usage{
coplot(formula, data, given.values, panel = points, rows, columns,
       show.given = TRUE, col = par("fg"), pch = par("pch"), 
       bar.bg = c(num = gray(0.8), fac = gray(0.95)),
       xlab = c(x.name, paste("Given :", a.name)),
       ylab = c(y.name, paste("Given :", b.name)),
       subscripts = FALSE,
       axlabels = function(f) abbreviate(levels(f)),
       number = 6, overlap = 0.5, xlim, ylim, \dots) 
co.intervals(x, number = 6, overlap = 0.5)
}
\alias{coplot}
\alias{co.intervals}
\arguments{
  \item{formula}{a formula describing the form of conditioning plot.  A
    formula of the form \code{y ~ x | a} indicates that plots of
    \code{y} versus \code{x} should be produced conditional on the
    variable \code{a}.  A formula of the form \code{y ~ x| a * b}
    indicates that plots of \code{y} versus \code{x} should be produced
    conditional on the two variables \code{a} and \code{b}.

    All three or four variables may be either numeric or factors.
    When \code{x} or \code{y} are factors, the result is almost as if
    \code{as.numeric()} was applied, whereas for factor
    \code{a} or \code{b}, the conditioning (and its graphics if
    \code{show.given} is true) are adapted.
  }
  \item{data}{a data frame containing values for any variables in the
    formula.  By default the environment where \code{coplot} was called
    from is used.}
  \item{given.values}{a value or list of two values which determine how
    the conditioning on \code{a} and \code{b} is to take place.

    When there is no \code{b} (i.e., conditioning only on \code{a}),
    usually this is a matrix with two columns each row of which gives an
    interval, to be conditioned on, but is can also be a single vector
    of numbers or a set of factor levels (if the variable being
    conditioned on is a factor). In this case (no \code{b}),
    the result of \code{co.intervals} can be used directly as
    \code{given.values} argument.
  }
  \item{panel}{a \code{\link{function}(x, y, col, pch, \dots)}
      which gives the action to be carried out in
      each panel of the display.  The default is \code{points}.}
  \item{rows}{the panels of the plot are laid out in a \code{rows} by
    \code{columns} array.  \code{rows} gives the number of rows in the
    array.}
  \item{columns}{the number of columns in the panel layout array.}
  \item{show.given}{logical (possibly of length 2 for 2 conditioning
      variables): should conditioning plots be shown for the
    corresponding conditioning variables (default \code{TRUE})}.
  \item{col}{a vector of colors to be used to plot the points.  If too
    short, the values are recycled.}
  \item{pch}{a vector of plotting symbols or characters.  If too short,
    the values are recycled.}
  \item{bar.bg}{a named vector with components \code{"num"} and
    \code{"fac"} giving the background colors for the (shingle) bars,
    for \bold{num}eric and \bold{fac}tor conditioning variables respectively.}
  \item{xlab}{character; labels to use for the x axis and the
    first conditioning variable.  If only one label is given, it is used
    for the x axis and the default label is used for the conditioning
    variable.}
  \item{ylab}{character; labels to use for the y axis and any
    second conditioning variable.}
  \item{subscripts}{logical: if true the panel function is given an
    additional (third) argument \code{subscripts} giving the subscripts
    of the data passed to that panel.}
  \item{axlabels}{function for creating axis (tick) labels when x or y
      are factors.}
  \item{number}{integer; the number of conditioning intervals,
    for a and b, possibly of length 2.  It is only used if the
    corresponding conditioning variable is not a \code{\link{factor}}.}
  \item{overlap}{numeric < 1; the fraction of overlap of the
    conditioning variables, possibly of length 2 for x and y
    direction.  When overlap < 0, there will be \emph{gaps} between
    the data slices.}
  \item{xlim}{the range for the x axis.}
  \item{ylim}{the range for the y axis.}
  \item{\dots}{additional arguments to the panel function.}

  \item{x}{a numeric vector.}
}
\description{
  This function produces two variants of the \bold{co}nditioning plots
  discussed in the reference below.
}
\details{
  In the case of a single conditioning variable \code{a}, when both
  \code{rows} and \code{columns} are unspecified, a \dQuote{close to
    square} layout is chosen with \code{columns >= rows}.

  In the case of multiple \code{rows}, the \emph{order} of the panel
  plots is from the bottom and from the left (corresponding to
  increasing \code{a}, typically).

  A panel function should not attempt to start a new plot, but just plot
  within a given coordinate system: thus \code{plot} and \code{boxplot}
  are not panel functions.
}
\value{
  \code{co.intervals(., number, .)} returns a (\code{number} \eqn{\times}{x}
  2) \code{\link{matrix}}, say \code{ci},  where \code{ci[k,]} is
  the \code{\link{range}} of \code{x} values for the \code{k}-th interval.
}
\references{
  Chambers, J. M. (1992)
  \emph{Data for models.}
  Chapter 3 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.

  Cleveland, W. S. (1993) \emph{Visualizing Data.} New Jersey: Summit Press.
}
\seealso{
  \code{\link{pairs}},
  \code{\link{panel.smooth}},
  \code{\link{points}}.
}
\examples{
## Tonga Trench Earthquakes
data(quakes)
coplot(lat ~ long | depth, data = quakes)
given.depth <- co.intervals(quakes$depth, number=4, overlap=.1)
coplot(lat ~ long | depth, data = quakes, given.v=given.depth, rows=1)

## Conditioning on 2 variables:
ll.dm <- lat ~ long | depth * mag
coplot(ll.dm, data = quakes)
coplot(ll.dm, data = quakes, number=c(4,7), show.given=c(TRUE,FALSE))
coplot(ll.dm, data = quakes, number=c(3,7),
       overlap=c(-.5,.1)) # negative overlap DROPS values

data(warpbreaks)
## given two factors
Index <- seq(length=nrow(warpbreaks)) # to get nicer default labels
coplot(breaks ~ Index | wool * tension, data = warpbreaks, show.given = 0:1)
coplot(breaks ~ Index | wool * tension, data = warpbreaks,
       col = "red", bg = "pink", pch = 21, bar.bg = c(fac = "light blue"))

## Example with empty panels:
data(state)
attach(data.frame(state.x77))#> don't need 'data' arg. below
coplot(Life.Exp ~ Income | Illiteracy * state.region, number = 3,
       panel = function(x, y, ...) panel.smooth(x, y, span = .8, ...))
## y ~ factor -- not really sensical, but 'show off':
coplot(Life.Exp ~ state.region | Income * state.division,
       panel = panel.smooth)
detach() # data.frame(state.x77)
}
\keyword{hplot}
\keyword{aplot}
\eof
\name{copyright}
\title{Copyrights of Files Used to Build R}
\alias{copyright}
\alias{copyrights}
\description{
  \R is released under the \sQuote{GNU Public License}: see
  \code{\link{license}} for details.  The license describes your right
  to use \R.  Copyright is concerned with ownership of intellectual
  rights, and some of the software used has conditions that the
  copyright must be explicitly stated: see the Details section.  We
  are grateful to these people and other contributors (see
  \code{\link{contributors}}) for the ability to use their work.
}
\details{
  The file \file{\$R\_HOME/COPYRIGHTS} lists the copyrights in full
  detail.
}
\keyword{misc}
\eof
\name{cor}
\title{Correlation, Variance and Covariance (Matrices)}
\usage{
var(x, y = NULL, na.rm = FALSE, use)
cov(x, y = NULL, use = "all.obs", method = c("pearson", "kendall", "spearman"))
cor(x, y = NULL, use = "all.obs", method = c("pearson", "kendall", "spearman"))
cov2cor(V)
}
\alias{var}
\alias{cov}
\alias{cor}
\alias{cov2cor}
\description{
  \code{var}, \code{cov} and \code{cor} compute the variance of \code{x}
  and the covariance or correlation of \code{x} and \code{y} if these
  are vectors.	If \code{x} and \code{y} are matrices then the
  covariances (or correlations) between the columns of \code{x} and the
  columns of \code{y} are computed.

  \code{cov2cor} scales a covariance matrix into the corresponding
  correlation matrix \emph{efficiently}.
}
\arguments{
  \item{x}{a numeric vector, matrix or data frame.}
  \item{y}{\code{NULL} (default) or a vector, matrix or data frame with
    compatible dimensions to \code{x}.	The default is equivalent to
    \code{y = x} (but more efficient).}
  \item{na.rm}{logical. Should missing values be removed?}
  \item{use}{an optional character string giving a
    method for computing covariances in the presence
    of missing values.	This must be (an abbreviation of) one of the strings
    \code{"all.obs"}, \code{"complete.obs"} or \code{"pairwise.complete.obs"}.}
  \item{method}{a character string indicating which correlation
    coefficient (or covariance) is to be computed.  One of
    \code{"pearson"} (default), \code{"kendall"}, or \code{"spearman"},
    can be abbreviated.}
  \item{V}{symmetric numeric matrix, usually positive definite such as a
    covariance matrix.}
}
\value{For \code{r <- cor(*, use = "all.obs")}, it is now guaranteed that
  \code{all(r <= 1)}.
}
\details{
  For \code{cov} and \code{cor} one must \emph{either} give a matrix or
  data frame for \code{x} \emph{or} give both \code{x} and \code{y}.

  \code{var} is just another interface to \code{cov}, where
  \code{na.rm} is used to determine the default for \code{use} when that
  is unspecified.  If \code{na.rm} is \code{TRUE} then the complete
  observations (rows) are used (\code{use = "complete"}) to compute the
  variance.  Otherwise (\code{use = "all"}), \code{var} will give an
  error if there are missing values.

  If \code{use} is \code{"all.obs"}, then the presence
  of missing observations will produce an error.
  If \code{use} is \code{"complete.obs"} then missing values
  are handled by casewise deletion.  Finally, if \code{use} has the
  value \code{"pairwise.complete.obs"} then the correlation between
  each pair of variables is computed using all complete pairs
  of observations on those variables.
  This can result in covariance or correlation matrices which are not
  positive semidefinite.

  The denominator \eqn{n - 1} is used which gives an unbiased estimator
  of the (co)variance for i.i.d. observations.
  These functions return \code{\link{NA}} when there is only one
  observation (whereas S-plus has been returning \code{NaN}), and %from \R 1.2.3
  fail if \code{x} has length zero.

  For \code{cor()}, if \code{method} is \code{"kendall"} or
  \code{"spearman"}, Kendall's \eqn{\tau}{tau} or Spearman's
  \eqn{\rho}{rho} statistic is used to estimate a rank-based measure of
  association.  These are more robust and have be recommended if the
  data do not necessarily come from a bivariate normal distribution.\cr
  For \code{cov()}, a non-Pearson method is unusual but available for
  the sake of completeness.

  Scaling a covariance matrix into a correlation one can be achieved in
  many ways, mathematically most appealing by multiplication with a
  diagonal matrix from left and right, or more efficiently by using
  \code{\link{sweep}(.., FUN = "/")} twice.  The \code{cov2cor} function
  is even a bit more efficient, and provided mostly for didactical
  reasons.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link[ctest]{cor.test}} (package \pkg{ctest}) for confidence
  intervals (and tests).\cr
  \code{\link{cov.wt}} for \emph{weighted} covariance
  computation, \code{\link{sd}} for standard deviation (vectors).
}
\examples{
var(1:10)# 9.166667

var(1:5,1:5)# 2.5

## Two simple vectors
cor(1:10,2:11)# == 1

## Correlation Matrix of Multivariate sample:
data(longley)
(Cl <- cor(longley))
## Graphical Correlation Matrix:
symnum(Cl) # highly correlated

## Spearman's rho  and  Kendall's tau
symnum(clS <- cor(longley, method = "spearman"))
symnum(clK <- cor(longley, method = "kendall"))
## How much do they differ?
i <- lower.tri(Cl)
cor(cbind(P = Cl[i], S = clS[i], K = clK[i]))


## cov2cor() scales a covariance matrix by its diagonal
##	     to become the correlation matrix.
cov2cor # see the function definition {and learn ..}
stopifnot(all.equal(Cl, cov2cor(cov(longley))),
          all.equal(cor(longley, method="kendall"),
            cov2cor(cov(longley, method="kendall"))))

##--- Missing value treatment:
data(swiss)
C1 <- cov(swiss)
range(eigen(C1, only=TRUE)$val) # 6.19	1921
swM <- swiss
swM[1,2] <- swM[7,3] <- swM[25,5] <- NA # create 3 "missing"
try(cov(swM)) # Error: missing obs...
C2 <- cov(swM, use = "complete")
range(eigen(C2, only=TRUE)$val) # 6.46	1930
C3 <- cov(swM, use = "pairwise")
range(eigen(C3, only=TRUE)$val) # 6.19	1938

(scM <- symnum(cor(swM, method = "kendall", use = "complete")))
## Kendall's tau doesn't change much: identical symnum codings!
identical(scM, symnum(cor(swiss, method = "kendall")))

all.equal(cov2cor(cov(swM, method = "kendall", use = "pairwise")),
                  cor(swM, method = "kendall", use = "pairwise"))
}
\keyword{univar}
\keyword{multivariate}
\keyword{array}
\eof
\name{count.fields}
\title{Count the Number of Fields per Line}
\usage{
count.fields(file, sep = "", quote = "\"'", skip = 0,
             blank.lines.skip = TRUE, comment.char = "#")
}
\alias{count.fields}
\arguments{
  \item{file}{a character string naming an ASCII data file, or a
    \code{\link{connection}}, which will be opened if necessary,
    and if so closed at the end of the function call.}

  \item{sep}{the field separator character.  Values on each line of the
    file are separated by this character.  By default, arbitrary amounts
    of whitespace can separate fields.}

  \item{quote}{the set of quoting characters}

  \item{skip}{the number of lines of the data file to skip before
    beginning to read data.}

  \item{blank.lines.skip}{logical: if \code{TRUE} blank lines in the
    input are ignored.}

  \item{comment.char}{character: a character vector of length one
    containing a single character or an empty string.}
}
\description{
  \code{count.fields} counts the number of fields, as separated by
  \code{sep}, in each of the lines of \code{file} read.
}
\details{
  This used to be used by \code{\link{read.table}} and can still be
  useful in discovering problems in reading a file by that function.

  For the handling of comments, see \code{\link{scan}}.
}
\value{
  A vector with the numbers of fields found.
}
\seealso{
  \code{\link{read.table}}
}
\examples{
cat("NAME", "1:John", "2:Paul", file = "foo", sep = "\n")
count.fields("foo", sep = ":")
unlink("foo")
}
\keyword{file}
\eof
\name{cov.wt}
\alias{cov.wt}
\title{Weighted Covariance Matrices}
\usage{
cov.wt(x, wt = rep(1/nrow(x), nrow(x)), cor = FALSE, center = TRUE)
}
\description{
  Returns a list containing estimates of the weighted covariance matrix
  and the mean of the data, and optionally of the (weighted) correlation
  matrix.}
\arguments{
  \item{x}{a matrix or data frame.  As usual, rows are observations and
    columns are variables.}
  \item{wt}{a non-negative and non-zero vector of weights for each
    observation.  Its length must equal the number of rows of \code{x}.}
  \item{cor}{A logical indicating whether the estimated correlation
    weighted matrix will be returned as well.}
  \item{center}{Either a logical or a numeric vector specifying the
    centers to be used when computing covariances.  If \code{TRUE}, the
    (weighted) mean of each variable is used, if \code{FALSE}, zero is
    used.  If \code{center} is numeric, its length must equal the number
    of columns of \code{x}.}
}
\value{
  A list containing the following named components:
  \item{cov}{the estimated (weighted) covariance matrix}
  \item{center}{an estimate for the center (mean) of the data.}
  \item{n.obs}{the number of observations (rows) in \code{x}.}
  \item{wt}{the weights used in the estimation.  Only returned if given
    as an argument.}
  \item{cor}{the estimated correlation matrix.  Only returned if
    \code{cor} is \code{TRUE}.}
}
\details{
  The covariance matrix is divided by one minus the sum of squares of
  the weights, so if the weights are the default (\eqn{1/n}) the conventional
  unbiased estimate of the covariance matrix with divisor \eqn{(n - 1)}
  is obtained.  This differs from the behaviour in S-PLUS.
}
\seealso{\code{\link{cov}} and \code{\link{var}}.
}
\keyword{multivariate}
\eof
\name{crossprod}
\alias{crossprod}
\title{Matrix Crossproduct}
\description{
  Given matrices \code{x} and \code{y} as arguments,
  \code{crossprod} returns their matrix cross-product.
  This is formally equivalent to, but faster than, the
  call \code{t(x) \%*\% y}.
}
\usage{
crossprod(x, y = NULL)
}
\arguments{
  \item{x, y}{matrices: \code{y = NULL} is taken to be the
    same matrix as \code{x}.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
\code{\link{\%*\%}} and outer product \code{\link{\%o\%}}.
}
\examples{
(z <- crossprod(1:4))    # = sum(1 + 2^2 + 3^2 + 4^2)
drop(z)                  # scalar
}
\keyword{algebra}
\keyword{array}
\eof
\name{cumsum}
\alias{cumsum}
\alias{cumprod}
\alias{cummin}
\alias{cummax}
\title{Cumulative Sums, Products, and Extremes}
\description{
  Returns a vector whose elements are the cumulative sums, products,
  minima or maxima of the elements of the argument.
}
\usage{
cumsum(x)
cumprod(x)
cummax(x)
cummin(x)
}
\arguments{
  \item{x}{a numeric object.}
}
\details{
  An \code{NA} value in \code{x} causes the corresponding and following
  elements of the return value to be \code{NA}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole. (\code{cumsum} only.)
}
\examples{
cumsum(1:10)
cumprod(1:10)
cummin(c(3:1, 2:0, 4:2))
cummax(c(3:1, 2:0, 4:2))
}
\keyword{arith}
\eof
\name{curve}
\title{Draw Function Plots}
\alias{curve}
\alias{plot.function}
\usage{
curve(expr, from, to, n = 101, add = FALSE, type = "l",
      ylab = NULL, log = NULL, xlim = NULL, \dots)

\method{plot}{function}(x, from = 0, to = 1, xlim = NULL, \dots)
}
\arguments{
  \item{expr}{an expression written as a function of \code{x}, or
    alternatively the name of a function which will be plotted.}
  \item{x}{a \sQuote{vectorizing} numeric \R function.}
  \item{from,to}{the range over which the function will be plotted.}
  \item{n}{integer; the number of x values at which to evaluate.}
  \item{add}{logical; if \code{TRUE} add to already existing plot.}
  \item{xlim}{numeric of length 2; if specified, it serves as default
    for \code{c(from, to)}.}
  \item{type, ylab, log, \dots}{graphical parameters can also be
    specified as arguments.
    \code{plot.function} passes all these to \code{curve}.}
}
\description{
  Draws a curve corresponding to the given function or expression (in
  \code{x}) over the interval \code{[from,to]}.
}
\details{
  The evaluation of \code{expr} is at \code{n} points equally spaced
  over the range \code{[from, to]}, possibly adapted to log scale.  The
  points determined in this way are then joined with straight lines.
  \code{x(t)} or \code{expr} (with \code{x} inside) must return a
  numeric of the same length as the argument \code{t} or \code{x}.

  If \code{add = TRUE}, \code{c(from,to)} default to \code{xlim} which
  defaults to the current x-limits.  Further, \code{log} is taken from the
  current plot when \code{add} is true.

  This used to be a quick hack which now seems to serve a useful purpose,
  but can give bad results for functions which are not smooth.

  For \dQuote{expensive} \code{expr}essions, you should use smarter tools.
}
\seealso{
  \code{\link{splinefun}} for spline interpolation, \code{\link{lines}}.
}
\examples{
op <- par(mfrow=c(2,2))
curve(x^3-3*x, -2, 2)
curve(x^2-2, add = TRUE, col = "violet")

plot(cos, xlim = c(-pi,3*pi), n = 1001, col = "blue")

chippy <- function(x) sin(cos(x)*exp(-x/2))
curve(chippy, -8, 7, n=2001)
curve(chippy, -8, -5)

for(ll in c("","x","y","xy"))
   curve(log(1+x), 1,100, log=ll, sub=paste("log= '",ll,"'",sep=""))
par(op)
}
\keyword{hplot}
\eof
\name{cut.POSIXt}
\alias{cut.POSIXt}
\title{Convert a Date-Time Object to a Factor}
\description{
  Method for \code{\link{cut}} applied to date-time objects.
}
\usage{
\method{cut}{POSIXt}(x, breaks, labels = NULL, start.on.monday = TRUE,
    right = FALSE, \dots)
}
\arguments{
  \item{x}{an object inheriting from class \code{"POSIXt"}.}
  \item{breaks}{
    a vector of cut points \emph{or} number giving the number of
    intervals which \code{x} is to be cut into \emph{or} an
    interval specification, one of \code{"sec"}, \code{"min"},
    \code{"hour"}, \code{"day"}, \code{"DSTday"}, \code{"week"},
    \code{"month"} or \code{"year"}, optionally preceded by an integer
    and a space, or followed by \code{"s"}.
  }
  \item{labels}{
    labels for the levels of the resulting category.  By default,
    labels are constructed from the left-hand end of the intervals
    (which are include for the default value of \code{right}). If
    \code{labels = FALSE}, simple integer codes are returned instead
    of a factor.
  }
  \item{start.on.monday}{logical. If \code{breaks = "weeks"}, should the
    week start on Mondays or Sundays?}
  \item{right, \dots}{arguments to be passed to or from other methods.}
}
\value{
     A factor is returned, unless \code{labels = FALSE} which returns
     the integer level codes.
}
\seealso{
  \code{\link{seq.POSIXt}}, \code{\link{cut}}
}
\examples{
## random dates in a 10-week period
cut(ISOdate(2001, 1, 1) + 70*86400*runif(100), "weeks")
}
\keyword{manip}
\keyword{chron}
\eof
\name{cut}
\title{Convert Numeric to Factor}
\usage{
cut(x, \dots)

\method{cut}{default}(x, breaks, labels = NULL,
    include.lowest = FALSE, right = TRUE, dig.lab = 3, \dots)
}
\alias{cut}
\alias{cut.default}
\arguments{
  \item{x}{a numeric vector which is to be converted to a factor by cutting.}
  \item{breaks}{either a vector of cut points or number
    giving the number of intervals which \code{x} is to be cut into.}
  \item{labels}{labels for the levels of the resulting category.  By default,
    labels are constructed using \code{"(a,b]"} interval notation. If
    \code{labels = FALSE}, simple integer codes are returned instead of
    a factor.}.
  \item{include.lowest}{logical, indicating if an \sQuote{x[i]} equal to
    the lowest (or highest, for \code{right = FALSE}) \sQuote{breaks}
    value should be included.}
  \item{right}{logical, indicating if the intervals should be closed on
    the right (and open on the left) or vice versa.}
  \item{dig.lab}{integer which is used when labels are not given. It
    determines the number of digits used in formatting the break numbers.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\description{
  \code{cut} divides the range of \code{x} into intervals
  and codes the values in \code{x} according to which
  interval they fall.
  The leftmost interval corresponds to level one,
  the next leftmost to level two and so on.
}
\value{
  A \code{\link{factor}} is returned, unless \code{labels = FALSE} which
  results in the mere integer level codes.
}
\details{
  If a \code{labels} parameter is specified, its values are used
  to name the factor levels. If none is specified, the factor
  level labels are constructed as \code{"(b1, b2]"}, \code{"(b2, b3]"}
  etc. for \code{right=TRUE} and as \code{"[b1, b2)"}, \ldots if
  \code{right=FALSE}.
  In this case, \code{dig.lab} indicates how many digits should be used in
  formatting the numbers \code{b1}, \code{b2}, \ldots.
}
\note{
  Instead of \code{table(cut(x, br))}, \code{hist(x, br, plot = FALSE)} is
  more efficient and less memory hungry.  Instead of \code{cut(*,
    labels = FALSE)}, \code{\link{findInterval}()} is more efficient.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{split}} for splitting a variable according to a group factor;
  \code{\link{factor}}, \code{\link{tabulate}}, \code{\link{table}},
  \code{\link{findInterval}()}.
}
\examples{
Z <- rnorm(10000)
table(cut(Z, br = -6:6))
sum(table(cut(Z, br = -6:6, labels=FALSE)))
sum(   hist  (Z, br = -6:6, plot=FALSE)$counts)

cut(rep(1,5),4)#-- dummy
tx0 <- c(9, 4, 6, 5, 3, 10, 5, 3, 5)
x <- rep(0:8, tx0)
stopifnot(table(x) == tx0)

table( cut(x, b = 8))
table( cut(x, br = 3*(-2:5)))
table( cut(x, br = 3*(-2:5), right = FALSE))

##--- some values OUTSIDE the breaks :
table(cx  <- cut(x, br = 2*(0:4)))
table(cxl <- cut(x, br = 2*(0:4), right = FALSE))
which(is.na(cx));  x[is.na(cx)]  #-- the first 9  values  0
which(is.na(cxl)); x[is.na(cxl)] #-- the last  5  values  8


## Label construction:
y <- rnorm(100)
table(cut(y, breaks = pi/3*(-3:3)))
table(cut(y, breaks = pi/3*(-3:3), dig.lab=4))

table(cut(y, breaks =  1*(-3:3), dig.lab=4))# extra digits don't "harm" here
table(cut(y, breaks =  1*(-3:3), right = FALSE))#- the same, since no exact INT!
}
\keyword{category}
\eof
\name{data}
\alias{data}
\alias{print.packageIQR}
\title{Data Sets}
\description{
  Loads specified data sets, or list the available data sets.
}
\usage{
data(\dots, list = character(0), package = .packages(),
     lib.loc = NULL, verbose = getOption("verbose"),
     envir = .GlobalEnv)
}
\arguments{
  \item{\dots}{a sequence of names or literal character strings.}
  \item{list}{a character vector.}
  \item{package}{a name or character vector giving the packages to look
    into for data sets.  By default, all packages in the search path are
    used, then the \file{data} directory (if present) of the current
    working directory.}
  \item{lib.loc}{a character vector of directory names of \R libraries,
    or \code{NULL}.  The default value of \code{NULL} corresponds to all
    libraries currently known.  If the default is used, the loaded
    packages are searched before the libraries.}
  \item{verbose}{a logical.  If \code{TRUE}, additional diagnostics are
    printed.}
  \item{envir}{the \link{environment} where the data should be loaded.}
}
\value{
  a character vector of all data sets specified, or information about
  all available data sets in an object of class \code{"packageIQR"} if
  none were specified.
}
\details{
  Currently, four formats of data files are supported:

  \enumerate{
    \item files ending \file{.R} or \file{.r} are
    \code{\link{source}()}d in, with the \R working directory changed
    temporarily to the directory containing the respective file.

    \item files ending \file{.RData} or \file{.rda} are
    \code{\link{load}()}ed.

    \item files ending \file{.tab}, \file{.txt} or \file{.TXT} are read
    using \code{\link{read.table}(\dots, header = TRUE)}, and hence
    result in a data frame.

    \item files ending \file{.csv} or \file{.CSV} are read using
    \code{\link{read.table}(\dots, header = TRUE, sep = ";")},
    and also result in a data frame.
  }
  If more than one matching file name is found, the first on this list
  is used.
  
  The data sets to be loaded can be specified as a sequence of names or
  character strings, or as the character vector \code{list}, or as both.

  For each given data set, the first two types (\file{.R} or \file{.r},
  and \file{.RData} or \file{.rda} files) can create several variables
  in the load environment, which might all be named differently from the
  data set.  The second two (\file{.tab}, \file{.txt}, or \file{.TXT},
  and \file{.csv} or \file{.CSV} files) will always result in the
  creation of a single variable with the same name as the data set. 

  If no data sets are specified, \code{data} lists the available data
  sets.  It looks for a new-style data index in the \file{Meta} or, if
  this is not found, an old-style \file{00Index} file in the \file{data}
  directory of each specified package, and uses these files to prepare a
  listing.  If there is a \file{data} area but no index, available data
  files for loading are computed and included in the listing, and a
  warning is given: such packages are incomplete.  The information about
  available data sets is returned in an object of class
  \code{"packageIQR"}.  The structure of this class is experimental.  In
  earlier versions of R, an empty character vector was returned along
  with listing available data sets.

  If \code{lib.loc} is not specified, the data sets are searched for
  amongst those packages already loaded, followed by the \file{data}
  directory (if any) of the current working directory and then packages
  in the specified libraries.  If \code{lib.loc} \emph{is} specified,
  packages are searched for in the specified libraries, even if they are
  already loaded from another library.

  To just look in the \file{data} directory of the current working
  directory, set \code{package = NULL}.
}
\note{
  The data files can be many small files.  On some file systems it is
  desirable to save space, and the files in the \file{data} directory of
  an installed package can be zipped up as a zip archive
  \file{Rdata.zip}.  You will need to provide a single-column file
  \file{filelist} of file names in that directory.

  One can take advantage of the search order and the fact that a
  \file{.R} file will change directory.  If raw data are stored in
  \file{mydata.txt} then one can set up \file{mydata.R} to read
  \file{mydata.txt} and pre-process it, e.g., using \code{transform}.
  For instance one can convert numeric vectors to factors with the
  appropriate labels.  Thus, the \file{.R} file can effectively contain
  a metadata specification for the plaintext formats.
}
\seealso{
  \code{\link{help}} for obtaining documentation on data sets,
  \code{\link{save}} for \emph{creating} the second (\file{.rda}) kind
  of data, typically the most efficient one.
}
\examples{
data()                      # list all available data sets
data(package = base)        # list the data sets in the base package
data(USArrests, "VADeaths") # load the data sets 'USArrests' and 'VADeaths'
help(USArrests)             # give information on data set 'USArrests'
}
\keyword{documentation}
\keyword{datasets}
\eof
\name{data.class}
\alias{data.class}
\title{Object Classes}
\description{
  Determine the class of an arbitrary \R object.
}
\usage{
data.class(x)
}
\arguments{
  \item{x}{an \R object.}
}
\value{
  character string giving the \dQuote{class} of \code{x}.

  The \dQuote{class} is the (first element) of the
  \code{\link[base]{class}} attribute if this is non-\code{NULL}, or
  inferred from the object's \code{dim} attribute if this is
  non-\code{NULL}, or \code{mode(x)}.

  Simply speaking, \code{data.class(x)} returns what is typically useful
  for method dispatching.  (Or, what the basic creator functions already
  and maybe eventually all will attach as a class attribute.)
}
\note{
  For compatibility reasons, there is one exception to the rule above:
  When \code{x} is \code{\link{integer}}, the result of
  \code{data.class(x)} is \code{"numeric"} even when \code{x} is classed.
}
\seealso{
  \code{\link[base]{class}}
}
\examples{
x <- LETTERS
data.class(factor(x))                 # has a class attribute
data.class(matrix(x, nc = 13))        # has a dim attribute
data.class(list(x))                   # the same as mode(x)
data.class(x)                         # the same as mode(x)

stopifnot(data.class(1:2) == "numeric")# compatibility "rule"
}
\keyword{classes}
\keyword{methods}
\eof
\name{data.frame}
\title{Data Frames}
\alias{data.frame}
\description{
  This function creates data frames, tightly coupled
  collections of variables which share many of the properties of
  matrices and of lists, used as the fundamental data structure by most
  of \R's modeling software.
}
\usage{
data.frame(\dots, row.names = NULL, check.rows = FALSE, check.names = TRUE)
}
\arguments{
  \item{\dots}{these arguments are of either the form \code{value} or
    \code{tag=value}.  Component names are created based on the tag (if
    present) or the deparsed argument itself.}
  \item{row.names}{\code{NULL} or an integer or character string specifying
    a column to be used as row names, or a character vector giving the row
    names for the data frame.}
  \item{check.rows}{if \code{TRUE} then the rows are checked for
    consistency of length and names.}
  \item{check.names}{logical.  If \code{TRUE} then the names of the
    variables in the data frame are checked to ensure that they are
    syntactically valid variable names.  If necessary they are adjusted
    (by \code{\link{make.names}}) so that they are.}
}
\value{
  A data frame, a matrix-like stucture whose columns may be of
  differing types (numeric, logical, factor and character and so on).
}
\details{
  A data frame is a list of variables of the same length with unique row
  names, given class \code{"data.frame"}.

  \code{data.frame} converts each of its arguments to a data frame by
  calling \code{\link{as.data.frame}(optional=TRUE)}.  As that is a
  generic function, methods can be written to change the behaviour of
  arguments according to their classes: \R comes with many such methods.
  Character variables passed to \code{data.frame} are converted to
  factor columns unless protected by \code{\link{I}}.
  If a list or data frame or matrix is passed to \code{data.frame}
  it is as if each column had been passed as a separate argument.

  Objects passed to \code{data.frame} should have the same number of
  rows, but atomic vectors, factors and character vectors protected by
  \code{\link{I}} will be recycled a whole number of times if necessary.

  If row names are not supplied in the call to \code{data.frame}, the
  row names are taken from the first component that has suitable names,
  for example a named vector or a matrix with rownames or a data frame.
  (If that component is subsequently recycled the names are discarded,
  with a warning.)  If \code{row.names} was supplied as \code{NULL} or no
  suitable component was found the row names are the integer sequence
  starting at one.

  If row names are supplied of length one and the data frame has a
  single row, the \code{row.names} is taken to specify the row names and
  not a column (by name or number).
}
\note{
  In versions of \R prior to 1.4.0 logical columns were converted to
  factors (as in S3 but not S4).
}
\references{
  Chambers, J. M. (1992)
  \emph{Data for models.}
  Chapter 3 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{I}},
  \code{\link{plot.data.frame}},
  \code{\link{print.data.frame}},
  \code{\link{row.names}},
  \code{\link{[.data.frame}} for subsetting methods,
  \code{\link{Math.data.frame}} etc, about
  \emph{Group} methods for \code{data.frame}s;
  \code{\link{read.table}},
  \code{\link{make.names}}.
}
\examples{
L3 <- LETTERS[1:3]
str(d <- data.frame(cbind(x=1, y=1:10), fac=sample(L3, 10, repl=TRUE)))

## The same with automatic column names:
str(     data.frame(cbind(  1,   1:10),     sample(L3, 10, repl=TRUE)))
is.data.frame(d)

## do not convert to factor, using I() :
str(cbind(d, char = I(letters[1:10])), vec.len = 10)

stopifnot(1:10 == row.names(d))# {coercion}

(d0  <- d[, FALSE]) # NULL data frame with 10 rows
(d.0 <- d[FALSE, ]) # <0 rows> data frame  (3 cols)
(d00 <- d0[FALSE,])  # NULL data frame with 0 rows
}
\keyword{classes}
\keyword{methods}
\eof
\name{data.matrix}
\alias{data.matrix}
\title{Data Frame to Numeric Matrix}
\description{
  Return the matrix obtained by converting all the variables in a data
  frame to numeric mode and then binding them together as the columns of
  a matrix.  Factors and ordered factors are replaced by their internal
  codes.
}
\usage{
data.matrix(frame)
}
\arguments{
  \item{frame}{a data frame whose components are logical vectors,
    factors or numeric vectors.}
}
\seealso{
  \code{\link{as.matrix}},
  \code{\link{data.frame}},
  \code{\link{matrix}}.
}
\references{
  Chambers, J. M. (1992)
  \emph{Data for models.}
  Chapter 3 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\keyword{array}
\eof
\name{dataentry}
\title{Spreadsheet Interface for Entering Data}
\usage{
data.entry(\dots, Modes = NULL, Names = NULL)
dataentry(data, modes)
de(\dots, Modes = list(), Names = NULL)
}
\alias{data.entry}
\alias{dataentry}
\alias{de}
\alias{de.ncols}
\alias{de.restore}
\alias{de.setup}
\description{
  A spreadsheet-like editor for entering or editing data.
}
\arguments{
  \item{\dots}{A list of variables: currently these should be numeric or
    character vectors or list containing such vectors.}
  \item{Modes}{The modes to be used for the variables.}
  \item{Names}{The names to be used for the variables.}
  \item{data}{A list of numeric and/or character vectors.}
  \item{modes}{A list of length up to that of \code{data} giving the
    modes of (some of) the variables. \code{list()} is allowed.}
}
\details{
  The data entry editor is only available on some platforms and GUIs.
  Where available it provides a means to visually edit a matrix or
  a collection of variables (including a data frame) as described in the
  \dQuote{Notes} section.
  
  \code{data.entry} has side
  effects, any changes made in the spreadsheet are reflected in the
  variables.  The functions \code{de}, \code{de.ncols}, \code{de.setup}
  and \code{de.restore} are designed to help achieve these side effects.
  If the user passes in a matrix, \code{X} say, then the matrix is
  broken into columns before \code{dataentry} is called. Then on return
  the columns are collected and glued back together and the result
  assigned to the variable \code{X}.  If you don't want this behaviour
  use dataentry directly.

  The primitive function is \code{dataentry}. It takes a list of
  vectors of possibly different lengths and modes (the second argument)
  and opens a spreadsheet with these variables being the columns.
  The columns of the dataentry window are returned as vectors in a
  list when the spreadsheet is closed.

  \code{de.ncols} counts the number of columns which are supplied as arguments
  to \code{data.entry}. It attempts to count columns in lists, matrices
  and vectors.  \code{de.setup} sets things up so that on return the
  columns can be regrouped and reassigned to the correct name. This
  is handled by \code{de.restore}.
}
\value{
  \code{de} and \code{dataentry} return the edited value of their
  arguments. \code{data.entry} invisibly returns a vector of variable
  names but its main value is its side effect of assigning new version
  of those variables in the user's workspace.
}
\note{
  The details of interface to the data grid may differ by platform and
  GUI.  The following description applies to
#ifdef unix
  the X11-based implementation under Unix.
#endif
#ifdef windows
  the GraphApp-based implementation under Windows.
#endif

  You can navigate around the grid using the cursor keys or by clicking
  with the (left) mouse button on any cell.  The active cell is
  highlighted by thickening the surrounding rectangle.  Moving to the
  right or down will scroll the grid as needed: there is no constraint
  to the rows or columns currently in use.

  The are alternative ways to navigate using the keys.  Return and
  (keypad) Enter and LineFeed all move down. Tab moves right and
  Shift-Tab move left.  Home moves to the top left.

  PageDown or Control-F moves down a page, and PageUp or
  Control-B up by a page.  End will show the last used column and the
  last few rows used (in any column).

  Using any other key starts an editing process on the currently
  selected cell: moving away from that cell enters the edited value
  whereas Esc cancels the edit and restores the previous value.  When
  the editing process starts the cell is cleared.
#ifdef windows
  The cursor changes to an I-beam to indicate that the cell is in enter mode.
#endif
  In numerical columns
  (the default) only letters making up a valid number (including
  \code{-.eE}) are accepted, and entering an invalid edited value (such
  as blank) enters \code{NA} in that cell.  The last entered value can
  be deleted using the  BackSpace or Del(ete) key.  Only a limited
  number of characters (currently 29) can be entered in a cell, and if
  necessary only the start or end of the string will be displayed, with the
  omissions indicated by \code{>} or \code{<}.  (The start is shown
  except when editing.)

#ifdef windows
  Double-clicking on a cell selects the cell and makes it into an
  editable field (a cursor will appear at the end of the text and it
  will change to the text highlight colour).  The edited text is
  entered by selecting another cell, for example by hitting Return.
  There is no way to cancel the edits.  The field will be expanded to
  the right if necessary to accommodate existing long strings, so it is
  preferable not to edit in the right-most displayed column.  (The
  editable field is itself scrollable.)
#endif

  Entering a value in a cell further down a column than the last used
  cell extends the variable and fills the gap (if any) by \code{NA}s (not
  shown on screen).

  The column names can only be selected by clicking in them.  This gives
  a popup menu to select the column type (currently Real (numeric) or
  Character) or to change the name.  Changing the type converts the
  current contents of the column (and converting from Character to Real
  may generate \code{NA}s.)
#ifdef unix
  If changing the name is selected the
  header cell becomes editable (and is cleared).  As with all cells, the
  value is entered by moving away from the cell by clicking elsewhere or
  by any of the keys for moving down (only).
#endif
#ifdef windows
  Enter the changes made in the popup window by clicking on its close box.
#endif

  New columns are created by entering values in them (and not by just
  assigning a new name).  The mode of the column is auto-detected from
  the first value entered: if this is a valid number it gives a numeric
  column.  Unused columns are ignored, so
  adding data in \code{var5} to a three-column grid adds one extra
  variable, not two.

#ifdef windows
  There is a popup-menu accessed by right-clicking anywhere in the window
  that refers to the currently selected cell. This can copy the value to
  or paste from the clipboard, or paste in common values in that column.
  Copying and pasting can also be accessed by the usual keyboard shortcuts
  Control-C and Control-V.

  Columns can be resized by selecting and dragging a line (the cursor
  will change) within limits: columns must be between 4 and 50 chars wide.
  The Autosize item on the popup menu will resize the currently selected
  column.
#endif
#ifdef unix
  The \code{Copy} button copies the currently selected cell:
  \code{paste} copies the last copied value to the current cell, and
  right-clicking selects a cell \emph{and} copies in the value.
  Initially the value is blank, and attempts to paste a blank value will
  have no effect.
#endif
  
  Control-L will refresh the display, recalculating field widths to fit
  the current entries.

  In the default mode the column widths are chosen to fit the contents
  of each column, with a default of 10 characters for empty columns.
  you can specify fixed column widths by setting option
  \code{de.cellwidth} to the required fixed width (in characters).
  (set it to zero to return to variable widths).  The displayed
  width of any field is limited to
#ifdef unix
  600 pixels (and by the window width).
#endif
#ifdef windows
  50 characters (and by the window width).
#endif
}
\seealso{
  \code{\link{vi}}, \code{\link{edit}}: \code{edit} uses
  \code{dataentry} to edit data frames.
}
\examples{
# call data entry with variables x and y
\dontrun{data.entry(x,y)}
}
\keyword{utilities}
\keyword{file}
\eof
\name{dataframeHelpers}
\title{Data Frame Auxiliary Functions}
\alias{xpdrows.data.frame}
\description{
  Auxiliary functions for use with data frames.
}
\usage{
xpdrows.data.frame(x, old.rows, new.rows)
}
\arguments{
  \item{x}{object of class \code{data.frame}.}
  \item{old.rows, new.rows}{row names for old and new rows.}
}
\details{
  \code{xpdrows.data.frame} is an auxiliary function which expands the
  rows of a data frame.  It is used by the data frame methods of
  \code{[<-} and \code{[[<-} (which perform subscripted assignments on a
  data frame), and not intended to be called directly.
}
\seealso{
  \code{\link{[.data.frame}}
}
\keyword{internal}
\eof
\name{date}
\alias{date}
\title{System Date and Time}
\description{
  Returns a character string of the current system date and time.
}
\usage{date()}
\value{
  The string has the form \code{"Fri Aug 20 11:11:00 1999"}, i.e.,
  length 24, since it relies on POSIX' \code{ctime} ensuring the above
  fixed format.  Timezone and Daylight Saving Time are taken account of,
  but \emph{not} indicated in the result.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
(d <- date())
nchar(d) == 24
}
\keyword{utilities}
\eof
\name{dcf}
\alias{read.dcf}
\alias{write.dcf}
\title{Read and Write Data in DCF Format}
\description{
  Reads or writes an \R object from/to a file in Debian Control File format.
}
\usage{
read.dcf(file, fields=NULL)
write.dcf(x, file = "", append = FALSE,
          indent = 0.1 * getOption("width"),
          width = 0.9 * getOption("width"))
}
\arguments{
  \item{file}{either a character string naming a file or a connection.
    \code{""} indicates output to the console.}
  \item{fields}{Fields to read from the DCF file. Default is to read all
    fields.}
  \item{x}{the object to be written, typically a data frame.  If not, it
    is attempted to coerce \code{x} to a data frame.}
  \item{append}{logical.  If \code{TRUE}, the output is appended to the
    file.  If \code{FALSE}, any existing file of the name is destroyed.}
  \item{indent}{a positive integer specifying the indentation for
    continuation lines in output entries.}
  \item{width}{a positive integer giving the target column for wrapping
    lines in the output.}
}
\details{
  DCF is a simple format for storing databases in plain text files that
  can easily be directly read and written by humans. DCF is used in
  various places to store R system information, like descriptions and
  contents of packages.

  The DCF rules as implemented in R are:
  \enumerate{
    \item A database consists of one or more records, each with one or
    more named fields. Not every record must contain each field, a
    field may appear only once in a record.
    \item Regular lines start with a non-whitespace character.
    \item Regular lines are of form \code{tag:value}, i.e.,
    have a name tag and a value for the field, seperated
    by \code{:} (only the first \code{:} counts). The value can be
    empty (=whitespace only).
    \item Lines starting with whitespace are continuation lines (to the
    preceding field) if at least one character
    in the line is non-whitespace.
    \item Records are seperated by one or more empty (=whitespace only)
    lines.
  }

  \code{read.dcf} returns a character matrix with one line per record
  and one column per field. Leading and trailing whitespace of field
  values is ignored. If a tag name is specified, but the corresponding
  value is empty, then an empty string of length 0 is returned. If the
  tag name of a fields is never used in a record, then \code{NA} is
  returned.
}    
\seealso{
  \code{\link{write.table}}.
}
\examples{
## Create a reduced version of the 'CONTENTS' file in package 'eda'
x <- read.dcf(file = system.file("CONTENTS", package = "eda"),
               fields = c("Entry", "Description"))
write.dcf(x)
}
\keyword{print}
\keyword{file}
\eof
\name{debug}
\title{Debug a function}
\usage{
debug(fun)
undebug(fun)
}
\alias{debug}
\alias{undebug}
\arguments{
\item{fun}{any interpreted \R function.}
}
\description{
  Set or unset the debugging flag on a function.
}
\details{
  When a function flagged for debugging is entered, normal execution
  is suspended and the body of function is executed one statement at a time.
  A new browser context is initiated for each step (and the previous one
  destroyed).
  Currently you can only debug functions that have bodies enclosed in braces.
  This is a bug and will be fixed soon.
% -when was this "soon" written? [MM. 1998.9.4]
  You take the next step by typing carriage return, \code{n} or \code{next}.
  You can see the values of variables by typing their names.
  Typing \code{c} or \code{cont} causes the debugger to continue to the
  end of the function.
  You can \code{debug} new functions before you step in to them from inside
  the debugger.
  Typing \code{Q} quits the current execution and returns you to the
  top--level prompt.
  Typing \code{where} causes the debugger to print out the current
  stack trace (all functions that are active).
  If you have variables with names that are identical to the controls
  (eg. \code{c} or \code{n} ) then you need to use \code{print(c)} and
  \code{print(n)} to evaluate them.
}
\seealso{
  \code{\link{browser}}, \code{\link{traceback}} to see the stack after
  an \code{Error: \dots} message; \code{\link{recover}} for another
  debugging approach.
}
\keyword{programming}
\keyword{environment}
\eof
\name{debugger}
\alias{debugger}
\alias{dump.frames}
\title{Post-Mortem Debugging}
\description{
  Functions to dump the evaluation environments (frames) and to examine
  dumped frames.
}
\usage{
dump.frames(dumpto = "last.dump", to.file = FALSE)
debugger(dump = last.dump)
}
\arguments{
  \item{dumpto}{a character string. The name of the object or file to
    dump to.}
  \item{to.file}{logical. Should the dump be to an \R object or to a
    file?}
  \item{dump}{An \R dump object created by \code{dump.frames}.}
}
\details{
  To use post-mortem debugging, set the option \code{error} to be a call
  to \code{dump.frames}.  By default this dumps to an \R object
  \code{"last.dump"} in the workspace, but it can be set to dump to a
  file (as dump of the object produced by a call to \code{\link{save}}).
  The dumped object contain the call stack, the active environments and
  the last error message as returned by \code{\link{geterrmessage}}.

  When dumping to file, \code{dumpto} gives the name of the dumped
  object and the file name has \code{.rda} appended.

  A dump object of class \code{"dump.frames"} can be examined
  by calling \code{debugger}. This will give the error message and a
  list of environments from which to select repeatedly. When an
  environment is selected, it is copied and the \code{browser} called
  from within the copy.

  If \code{dump.frames} is installed as the error handler, execution
  will continue even in non-interactive sessions. See the examples for
  how to dump and then quit.
}
\value{
  None.
}
\note{
  Functions such as \code{\link{sys.parent}} and
  \code{\link{environment}} applied to closures will not work correctly
  inside \code{debugger}.

  Of course post-mortem debugging will not work if \R is too damaged to
  produce and save the dump, for example if it has run out of workspace.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{options}} for setting \code{error} options;
  \code{\link{recover}} is an interactive debugger working similarly to
  \code{debugger} but directly after the error occurs.
}
\examples{
\dontrun{
options(error=quote(dump.frames("testdump", TRUE)))

f <- function() {
    g <- function() stop("test dump.frames")
    g()
}
f()   # will generate a dump on file "testdump.rda"
options(error=NULL)

## possibly in another R session
load("testdump.rda")
debugger(testdump)
Available environments had calls:
1: f()
2: g()
3: stop("test dump.frames")

Enter an environment number, or 0 to exit
Selection: 1
Browsing in the environment with call:
f()
Called from: debugger.look(ind)
Browse[1]> ls()
[1] "g"
Browse[1]> g
function() stop("test dump.frames")
<environment: 759818>
Browse[1]> 
Available environments had calls:
1: f()
2: g()
3: stop("test dump.frames")

Enter an environment number, or 0 to exit
Selection: 0

## A possible setting for non-interactive sessions
options(error=quote({dump.frames(to.file=TRUE); q()}))
}}
\keyword{utilities}
\keyword{error}
\eof
\name{delay}
\title{Delay Evaluation}
\usage{
delay(x, env=.GlobalEnv)
}
\alias{delay}
\arguments{
\item{x}{an expression.}
\item{env}{an evaluation environment}
}
\description{
  \code{delay} creates a \emph{promise} to evaluate the given
  expression in the specified environment if its value is requested.
  This provides direct access to \emph{lazy evaluation} mechanism
  used by \R for the evaluation of (interpreted) functions.
}
\details{
  This is an experimental feature and its addition is purely
  for evaluation purposes.
}
\value{
  A \emph{promise} to evaluate the expression.
  The value which is returned by \code{delay} can be assigned
  without forcing its evaluation, but any further accesses
  will cause evaluation.
}
\examples{
x <- delay({
    for(i in 1:7)
        cat("yippee!\n")
    10
})

x^2#- yippee
x^2#- simple number
}
\keyword{programming}
\keyword{data}
\eof
\name{delete.response}
\title{Modify Terms Objects}
\usage{
delete.response(termobj)
reformulate(termlabels, response = NULL)
drop.terms(termobj, dropx = NULL, keep.response = FALSE)
}
\alias{reformulate}
\alias{drop.terms}
\alias{delete.response}
\alias{[.terms}
\arguments{
  \item{termobj}{A \code{terms} object}
  \item{termlabels}{character vector giving the right-hand side of a
    model formula.}
  \item{response}{character string, symbol or call giving the left-hand side of
    a model formula.}
  \item{dropx}{vector of positions of variables to drop from the
    right-hand side of the model.}
  \item{keep.response}{Keep the response in the resulting object?}
}
\description{
  \code{delete.response} returns a \code{terms} object for the same
  model but with no response variable.

  \code{drop.terms} removes variables from the right-hand side of the
  model. There is also a \code{"[.terms"} method to perform the same
  function (with \code{keep.response=TRUE}).

  \code{reformulate} creates a formula from a character vector.
}
\value{
  \code{delete.response} and \code{drop.terms} return a \code{terms}
  object.

  \code{reformulate} returns a \code{formula}.
}
\seealso{\code{\link{terms}}}

\examples{
ff <- y ~ z + x + w
tt <- terms(ff)
tt
delete.response(tt)
drop.terms(tt, 2:3, keep.response = TRUE)
tt[-1]
tt[2:3]
reformulate(attr(tt, "term.labels"))

## keep LHS :
reformulate("x*w", ff[[2]])
fS <- surv(ft, case) ~ a + b
reformulate(c("a", "b*f"), fS[[2]])

stopifnot(identical(      ~ var, reformulate("var")),
          identical(~ a + b + c, reformulate(letters[1:3])),
          identical(  y ~ a + b, reformulate(letters[1:2], "y"))
         )
}
\keyword{programming}
\eof
\name{demo}
\alias{demo}
\title{Demonstrations of R Functionality}
\description{
  \code{demo} is a user-friendly interface to running some demonstration
  \R scripts.  \code{demo()} gives the list of available topics.
}
\usage{
demo(topic, device = getOption("device"),
     package = .packages(), lib.loc = NULL,
     character.only = FALSE, verbose = getOption("verbose"))
}
\arguments{
  \item{topic}{the topic which should be demonstrated, given as a
    \link{name} or literal character string, or a character string,
    depending on whether \code{character.only} is \code{FALSE} (default)
    or \code{TRUE}.  If omitted, the list of available topics is
    displayed.}
  \item{device}{the graphics device to be used.}
  \item{package}{a character vector giving the packages to look into for
    demos.  By default, all packages in the search path are used.}
  \item{lib.loc}{a character vector of directory names of \R libraries,
    or \code{NULL}.  The default value of \code{NULL} corresponds to all
    libraries currently known.  If the default is used, the loaded
    packages are searched before the libraries.}
  \item{character.only}{logical; if \code{TRUE}, use \code{topic} as
    character string.}
  \item{verbose}{a logical.  If \code{TRUE}, additional diagnostics are
    printed.}
}
\details{
  If no topics are given, \code{demo} lists the available demos.  The
  corresponding information is returned in an object of class
  \code{"packageIQR"}.  The structure of this class is experimental.  In
  earlier versions of R, an empty character vector was returned along
  with listing available demos.
}
\seealso{\code{\link{source}} which is called by \code{demo}.}
\examples{
demo() # for attached packages

## All available demos:
demo(package = .packages(all.available = TRUE))

demo(lm.glm)
\dontrun{
 ch <- "scoping"
 demo(ch, character = TRUE)
}}
\keyword{documentation}
\keyword{utilities}
\eof
\name{density}
\alias{density}
\alias{print.density}
\title{Kernel Density Estimation}
\usage{
density(x, bw = "nrd0", adjust = 1,
        kernel = c("gaussian", "epanechnikov", "rectangular", "triangular",
                   "biweight", "cosine", "optcosine"),
        window = kernel, width,
        give.Rkern = FALSE,
        n = 512, from, to, cut = 3, na.rm = FALSE)
}
\arguments{
  \item{x}{the data from which the estimate is to be computed.}

  \item{bw}{the smoothing bandwidth to be used.  The kernels are scaled
    such that this is the standard deviation of the smoothing kernel.
    (Note this differs from the reference books cited below, and from S-PLUS.)

    \code{bw} can also be a character string giving a rule to choose the
    bandwidth.  See \code{\link{bw.nrd}}.
  
    The specified (or computed) value of \code{bw} is multiplied by
    \code{adjust}.
  }
  \item{adjust}{the bandwidth used is actually \code{adjust*bw}.
    This makes it easy to specify values like \dQuote{half the default}
    bandwidth.}

  \item{kernel, window}{a character string giving the smoothing kernel
    to be used. This must be one of \code{"gaussian"},
    \code{"rectangular"}, \code{"triangular"}, \code{"epanechnikov"},
    \code{"biweight"}, \code{"cosine"} or \code{"optcosine"}, with default
    \code{"gaussian"}, and may be abbreviated to a unique prefix (single
    letter).
    
    \code{"cosine"} is smoother than \code{"optcosine"}, which is the
    usual \dQuote{cosine} kernel in the literature and almost MSE-efficient.
    However, \code{"cosine"} is the version used by S.
  }
  
  \item{width}{this exists for compatibility with S; if given, and
    \code{bw} is not, will set \code{bw} to \code{width} if this is a
    character string, or to a kernel-dependent multiple of \code{width}
    if this is numeric.}

  \item{give.Rkern}{logical; if true, \emph{no} density is estimated, and
    the \dQuote{canonical bandwidth} of the chosen \code{kernel} is returned
    instead.}

  \item{n}{the number of equally spaced points at which the density
    is to be estimated.  When \code{n > 512}, it is rounded up to the next
    power of 2 for efficiency reasons (\code{\link{fft}}).}

  \item{from,to}{the left and right-most points of the grid at which the
    density is to be estimated.}

  \item{cut}{by default, the values of \code{left} and \code{right} are
    \code{cut} bandwidths beyond the extremes of the data. This allows the
    estimated density to drop to approximately zero at the extremes.}

  \item{na.rm}{logical; if \code{TRUE}, missing values are removed
    from \code{x}. If \code{FALSE} any missing values cause an error.}
}
\description{
  The function \code{density} computes kernel density estimates
  with the given kernel and bandwidth.
}
\details{
  The algorithm used in \code{density} disperses the mass of the
  empirical distribution function over a regular grid of at least 512
  points and then uses the fast Fourier transform to convolve this
  approximation with a discretized version of the kernel and then uses
  linear approximation to evaluate the density at the specified points.

  The statistical properties of a kernel are determined by
  \eqn{\sigma^2_K = \int t^2 K(t) dt}{sig^2 (K) = int(t^2 K(t) dt)}
  which is always \eqn{= 1} for our kernels (and hence the bandwidth
  \code{bw} is the standard deviation of the kernel) and
  \eqn{R(K) = \int K^2(t) dt}{R(K) = int(K^2(t) dt)}.\cr
  MSE-equivalent bandwidths (for different kernels) are proportional to
  \eqn{\sigma_K R(K)}{sig(K) R(K)} which is scale invariant and for our
  kernels equal to \eqn{R(K)}.  This value is returned when
  \code{give.Rkern = TRUE}.  See the examples for using exact equivalent
  bandwidths.

  Infinite values in \code{x} are assumed to correspond to a point mass at
  \code{+/-Inf} and the density estimate is of the sub-density on
  \code{(-Inf, +Inf)}.
}
\value{
  If \code{give.Rkern} is true, the number \eqn{R(K)}, otherwise
  an object with class \code{"density"} whose
  underlying structure is a list containing the following components.
  \item{x}{the \code{n} coordinates of the points where the density is
    estimated.}
  \item{y}{the estimated density values.}
  \item{bw}{the bandwidth used.}
  \item{N}{the sample size after elimination of missing values.}
  \item{call}{the call which produced the result.}
  \item{data.name}{the deparsed name of the \code{x} argument.}
  \item{has.na}{logical, for compatibility (always FALSE).}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole (for S version).

  Scott, D. W. (1992)
  \emph{Multivariate Density Estimation. Theory, Practice and Visualization}.
  New York: Wiley.

  Sheather, S. J. and Jones M. C. (1991)
  A reliable data-based bandwidth selection method for kernel density
  estimation.
  \emph{J. Roy. Statist. Soc.} \bold{B}, 683--690.

  Silverman, B. W. (1986)
  \emph{Density Estimation}.
  London: Chapman and Hall.

  Venables, W. N. and Ripley, B. D. (1999)
  \emph{Modern Applied Statistics with S-PLUS}.
  New York: Springer.
}
\seealso{
  \code{\link{bw.nrd}},
  \code{\link{plot.density}}, \code{\link{hist}}.
}
\examples{
plot(density(c(-20,rep(0,98),20)), xlim = c(-4,4))# IQR = 0

# The Old Faithful geyser data
data(faithful)
d <- density(faithful$eruptions, bw = "sj")
d
plot(d)

plot(d, type = "n")
polygon(d, col = "wheat")

## Missing values:
x <- xx <- faithful$eruptions
x[i.out <- sample(length(x), 10)] <- NA
doR <- density(x, bw = 0.15, na.rm = TRUE)
lines(doR, col = "blue")
points(xx[i.out], rep(0.01, 10))


(kernels <- eval(formals(density)$kernel))

## show the kernels in the R parametrization
plot (density(0, bw = 1), xlab = "",
      main="R's density() kernels with bw = 1")
for(i in 2:length(kernels))
   lines(density(0, bw = 1, kern =  kernels[i]), col = i)
legend(1.5,.4, legend = kernels, col = seq(kernels),
       lty = 1, cex = .8, y.int = 1)

## show the kernels in the S parametrization
plot(density(0, from=-1.2, to=1.2, width=2, kern="gaussian"), type="l",
     ylim = c(0, 1), xlab="", main="R's density() kernels with width = 1")
for(i in 2:length(kernels))
   lines(density(0, width=2, kern =  kernels[i]), col = i)
legend(0.6, 1.0, legend = kernels, col = seq(kernels), lty = 1)

(RKs <- cbind(sapply(kernels, function(k)density(kern = k, give.Rkern = TRUE))))
100*round(RKs["epanechnikov",]/RKs, 4) ## Efficiencies

if(interactive()) {
data(precip)
bw <- bw.SJ(precip) ## sensible automatic choice
plot(density(precip, bw = bw, n = 2^13),
     main = "same sd bandwidths, 7 different kernels")
for(i in 2:length(kernels))
   lines(density(precip, bw = bw, kern =  kernels[i], n = 2^13), col = i)

## Bandwidth Adjustment for "Exactly Equivalent Kernels"
h.f <- sapply(kernels, function(k)density(kern = k, give.Rkern = TRUE))
(h.f <- (h.f["gaussian"] / h.f)^ .2)
## -> 1, 1.01, .995, 1.007,... close to 1 => adjustment barely visible..

plot(density(precip, bw = bw, n = 2^13),
     main = "equivalent bandwidths, 7 different kernels")
for(i in 2:length(kernels))
   lines(density(precip, bw = bw, adjust = h.f[i], kern =  kernels[i],
         n = 2^13), col = i)
legend(55, 0.035, legend = kernels, col = seq(kernels), lty = 1)
}
}
\keyword{distribution}
\keyword{smooth}
\eof
\name{deparse}
\alias{deparse}
\title{Expression Deparsing}
\description{
  Turn unevaluated expressions into character strings.
}
\usage{
deparse(expr, width.cutoff = 60,
        backtick = mode(expr) \%in\% c("call", "expression", "("))
}
\arguments{
  \item{expr}{any \R expression.}
  \item{width.cutoff}{integer in \eqn{[20, 500]} determining the cutoff
    at which line-breaking is tried.}
  \item{backtick}{logical indicating whether symbolic names should be
    enclosed in backticks if they don't follow the standard syntax.}
}
\details{
  This function turns unevaluated expressions (where \dQuote{expression}
  is taken in a wider sense than the strict concept of a vector of mode
  \code{"expression"} used in \code{\link{expression}}) into character
  strings (a kind of inverse \code{\link{parse}}).

  A typical use of this is to create informative labels for data sets
  and plots.  The example shows a simple use of this facility.  It uses
  the functions \code{deparse} and \code{substitute} to create labels
  for a plot which are character string versions of the actual arguments
  to the function \code{myplot}.

  The default for the \code{backtick} option is not to quote single
  symbols but only composite expressions. This is a compromise to
  avoid breaking existing code.

}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{substitute}},
  \code{\link{parse}},
  \code{\link{expression}}.
}
\examples{
deparse(args(lm))
deparse(args(lm), width = 500)
myplot <-
function(x, y)
    plot(x, y, xlab=deparse(substitute(x)),
        ylab=deparse(substitute(y)))
}
e <- quote(`foo bar`)
deparse(e)
deparse(e, backtick=TRUE)
e <- quote(`foo bar`+1)
deparse(e)
\keyword{programming}
\keyword{manip}
\keyword{data}
\eof
\name{deriv}
\alias{D}
\alias{deriv}
\alias{deriv.default}
\alias{deriv.formula}
\alias{deriv3}
\alias{deriv3.default}
\alias{deriv3.formula}
\title{Symbolic and Algorithmic Derivatives of Simple Expressions}
\description{
  Compute derivatives of simple expressions, symbolically.
}
\synopsis{
D(expr, name)
deriv(expr, ...)
deriv.default(expr, namevec, function.arg = NULL, tag = ".expr", hessian = FALSE, ...)
deriv.formula(expr, namevec, function.arg = NULL, tag = ".expr", hessian = FALSE, ...)
deriv3(expr, ...)
deriv3.default(expr, namevec, function.arg = NULL, tag = ".expr", hessian = TRUE, ...)
deriv3.formula(expr, namevec, function.arg = NULL, tag = ".expr", hessian = TRUE, ...)
}
\usage{
    D (expr, name)
 deriv(expr, namevec, function.arg, tag = ".expr", hessian = FALSE)
deriv3(expr, namevec, function.arg, tag = ".expr", hessian = TRUE)
}
\arguments{
  \item{expr}{\code{\link{expression}} or \code{\link{call}} to
    be differentiated.}
  \item{name,namevec}{character vector, giving the variable names (only
    one for \code{D()}) with respect to which derivatives will be
    computed.}
  \item{function.arg}{If specified, a character vector of arguments for
    a function return, or a function (with empty body) or \code{TRUE},
    the latter indicating that a function with argument names
    \code{namevec} should be used.}
  \item{tag}{character; the prefix to be used for the locally created
    variables in result.}
  \item{hessian}{a logical value indicating whether the second derivatives
    should be calculated and incorporated in the return value.}
}
\details{
  \code{D} is modelled after its S namesake for taking simple symbolic
  derivatives.

  \code{deriv} is a \emph{generic} function with a default and a
  \code{\link{formula}} method.  It returns a \code{\link{call}} for
  computing the \code{expr} and its (partial) derivatives,
  simultaneously.  It uses so-called \dQuote{\emph{algorithmic
      derivatives}}.  If \code{function.arg} is a function,
  its arguments can have default values, see the \code{fx} example below.

  Currently, \code{deriv.formula} just calls \code{deriv.default} after
  extracting the expression to the right of \code{~}.

  \code{deriv3} and its methods are equivalent to \code{deriv} and its
  methods except that \code{hessian} defaults to \code{TRUE} for
  \code{deriv3}.
}
\value{
  \code{D} returns a call and therefore can easily be iterated
  for higher derivatives.

  \code{deriv} and \code{deriv3} normally return an
  \code{\link{expression}} object whose evaluation returns the function
  values with a \code{"gradient"} attribute containing the gradient
  matrix.  If \code{hessian} is \code{TRUE} the evaluation also returns
  a \code{"hessian"} attribute containing the Hessian array.
  
  If \code{function.arg} is specified, \code{deriv} and \code{deriv3}
  return a function with those arguments rather than an expression.
}
\references{
  Griewank, A.  and  Corliss, G. F. (1991)
  \emph{Automatic Differentiation of Algorithms: Theory, Implementation,
    and Application}.
  SIAM proceedings, Philadelphia.

  Bates, D. M. and Chambers, J. M. (1992)
  \emph{Nonlinear models.}
  Chapter 10 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{nlm}} and \code{\link{optim}} for numeric minimization
  which could make use of derivatives,
  \code{\link[nls]{nls}} in package \pkg{nls}.
}
\examples{
## formula argument :
dx2x <- deriv(~ x^2, "x") ; dx2x
\dontrun{expression({
         .value <- x^2
         .grad <- array(0, c(length(.value), 1), list(NULL, c("x")))
         .grad[, "x"] <- 2 * x
         attr(.value, "gradient") <- .grad
         .value
})}
mode(dx2x)
x <- -1:2
eval(dx2x)

## Something 'tougher':
trig.exp <- expression(sin(cos(x + y^2)))
( D.sc <- D(trig.exp, "x") )
all.equal(D(trig.exp[[1]], "x"), D.sc)

( dxy <- deriv(trig.exp, c("x", "y")) )
y <- 1
eval(dxy)
eval(D.sc)

## function returned:
deriv((y ~ sin(cos(x) * y)), c("x","y"), func = TRUE)

## function with defaulted arguments:
(fx <- deriv(y ~ b0 + b1 * 2^(-x/th), c("b0", "b1", "th"),
             function(b0, b1, th, x = 1:7){} ) )
fx(2,3,4)

## Higher derivatives
deriv3(y ~ b0 + b1 * 2^(-x/th), c("b0", "b1", "th"),
     c("b0", "b1", "th", "x") )

## Higher derivatives:
DD <- function(expr,name, order = 1) {
   if(order < 1) stop("'order' must be >= 1")
   if(order == 1) D(expr,name)
   else DD(D(expr, name), name, order - 1)
}
DD(expression(sin(x^2)), "x", 3)
## showing the limits of the internal "simplify()" :
\dontrun{
-sin(x^2) * (2 * x) * 2 + ((cos(x^2) * (2 * x) * (2 * x) + sin(x^2) *
    2) * (2 * x) + sin(x^2) * (2 * x) * 2)
}
}
\keyword{math}
\keyword{nonlinear}


\eof
\name{det}
\title{Calculate the Determinant of a Matrix}
\alias{det}
\alias{determinant}
\alias{determinant.matrix}
\usage{
det(x, \dots)
determinant(x, logarithm = TRUE, \dots)
}
\description{
  \code{det} calculates the determinant of a matrix. \code{determinant}
  is a generic function that returns separately the modulus of the determinant,
  optionally on the logarithm scale, and the sign of the determinant.
  }
\arguments{
  \item{x}{numeric matrix.}
  \item{logarithm}{logical; if \code{TRUE} (default) return the
    logarithm of the modulus of the determinant.}
  \item{\dots}{Optional arguments.  At present none are used.  Previous
    versions of \code{det} allowed an optional \code{method} argument.
    This argument will be ignored but will not produce an error.}
}
\value{
  For \code{det}, the determinant of \code{x}.  For \code{determinant}, a
  list with components
  \item{modulus}{a numeric value.  The modulus (absolute value) of the
    determinant if \code{logarithm} is \code{FALSE}; otherwise the
    logarithm of the modulus.}
  \item{sign}{integer; either \eqn{+1} or \eqn{-1} according to whether
    the determinant is positive or negative.}
}
\note{
  Often, computing the determinant is \emph{not} what you should be doing
  to solve a given problem.

  Prior to version 1.8.0 the \code{det} function had a \code{method}
  argument to allow use of either a QR decomposition or an
  eigenvalue-eigenvector decomposition.  The \code{determinant} function now
  uses an LU decomposition and the \code{det} function is simply a
  wrapper around a call to \code{determinant}.
}
%\seealso{\code{\link{eigen}}, \code{\link{qr}}, \code{\link{svd}}}
\examples{
(x <- matrix(1:4, ncol=2))
unlist(determinant(x))
det(x)

det(print(cbind(1,1:3,c(2,0,1))))
}

\keyword{array}
\eof
\name{detach}
\title{Detach Objects from the Search Path}
\usage{
detach(name, pos = 2, version)
}
\alias{detach}
\arguments{
  \item{name}{
    The object to detach.  Defaults to \code{search()[pos]}.
    This can be a name or a character string but \emph{not} a
    character vector.
  }
  \item{pos}{
    Index position in \code{\link{search}()} of database to
    detach.  When \code{name} is \code{\link{numeric}}, \code{pos = name}
    is used.
  }
    \item{version}{A character string denoting a version number of the 
     package to be loaded.  If no version is given, a suitable default
     is chosen.}
}
\description{
  Detach a database, i.e., remove it from the \code{\link{search}()} path
  of available \R objects. Usually, this either a \code{\link{data.frame}}
  which has been \code{\link{attach}}ed or a package which was required
  previously.
}
\value{
  The attached database is returned invisibly, either as
  \code{\link{data.frame}} or as \code{\link{list}}.
}
\note{
  You cannot detach either the workspace (position 1) or the \pkg{base}
  package (the last item in the search list).
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{attach}}, \code{\link{library}}, \code{\link{search}},
  \code{\link{objects}}.
}
\examples{
require(eda)#package
detach(package:eda)
## could equally well use detach("package:eda")
## but NOT  pkg <- "package:eda"; detach(pkg)
## Instead, use
library(eda)
pkg <- "package:eda"
detach(pos = match(pkg, search()))

## careful: do not do this unless 'lqs' is not already loaded.
library(lqs)
detach(2)# 'pos' used for 'name'
}
\keyword{data}
\eof
\name{dev.xxx}
\title{Control Multiple Devices}
\usage{
dev.cur()
dev.list()
dev.next(which = dev.cur())
dev.prev(which = dev.cur())
dev.off(which = dev.cur())
dev.set(which = dev.next())
graphics.off()
}
\alias{dev.cur}
\alias{dev.list}
\alias{dev.next}
\alias{dev.prev}
\alias{dev.off}
\alias{dev.set}
\alias{.Device}
\alias{.Devices}
\alias{graphics.off}

\arguments{
  \item{which}{An integer specifying a device number}
}
\description{
  These functions provide control over multiple graphics devices.

  Only one device is the \emph{active} device.  This is the device in
  which all graphics operations occur.

  Devices are associated with a name (e.g., \code{"X11"} or
  \code{"postscript"}) and a number; the \code{"null device"} is always
  device 1.

  \code{dev.off} shuts down the specified (by default the current) device.
  \code{graphics.off()} shuts down all open graphics devices.

  \code{dev.set} makes the specified device the active device.

  A list of the names of the open devices is stored in \code{.Devices}.
  The name of the active device is stored in \code{.Device}.
}
\value{
  \code{dev.cur} returns the number and name of the active device,
  or 1, the null device, if none is active.

  \code{dev.list} returns the numbers of all open devices, except device
  1, the null device.  This is a numeric vector with a names attribute
  giving the names, or \code{NULL} is there is no open device.

  \code{dev.next} and \code{dev.prev} return the number and name of the
  next / previous device in the list of devices.  The list is regarded as
  a circular list, and \code{"null device"} will be included only if there
  are no open devices.

  \code{dev.off} returns the name and number of the new active device
  (after the specified device has been shut down).

  \code{dev.set} returns the name and number of the new active device.
}
\seealso{
  \code{\link{Devices}}, such as \code{\link{postscript}}, etc;
  \code{\link{layout}} and its links for setting up plotting regions
  on the current device.
}
\examples{
\dontrun{## Unix-specific example
x11()
plot(1:10)
x11()
plot(rnorm(10))
dev.set(dev.prev())
abline(0,1)# through the 1:10 points
dev.set(dev.next())
abline(h=0, col="gray")# for the residual plot
dev.set(dev.prev())
dev.off(); dev.off()#- close the two X devices
}
}
\keyword{device}
\keyword{iplot}
\eof
\name{dev2}
\alias{dev.copy}
\alias{dev.print}
\alias{dev.copy2eps}
\alias{dev.control}
\title{Copy Graphics Between Multiple Devices}
\usage{
dev.copy(device, \dots, which = dev.next())
dev.print(device = postscript, \dots)
dev.copy2eps(\dots)
dev.control(displaylist = c("inhibit", "enable"))
}
\arguments{
  \item{device}{A device function (e.g., \code{x11},
    \code{postscript}, \ldots)}
  \item{\dots}{Arguments to the \code{device} function above.
    For \code{dev.print}, this includes \code{which} and by default any
    \code{\link{postscript}} arguments.}
  \item{which}{A device number specifying the device to copy to}
  \item{displaylist}{A character string: the only valid values are
    \code{"inhibit"} and \code{"enable"}.}
}
\description{
  \code{dev.copy} copies the graphics contents of the current device
  to the device specified by \code{which} or to a new device which has
  been created by the function specified by \code{device} (it is an
  error to specify both \code{which} and \code{device}).  (If recording
  is off on the current device, there are no contents to copy: this will
  result in no plot or an empty plot.)
  The device copied to becomes the current device.

  \code{dev.print} copies the graphics contents of the current device
  to a new device which has been created by the function specified by
  \code{device} and then shuts the new device.

  \code{dev.copy2eps} is similar to \code{dev.print} but produces an
  EPSF output file, in portrait orientation (\code{horizontal = FALSE})

  \code{dev.control} allows the user to control the recording of
  graphics operations in a device.  If \code{displaylist} is \code{"inhibit"}
  (\code{"enable")} then recording is turned off (on). It is only safe
  to change this at the beginning of a plot (just before or just after a
  new page).  Initially recording is on for screen devices, and off for
  print devices.
}
\value{
  \code{dev.copy} returns the name and number of the device which has
  been copied to.

  \code{dev.print} and \code{dev.copy2eps} return the name and number of
  the device which has been copied from.
}
\details{
  For \code{dev.copy2eps}, \code{width} and \code{height} are taken
  from the current device unless otherwise specified.  If just one of
  \code{width} and \code{height} is specified, the other is adjusted
  to preserve the aspect ratio of the device being copied.  The default
  file name is \code{Rplot.eps}.

#ifdef unix
  The default for \code{dev.print} is to produce and print a postscript
  copy, if \code{\link{options}("printcmd")} is set suitably.
#endif
#ifdef windows
  The default for \code{dev.print} is to produce and print a postscript
  copy.  This will not work unless
  \code{\link{options}("printcmd")} is set suitably and you have a
  PostScript printer: see \code{\link{postscript}} for how to set this
  up.  Windows users may prefer to use \code{dev.print(win.print)}.
#endif


  \code{dev.print} is most useful for producing a postscript print
  (its default) when the following applies.  Unless
  \code{file} is specified, the plot will be printed.  Unless
  \code{width}, \code{height} and \code{pointsize} are specified
  the plot dimensions will be taken from the current device, shrunk
  if necessary to fit on the paper. (\code{pointsize} is rescaled if the
  plot is shrunk.)  If \code{horizontal} is not specified and the plot
  can be printed at full size by switching its value this is done
  instead of shrinking the plot region.

  If \code{dev.print} is used with a specified device (even
  \code{postscript}) it sets the width and height in the same way as
  \code{dev.copy2eps}.
}
\note{
  Most devices (including all screen devices) have a display list
  which records all of the graphics operations that occur in the device.
  \code{dev.copy} copies graphics contents by copying the display list
  from one device to another device.  Also, automatic redrawing of
  graphics contents following the resizing of a device depends on the
  contents of the display list.

  After the command \code{dev.control("inhibit")}, graphics operations
  are not recorded in the display list so that \code{dev.copy} and
  \code{dev.print} will not copy anything and the contents of a device
  will not be redrawn automatically if the device is resized.

  The recording of graphics operations is relatively expensive in
  terms of memory so the command \code{dev.control("inhibit")} can be
  useful if memory usage is an issue.
}
\seealso{
  \code{\link{dev.cur}} and other \code{dev.xxx} functions
}
\examples{
\dontrun{
x11()
plot(rnorm(10), main="Plot 1")
dev.copy(device=x11)
mtext("Copy 1", 3)
dev.print(width=6, height=6, horizontal=FALSE) # prints it
dev.off(dev.prev())
dev.off()
}
}
\keyword{device}
\eof
\name{dev2bitmap}
\alias{dev2bitmap}
\alias{bitmap}
\title{Graphics Device for Bitmap Files via GhostScript}
\usage{
bitmap(file, type = "png256", height = 6, width = 6, res = 72,
       pointsize, \dots)
dev2bitmap(file, type = "png256", height = 6, width = 6, res = 72,
           pointsize, \dots)
}
\arguments{
  \item{file}{The output file name, with an appropriate extension.}
  \item{type}{The type of bitmap. the default is \code{"png256"}.}
  \item{height}{The plot height, in inches.}
  \item{width}{The plot width, in inches.}
  \item{res}{Resolution, in dots per inch.}
  \item{pointsize}{The pointsize to be used for text: defaults to
    something reasonable given the width and height}
  \item{\dots}{Other parameters passed to \code{\link{postscript}}.}
}
\description{
  \code{bitmap} generates a graphics file.
  \code{dev2bitmap} copies the current graphics device to a file in a
  graphics format.
}
\details{
  \code{dev2bitmap} works by copying the current device to a
  \code{\link{postscript}} device, and post-processing the output file
  using \code{ghostscript}.  \code{bitmap} works in the same way using a
  \code{postscript} device and postprocessing the output as
  \dQuote{printing}.

  You will need a version of \code{ghostscript} (5.10 and
  later have been tested): the full path to the executable can be set by
  the environment variable \env{R\_GSCMD}.

  The types available will depend on the version of \code{ghostscript},
  but are likely to include
  \code{"pcxmono"}, \code{"pcxgray"}, \code{"pcx16"}, \code{"pcx256"},
  \code{"pcx24b"}, \code{"pcxcmyk"}, \code{"pbm"}, \code{"pbmraw"},
  \code{"pgm"}, \code{"pgmraw"}, \code{"pgnm"}, \code{"pgnmraw"},
  \code{"pnm"}, \code{"pnmraw"}, \code{"ppm"}, \code{"ppmraw"},
  \code{"pkm"}, \code{"pkmraw"}, \code{"tiffcrle"}, \code{"tiffg3"},
  \code{"tiffg32d"}, \code{"tiffg4"}, \code{"tifflzw"},
  \code{"tiffpack"}, \code{"tiff12nc"}, \code{"tiff24nc"},
  \code{"psmono"}, \code{"psgray"}, \code{"psrgb"}, \code{"bit"},
  \code{"bitrgb"}, \code{"bitcmyk"}, \code{"pngmono"}, \code{"pnggray"},
  \code{"png16"}, \code{"png256"}, \code{"png16m"}, \code{"jpeg"},
  \code{"jpeggray"}, \code{"pdfwrite"}.

  Note: despite the name of the functions they can produce PDF \emph{via}
  \code{type = "pdfwrite"}, and the PDF produced is not bitmapped.

  For formats which contain a single image, a file specification like
  \code{Rplots\%03d.png} can be used: this is intepreted by GhostScript.

  For \code{dev2bitmap} if just one of \code{width} and \code{height} is
  specified, the other is chosen to preserve aspect ratio of the
  device being copied.
}
\value{
  None.
}

#ifdef windows
\note{
  Use of \code{bitmap} will leave a temporary file (with file name
  starting \code{Rbit}).  Use of the \code{\link{pdf}}, \code{\link{bmp}},
  \code{\link{png}} and \code{\link{jpeg}} devices is preferable to
  using these functions.
}
#endif

\seealso{
  \code{\link{postscript}}, \code{\link{png}} and
  \code{\link{jpeg}} and on Windows \code{bmp}.

  \code{\link{pdf}} generate PDF directly.

  To display an array of data, see \code{\link{image}}.
}

\keyword{utilities}
\eof
\name{deviance}
\alias{deviance}
\alias{deviance.default}
\alias{deviance.lm}
\alias{deviance.glm}
\alias{deviance.mlm}
\title{Model Deviance}
\description{
  Returns the deviance of a fitted model object.
}
\usage{
deviance(object, \dots)
}
\arguments{
  \item{object}{an object for which the deviance is desired.}
  \item{\dots}{additional optional argument.}
}
\details{
  This is a generic function which can be used to extract deviances for
  fitted models.  Consult the individual modeling functions for details
  on how to use this function.
}
\value{
  The value of the deviance extracted from the object \code{object}.
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S.}
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{df.residual}},
  \code{\link{extractAIC}},
  \code{\link{glm}},
  \code{\link{lm}}.
}
\keyword{models}
\eof
\name{df.residual}
\alias{df.residual}
\alias{df.residual.default}
\title{Residual Degrees-of-Freedom}
\description{
  Returns the residual degrees-of-freedom extracted from a fitted model
  object.
}
\usage{
df.residual(object, \dots)
}
\arguments{
  \item{object}{an object for which the degrees-of-freedom are desired.}
  \item{\dots}{additional optional arguments.}
}
\details{
  This is a generic function which can be used to extract residual
  degrees-of-freedom for fitted models.  Consult the individual modeling
  functions for details details on how to use this function.

  The default method just extracts the \code{df.residual} component.
}
\value{
  The value of the residual degrees-of-freedom extracted from the object
  \code{x}.
}
\seealso{
  \code{\link{deviance}}, \code{\link{glm}}, \code{\link{lm}}.
}
\keyword{models}
\keyword{regression}
\eof
\name{diag}
\title{Matrix Diagonals}
\usage{
diag(x = 1, nrow, ncol= )
diag(x) <- value
}
\alias{diag}
\alias{diag<-}
\description{
  Extract or replace the diagonal of a matrix,
  or construct a diagonal matrix.
}
\arguments{
  \item{x}{a matrix, vector or 1D array.}
  \item{nrow, ncol}{Optional dimensions for the result.}
  \item{value}{either a single value or a vector of length equal to that
    of the current diagonal.  Should be of a mode which can be coerced
    to that of \code{x}.}
}
\value{
  If \code{x} is a matrix then \code{diag(x)} returns the diagonal of
  \code{x}.  The resulting vector will have \code{\link{names}} if the
  matrix \code{x} has matching column and row names.

  If \code{x} is a vector (or 1D array) of length two or more,
  then \code{diag(x)} returns a diagonal matrix whose diagonal is \code{x}.

  If \code{x} is a vector of length one then \code{diag(x)} returns an
  identity matrix of order the nearest integer to \code{x}.  The
  dimension of the returned matrix can be specified by \code{nrow} and
  \code{ncol} (the default is square).

  The assignment form sets the diagonal of the matrix \code{x} to the
  given value(s).
}
\note{
  Using \code{diag(x)} can have unexpected effects if \code{x} is a
  vector that could be of length one. Use \code{diag(x, nrow =
    length(x))} for consistent behaviour.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
\code{\link{upper.tri}}, \code{\link{lower.tri}}, \code{\link{matrix}}.
}
\examples{
dim(diag(3))
diag(10,3,4) # guess what?
all(diag(1:3) == {m <- matrix(0,3,3); diag(m) <- 1:3; m})

diag(var(M <- cbind(X=1:5, Y=rnorm(5))))#-> vector with names "X" and "Y"
rownames(M) <- c(colnames(M),rep("",3));
M; diag(M) #  named as well
}
\keyword{array}
\eof
\name{diff}
\alias{diff}
\alias{diff.default}
\alias{diff.POSIXt}
\title{Lagged Differences}
\description{
  Returns suitably lagged and iterated differences.
}
\usage{
diff(x, \dots)

\method{diff}{default}(x, lag = 1, differences = 1, \dots)

\method{diff}{POSIXt}(x, lag = 1, differences = 1, \dots)
}
\arguments{
  \item{x}{a numeric vector or matrix containing the values to be
    differenced.}
  \item{lag}{an integer indicating which lag to use.}
  \item{differences}{an integer indicating the order of the difference.}
  \item{\dots}{further arguments to be passed to or from methods.}
}
\details{
  \code{diff} is a generic function with a default method and ones for
  classes \code{"\link{ts}"} and \code{"\link{POSIXt}"}.
  \code{\link{NA}}'s propagate.
}
\value{
  If \code{x} is a vector of length \code{n} and \code{differences=1},
  then the computed result is equal to the successive differences
  \code{x[(1+lag):n] - x[1:(n-lag)]}.

  If \code{difference} is larger than one this algorithm is applied
  recursively to \code{x}.
  Note that the returned value is a vector which is shorter than
  \code{x}.

  If \code{x} is a matrix then the difference operations are carried out
  on each column separately.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{diff.ts}}, \code{\link[ts]{diffinv}}.
}
\examples{
diff(1:10, 2)
diff(1:10, 2, 2)
x <- cumsum(cumsum(1:10))
diff(x, lag = 2)
diff(x, differences = 2)

diff(.leap.seconds)
}
\keyword{ts}
\keyword{arith}
\eof
\name{difftime}
\alias{difftime}
\alias{as.difftime}
\alias{print.difftime}
\alias{round.difftime}
\alias{Ops.difftime}
\alias{*.difftime}
\alias{/.difftime}
\alias{Math.difftime}
\alias{Summary.difftime}
\alias{[.difftime}
\title{Time Intervals}
\description{
  Create, print and round time intervals.
}
\usage{
time1 - time2
difftime(time1, time2, tz = "",
         units = c("auto", "secs", "mins", "hours", "days", "weeks"))
as.difftime(tim, format = "\%X")

\method{round}{difftime}(x, digits = 0)
}
\arguments{
  \item{time1, time2}{date-time objects.}
  \item{tz}{a timezone specification to be used for the conversion.
    System-specific, but \code{""} is the current time zone, and
    \code{"GMT"} is UTC.}
  \item{units}{character.  Units in which the results are desired. Can
    be abbreviated.}
  \item{tim}{character string specifying a time interval.}
  \item{format}{character specifying the format of \code{tim}.}
  \item{x}{an object inheriting from class \code{"difftime"}.}
  \item{digits}{integer.  Number of significant digits to retain.}
}
\details{
  Function \code{difftime} takes a difference of two date/time objects
  (of either class) and returns an object of class \code{"difftime"}
  with an attribute indicating the units.  There is a \code{\link{round}}
  method for objects of this class, as well as methods for the
  group-generic (see \code{\link[base]{Ops}}) logical and
  arithmetic operations.

  If \code{units = "auto"}, a suitable set of units is chosen, the largest
  possible (excluding \code{"weeks"}) in which all the absolute
  differences are greater than one.

  Subtraction of two date-time objects gives an object of this class,
  by calling \code{difftime} with \code{units="auto"}.  Alternatively,
  \code{as.difftime()} works on character-coded time intervals.

  Limited arithmetic is available on \code{"difftime"} objects: they can
  be added or subtracted, and multiplied or divided by a numeric vector.
  In addition, adding or subtracting a numeric vector implicitly
  converts the numeric vector to a \code{"difftime"} object with the
  same units as the \code{"difftime"} object.
}
\seealso{
  \code{\link{DateTimeClasses}}.
}
\examples{
(z <- Sys.time() - 3600)
Sys.time() - z                # just over 3600 seconds.

## time interval between releases of 1.2.2 and 1.2.3.
ISOdate(2001, 4, 26) - ISOdate(2001, 2, 26)

as.difftime(c("0:3:20", "11:23:15"))
as.difftime(c("3:20", "23:15", "2:"), format= "\%H:\%M")# 3rd gives NA
}
\keyword{utilities}
\keyword{chron}
\eof
\name{dim}
\alias{dim}
\alias{dim.data.frame}
\alias{dim<-}
\title{Dimensions of an Object}
\usage{
dim(x)
dim(x) <- value
}
\description{
  Retrieve or set the dimension of an object.
}
\arguments{
  \item{x}{an \R object, for example a matrix, array or data frame.}
  \item{value}{For the default method, either \code{NULL} or
    a numeric vector which coerced to integer (by truncation).}
}
\details{
  The functions \code{dim} and \code{dim<-} are generic.

  \code{dim} has a method for \code{\link{data.frame}}s, which returns
  the length of the \code{row.names} attribute of \code{x} and the
  length of \code{x} (the numbers of \dQuote{rows} and \dQuote{columns}).
}
\value{
  For an array (and hence in particular, for a matrix) \code{dim} retrieves
  the \code{dim} attribute of the object.  It is \code{NULL} or a vector
  of mode \code{\link{integer}}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{ncol}}, \code{\link{nrow}} and \code{\link{dimnames}}.
}
\examples{
x <- 1:12 ; dim(x) <- c(3,4)
x

# simple versions of nrow and ncol could be defined as follows
nrow0 <- function(x) dim(x)[1]
ncol0 <- function(x) dim(x)[2]
}
\keyword{array}
\eof
\name{dimnames}
\title{Dimnames of an Object}
\alias{dimnames}
\alias{dimnames<-}
\alias{dimnames.data.frame}
\alias{dimnames<-.data.frame}
\description{
  Retrieve or set the dimnames of an object.
}
\usage{
dimnames(x)
dimnames(x) <- value
}
\arguments{
  \item{x}{an \R object, for example a matrix, array or data frame.}
  \item{value}{a possible value for \code{dimnames(x)}: see
    \dQuote{Value}.}
}
\details{
  The functions \code{dimnames} and \code{dimnames<-} are generic.

  For an \code{\link{array}} (and hence in particular, for a
  \code{\link{matrix}}), they retrieve or set the \code{dimnames}
  attribute (see \link{attributes}) of the object.  The list
  \code{value} can have names, and these will be used to label the
  dimensions of the array where appropriate.

  Both have methods for data frames.  The dimnames of a data frame are
  its \code{row.names} attribute and its \code{\link{names}}.

  As from \R 1.8.0 factor components of \code{value} will be coerced to
  character. 
}
\value{
  The dimnames of a matrix or array can be \code{NULL} or a list of the
  same length as \code{dim(x)}.  If a list, its components are either
  \code{NULL} or a character vector the length of the appropriate
  dimension of \code{x}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{rownames}}, \code{\link{colnames}};
  \code{\link{array}}, \code{\link{matrix}}, \code{\link{data.frame}}.
}
\examples{
## simple versions of rownames and colnames
## could be defined as follows
rownames0 <- function(x) dimnames(x)[[1]]
colnames0 <- function(x) dimnames(x)[[2]]
}
\keyword{array}
\keyword{manip}
\eof
\name{discoveries}
\docType{data}
\alias{discoveries}
\title{Yearly Numbers of Important Discoveries}
\description{
  The numbers of \dQuote{great} inventions and scientific
  discoveries in each year from 1860 to 1959.
}
\usage{data(discoveries)}
\format{A time series of 100 values.}
\source{
  The World Almanac and Book of Facts, 1975 Edition, pages 315--318.
}
\references{
  McNeil, D. R. (1977)
  \emph{Interactive Data Analysis}.
  Wiley.
}
\examples{
data(discoveries)
plot(discoveries, ylab = "Number of important discoveries",
     las = 1)
title(main = "discoveries data set")
}
\keyword{datasets}
\eof
\name{do.call}
\title{Execute a Function Call}
\usage{
do.call(what, args)
}
\alias{do.call}
\arguments{
  \item{what}{a character string naming the function to be called.}
  \item{args}{a \emph{list} of arguments to the function call.  The
    \code{names} attribute of \code{args} gives the argument names.}
}
\description{
  \code{do.call} executes a function call from the name of the function
  and a list of arguments to be passed to it.
}
\value{
  The result of the (evaluated) function call.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{call}} which creates an unevaluated call.
}
\examples{
do.call("complex", list(imag = 1:3))
}
\keyword{programming}
\eof
\name{dotchart}
\alias{dotchart}
\title{Cleveland Dot Plots}
\description{
  Draw a Cleveland dot plot.
}
\usage{
dotchart(x, labels = NULL, groups = NULL, gdata = NULL,
         cex = par("cex"), pch = 21, gpch = 21, bg = par("bg"),
         color = par("fg"), gcolor = par("fg"), lcolor = "gray",
         xlim = range(x[is.finite(x)]),
         main = NULL, xlab = NULL, ylab = NULL, \dots)
}
\arguments{
  \item{x}{either a vector or matrix of numeric values (\code{NA}s are
    allowed).  If \code{x} is a matrix the overall plot consists of
    juxtaposed dotplots for each row.}
  \item{labels}{a vector of labels for each point.
    For vectors the default is to use \code{names(x)} and for matrices
    the row labels \code{dimnames(x)[[1]]}.}
  \item{groups}{an optional factor indicating how the elements of
    \code{x} are grouped.
    If \code{x} is a matrix, \code{groups} will default to the columns
    of \code{x}.}
  \item{gdata}{data values for the groups.
    This is typically a summary such as the median or mean
    of each group.}
  \item{cex}{the character size to be used.  Setting \code{cex}
    to a value smaller than one can be a useful way of avoiding label
    overlap.}
  \item{pch}{the plotting character or symbol to be used.}
  \item{gpch}{the plotting character or symbol to be used for group
    values.}
  \item{bg}{the background color of plotting characters or symbols to be
    used; use \code{\link{par}(bg= *)} to set the background color of
    the whole plot.}
  \item{color}{the color(s) to be used for points an labels.}
  \item{gcolor}{the single color to be used for group labels and
    values.}
  \item{lcolor}{the color(s) to be used for the horizontal lines.}
  \item{xlim}{horizontal range for the plot, see
    \code{\link{plot.window}}, e.g.}
  \item{main}{overall title for the plot, see \code{\link{title}}.}
  \item{xlab, ylab}{axis annotations as in \code{title}.}
  \item{\dots}{graphical parameters can also be specified as arguments.}
}
\value{
  This function is invoked for its side effect, which is to produce two
  variants of dotplots as described in Cleveland (1985).

  Dot plots are a reasonable substitute for bar plots.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Cleveland, W. S. (1985)
  \emph{The Elements of Graphing Data.}
  Monterey, CA: Wadsworth.
}
\examples{
data(VADeaths)
dotchart(VADeaths, main = "Death Rates in Virginia - 1940")
op <- par(xaxs="i")# 0 -- 100\%
dotchart(t(VADeaths), xlim = c(0,100),
         main = "Death Rates in Virginia - 1940")
par(op)
}
\keyword{hplot}
\eof
\name{double}
\title{Double Precision Vectors}
\alias{double}
\alias{as.double}
\alias{as.double.default}
\alias{is.double}
\alias{single}
\alias{as.single}
\alias{as.single.default}
\description{
  Create, coerce to or test for a double-precision vector.
}
\usage{
double(length = 0)
as.double(x, \dots)
is.double(x)
single(length = 0)
as.single(x, \dots)
}
\arguments{
  \item{length}{desired length.}
  \item{x}{object to be coerced or tested.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\value{
  \code{double} creates a double precision vector of the specified
  length.  The elements of the vector are all equal to \code{0}.

  \code{as.double} attempts to coerce its argument to be of double
  type: like \code{\link{as.vector}} it strips attributes including names.

  \code{is.double} returns \code{TRUE} or \code{FALSE} depending on
  whether its argument is of double type or not.  It is generic:
  you can write methods to handle of specific classes of objects,
  see \link{InternalMethods}.
}
\note{
  \emph{\R has no single precision data type.  All real numbers are
    stored in double precision format}.  The functions \code{as.single}
  and \code{single} are identical to \code{as.double} and \code{double}
  except they set the attribute \code{Csingle} that is used in the
  \code{\link{.C}} and \code{\link{.Fortran}} interface, and they are
  intended only to be used in that context.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{integer}}.
}
\examples{
is.double(1)
all(double(3) == 0)
}
\keyword{classes}
\eof
\name{download.file}
\alias{download.file}
\title{Download File from the Internet}
\description{
  This function can be used to download a file from the Internet.
}
\usage{
download.file(url, destfile, method, quiet = FALSE, mode="w",
              cacheOK = TRUE)
}
\arguments{
  \item{url}{A character string naming the URL of a resource to be
    downloaded.}

  \item{destfile}{A character string with the name where the downloaded
    file is saved.  Tilde-expansion is performed.}

  \item{method}{Method to be used for downloading files.  Currently
    download methods \code{"internal"}, \code{"wget"} and \code{"lynx"}
    are available.  The default is to choose the first of these which
    will be \code{"internal"}. The method can also be set through the
    option \code{"download.file.method"}: see \code{\link{options}()}.}

  \item{quiet}{If \code{TRUE}, suppress status messages (if any).}

  \item{mode}{character.  The mode with which to write the file. Useful
    values are \code{"w"}, \code{"wb"} (binary), \code{"a"} (append) and
    \code{"ab"}.  Only used for the \code{"internal"} method.}

  \item{cacheOK}{logical. Is a server-side cached value acceptable?
    Implemented for the \code{"internal"} and \code{"wget"} methods.}
}
\details{
  The function \code{download.file} can be used to download a single
  file as described by \code{url} from the internet and store it in
  \code{destfile}.
  The \code{url} must start with a scheme such as
  \code{"http://"}, \code{"ftp://"} or \code{"file://"}.

  \code{cacheOK = FALSE} is useful for \code{"http://"} URLs, and will
  attempt to get a copy directly from the site rather than from an
  intermediate cache.  (Not all platforms support it.)
  It is used by \code{\link{CRAN.packages}}.

  The remaining details apply to method \code{"internal"} only.

  The timeout for many parts of the transfer can be set by the option
  \code{timeout} which defaults to 60 seconds.

  The level of detail provided during transfer can be set by the
  \code{quiet} argument and the \code{internet.info} option.  The
  details depend on the platform and scheme, but setting
  \code{internet.info} to 0 gives all available details, including
  all server responses. Using 2 (the default) gives only serious
  messages, and 3 or more suppresses all messages.

#ifdef windows
  A progress bar tracks the transfer. If the file length is known, the
  full width of the bar is the known length.  Otherwise the initial
  width represents 100Kbytes and is doubled whenever the current width
  is exceeded.

  There is an alternative method if you have Internet Explorer 4 or
  later installed.   You can use the flag \option{--internet2}, when
  the \sQuote{Internet Options} of the system are used to choose proxies
  and so on; these are set in the Control Panel and are those used for
  Internet Explorer.
  This version does not support \code{cacheOK = FALSE}.

#endif
  Method \code{"wget"} can be used with proxy firewalls which require
  user/password authentication if proper values are stored in the
  configuration file for \code{wget}.
}
\note{
  Methods \code{"wget"} and \code{"lynx"} are for historical
  compatibility. They will block all other activity on the \R process.

  For methods \code{"wget"} and \code{"lynx"} a system call is made to
  the tool given by \code{method}, and the respective program must be
  installed on your system and be in the search path for executables.
}
\section{Setting Proxies}{
  This applies to the internal code only.

  Proxies can be specified via environment variables.
  Setting \code{"no_proxy"} stops any proxy being tried.
  Otherwise the setting of \code{"http_proxy"} or \code{"ftp_proxy"}
  (or failing that, the all upper-case version) is consulted and if
  non-empty used as a proxy site.  For FTP transfers, the username
  and password on the proxy can be specified by \code{"ftp_proxy_user"}
  and \code{"ftp_proxy_password"}.  The form of \code{"http_proxy"}
  should be \code{"http://proxy.dom.com/"} or
  \code{"http://proxy.dom.com:8080/"} where the port defaults to
  \code{80} and the trailing slash may be omitted. For
  \code{"ftp_proxy"} use the form \code{"ftp://proxy.dom.com:3128/"}
  where the default port is \code{21}.  These environment variables
  must be set before the download code is first used: they cannot be
  altered later by calling \code{Sys.putenv}.

  Usernames and passwords can be set for HTTP proxy transfers via
  environment variable \env{http\_proxy\_user} in the form
  \code{user:passwd}.  Alternatively, \code{"http_proxy"} can be of the
  form \code{"http://user:pass@proxy.dom.com:8080/"} for compatibility
  with \code{wget}.  Only the HTTP/1.0 basic authentication scheme is
  supported.
#ifdef windows
  Under Windows, if \code{"http_proxy_user"} is set to \code{"ask"} then
  a dialog box will come up for the user to enter the username and
  password.  \bold{NB:} you will be given only one opportunity to enter this,
  but if proxy authentication is required and fails there will be one
  further prompt per download.
#endif
}
\seealso{
  \code{\link{options}} to set the \code{timeout} and
  \code{internet.info} options.

  \code{\link{url}} for a finer-grained way to read data from URLs.

  \code{\link{url.show}}, \code{\link{CRAN.packages}},
  \code{\link{download.packages}} for applications
}
\keyword{utilities}
\eof
\name{dput}
\alias{dput}
\alias{dget}
\title{Write an Internal Object to a File}
\description{
  Writes an ASCII text representation of an \R object to a file
  or connection, or uses one to recreate the object.
}
\usage{
dput(x, file = "")
dget(file)
}
\arguments{
  \item{x}{an object.}
  \item{file}{either a character string naming a file or a
    connection. \code{""} indicates output to the console.}
}
\details{
  \code{dput} opens \code{file} and deparses the object \code{x} into
  that file.  The object name is not written (contrary to \code{dump}).
  If \code{x} is a function the associated environment is stripped.
  Hence scoping information can be lost.

  Using \code{dget}, the object can be recreated (with the limitations
  mentioned above).

  \code{dput} will warn if fewer characters were written to a file than
  expected, which may indicate a full or corrupt file system.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{deparse}}, \code{\link{dump}}, \code{\link{write}}.
}
\examples{
## Write an ASCII version of mean to the file "foo"
dput(mean, "foo")
## And read it back into 'bar'
bar <- dget("foo")
unlink("foo")
}
\keyword{file}
\keyword{programming}
\keyword{connection}
\eof
\name{drop}
\alias{drop}
\title{Drop Redundant Extent Information}
\description{
  Delete the dimensions of an array which have only one level.
}
\usage{
drop(x)
}
\arguments{
  \item{x}{an array (including a matrix).}
}
\value{
  If \code{x} is an object with a \code{dim} attribute (e.g., a matrix
  or \code{\link{array}}), then \code{drop} returns an object like
  \code{x}, but with any extents of length one removed.  Any
  accompanying \code{dimnames} attribute is adjusted and returned with
  \code{x}.

  Array subsetting (\code{\link{[}}) performs this reduction unless used
  with \code{drop = FALSE}, but sometimes it is useful to invoke
  \code{drop} directly.
}
\seealso{
  \code{\link{drop1}} which is used for dropping terms in models.
}
\examples{
dim(drop(array(1:12, dim=c(1,3,1,1,2,1,2))))# = 3 2 2
drop(1:3 \%*\% 2:4)# scalar product
}
\keyword{array}
\eof
\name{dummy.coef}
\title{Extract Coefficients in Original Coding}
\usage{
dummy.coef(object, \dots)

\method{dummy.coef}{lm}(object, use.na = FALSE, \dots)

\method{dummy.coef}{aovlist}(object, use.na = FALSE, \dots)
}
\alias{dummy.coef}
\alias{dummy.coef.lm}
\alias{dummy.coef.aovlist}
\alias{print.dummy.coef}
\alias{print.dummy.coef.list}
\arguments{
  \item{object}{a linear model fit.}
  \item{use.na}{logical flag for coefficients in a singular model. If
    \code{use.na} is true, undetermined coefficients will be missing; if
    false they will get one possible value.}
  \item{\dots}{arguments passed to or from other methods.}
}
\description{
  This extracts coefficients in terms of the original levels of the
  coefficients rather than the coded variables.
}
\details{
  A fitted linear model has coefficients for the contrasts of the factor
  terms, usually one less in number than the number of levels.  This
  function re-expresses the coefficients in the original coding; as the
  coefficients will have been fitted in the reduced basis, any implied
  constraints (e.g., zero sum for \code{contr.helmert} or \code{contr.sum}
  will be respected.  There will be little point in using
  \code{dummy.coef} for \code{contr.treatment} contrasts, as the missing
  coefficients are by definition zero.

  The method used has some limitations, and will give incomplete results
  for terms such as \code{poly(x, 2))}.  However, it is adequate for
  its main purpose, \code{aov} models.
}
\value{
  A list giving for each term the values of the coefficients. For a
  multistratum \code{aov} model, such a list for each stratum.
}

\section{Warning}{
  This function is intended for human inspection of the
  output: it should not be used for calculations.  Use coded variables
  for all calculations.

  The results differ from S for singular values, where S can be incorrect.
}

\seealso{\code{\link{aov}}, \code{\link{model.tables}}}

\examples{
options(contrasts=c("contr.helmert", "contr.poly"))
## From Venables and Ripley (2002) p.165.
N <- c(0,1,0,1,1,1,0,0,0,1,1,0,1,1,0,0,1,0,1,0,1,1,0,0)
P <- c(1,1,0,0,0,1,0,1,1,1,0,0,0,1,0,1,1,0,0,1,0,1,1,0)
K <- c(1,0,0,1,0,1,1,0,0,1,0,1,0,1,1,0,0,0,1,1,1,0,1,0)
yield <- c(49.5,62.8,46.8,57.0,59.8,58.5,55.5,56.0,62.8,55.8,69.5,
55.0, 62.0,48.8,45.5,44.2,52.0,51.5,49.8,48.8,57.2,59.0,53.2,56.0)

npk <- data.frame(block=gl(6,4), N=factor(N), P=factor(P),
                  K=factor(K), yield=yield)
npk.aov <- aov(yield ~ block + N*P*K, npk)
dummy.coef(npk.aov)

npk.aovE <- aov(yield ~  N*P*K + Error(block), npk)
dummy.coef(npk.aovE)
}
\keyword{models}
\eof
\name{dump}
\title{Text Representations of R Objects}
\usage{
dump(list, file = "dumpdata.R", append = FALSE, envir = parent.frame())
}
\alias{dump}
\description{
  This function takes a vector of names of \R objects and produces
  text representations of the objects on a file or connection.
  A \code{dump} file can be \code{\link{source}}d into another
  \R (or S) session.
}
\arguments{
  \item{list}{character. The names of one or more \R objects to be dumped.}

  \item{file}{either a character string naming a file or a
    connection. \code{""} indicates output to the console.}

  \item{append}{if \code{TRUE}, output will be appended to
    \code{file}; otherwise, it will overwrite the contents of
    \code{file}.}

  \item{envir}{the environment to search for objects.}
}
\details{
  At present the implementation of \code{dump} is very
  incomplete and it really only works for functions and
  simple vectors.

  \code{dump} will warn if fewer characters were written to a file than
  expected, which may indicate a full or corrupt file system.

  The function \code{\link{save}} is designed to be used for
  transporting \R data between machines.
}
\note{
  The \code{envir} argument was added at version 1.7.0, and changed the
  search path for named objects to include the environment from which
  \code{dump} was called.

  As \code{dump} is defined in the base namespace, the \pkg{base}
  package will be searched \emph{before} the global environment unless
  \code{dump} is called from the top level or the \code{envir} argument
  is given explicitly.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}

\seealso{\code{\link{dput}}, \code{\link{dget}},\code{\link{write}}.
}
\examples{
x <- 1; y <- 1:10
dump(ls(patt='^[xyz]'), "xyz.Rdmped")
unlink("xyz.Rdmped")
}
\keyword{file}
\keyword{connection}
\eof
\name{duplicated}
\alias{duplicated}
\alias{duplicated.default}
\alias{duplicated.data.frame}
\alias{duplicated.matrix}
\alias{duplicated.array}
\title{Determine Duplicate Elements}
\description{
  Determines which elements of a vector of data frame are duplicates
  of elements with smaller subscripts, and returns a logical vector
  indicating which elements (rows) are duplicates.
}
\usage{
duplicated(x, incomparables = FALSE, \dots)

\method{duplicated}{array}(x, incomparables = FALSE, MARGIN = 1, \dots)
}
\arguments{
  \item{x}{an atomic vector or a data frame or an array.}
  \item{incomparables}{a vector of values that cannot be compared.
    Currently, \code{FALSE} is the only possible value, meaning that all
    values can be compared.}
  \item{\dots}{arguments for particular methods.}
  \item{MARGIN}{the array margin to be held fixed: see
    \code{\link{apply}}.}
}
\details{
  This is a generic function with methods for vectors, data frames and
  arrays (including matrices).

  The data frame method works by pasting together a character
  representation of the rows separated by \code{\r}, so may be imperfect
  if the data frame has characters with embedded carriage returns or
  columns which do not reliably map to characters.

  The array method calculates for each element of the sub-array
  specified by \code{MARGIN} if the remaining dimensions are identical
  to those for an earlier element (in row-major order).  This would most
  commonly be used to find duplicated rows (the default) or columns
  (with \code{MARGIN = 2}).
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{\code{\link{unique}}.}
\examples{
x <- c(9:20, 1:5, 3:7, 0:8)
## extract unique elements
(xu <- x[!duplicated(x)])
## xu == unique(x) but unique(x) is more efficient

data(iris)
duplicated(iris)[140:143]

data(iris3)
duplicated(iris3, MARGIN = c(1, 3))
}
\keyword{logic}
\keyword{manip}
\eof
\name{dyn.load}
\alias{dyn.load}
\alias{dyn.unload}
\alias{is.loaded}
\alias{symbol.C}
\alias{symbol.For}
\title{Foreign Function Interface}
\description{
  Load or unload shared libraries, and test whether a C function or
  Fortran subroutine is available.
}
\usage{
dyn.load(x, local = TRUE, now = TRUE)
dyn.unload(x)

is.loaded(symbol, PACKAGE="")
symbol.C(name)
symbol.For(name)
}
\arguments{
  \item{x}{a character string giving the pathname to a shared library or
    DLL.}
  \item{local}{a logical value controlling whether the symbols in the
    shared library are stored in their own local table and not shared
    across shared libraries,
    or added to the global symbol table.  Whether this has any effect is
    system-dependent.
#ifdef windows
    It is ignored on Windows.
#endif
  }
  \item{now}{a logical controlling whether all symbols are resolved (and
    relocated) immediately the library is loaded or deferred until they
    are used.  This control is useful for developers testing whether a
    library is complete and has all the necessary symbols and for users
    to ignore missing symbols. Whether this has any effect is system-dependent.
#ifdef windows
    It is ignored on Windows.
#endif
  }
  \item{symbol}{a character string giving a symbol name.}
  \item{PACKAGE}{if supplied, confine the search for the \code{name} to
    the DLL given by this argument (plus the conventional extension,
    \code{.so}, \code{.sl}, \code{.dll}, \dots).  This is intended to
    add safety for packages, which can ensure by using this argument
    that no other package can override their external symbols.  Use
    \code{PACKAGE="base"} for symbols linked in to \R.  This is used in the
    same way as in \code{\link{.C}}, \code{\link{.Call}},
    \code{\link{.Fortran}} and \code{\link{.External}} functions}
  \item{name}{a character string giving either the name of a C function
    or Fortran subroutine.  Fortran names probably need to be given
    entirely in lower case (but this may be system-dependent).}
}
\details{
  See
#ifdef windows
  file \file{readme.packages},
#endif
  \sQuote{See Also} and the \emph{Writing R Extensions} manual for how to
  create a suitable shared library.  Note that unlike some versions of
  S-PLUS, \code{dyn.load} does not load an object (\code{.o}) file but a
  shared library or DLL.

  Unfortunately a very few platforms (Compaq Tru64) do not handle the
  \code{PACKAGE} argument correctly, and may incorrectly find symbols
  linked into \R.
  
  The additional arguments to \code{dyn.load} mirror the different
  aspects of the mode argument to the dlopen() routine on UNIX
  systems. They are available so that users can exercise greater control
  over the loading process for an individual library.  In general, the
  defaults values are appropriate and one should override them only if 
  there is good reason and you understand the implications.

#ifdef unix
  The \code{local} argument allows one to control whether the symbols in
  the DLL being attached are visible to other DLLs.  While maintaining
  the symbols in their own namespace is good practice, the ability to
  share symbols across related \dQuote{chapters} is useful in many
  cases.  Additionally, on certain platforms and versions of an
  operating system, certain libraries must have their symbols loaded
  globally to successfully resolve all symbols.

  One should be careful of the potential side-effect of using lazy
  loading via the \code{now} argument as \code{FALSE}.  If a routine is
  called that has a missing symbol, the process will terminate
  immediately and unsaved session variables will be lost.  The intended
  use is for library developers to call specify a value \code{TRUE} to
  check that all symbols are actually resolved and for regular users to
  all with \code{FALSE} so that missing symbols can be ignored and the
  available ones can be called.

  The initial motivation for adding these was to avoid such termination
  in the \code{_init()} routines of the Java virtual machine library.
  However, symbols loaded locally may not be (read probably) available
  to other DLLs.  Those added to the global table are available to all
  other elements of the application and so can be shared across two
  different DLLs.

  Some systems do not provide (explicit) support for local/global and
  lazy/eager symbol resolution.  This can be the source of subtle bugs.
  One can arrange to have warning messages emitted when unsupported
  options are used.  This is done by setting either of the options
  \code{verbose} or \code{warn} to be non-zero via the
  \code{\link{options}} function.  Currently, we know of only 2
  platforms that do not provide a value for local load (RTLD\_LOCAL).
  These are IRIX6.4 and unpatched versions of Solaris 2.5.1.

  There is a short discussion of these additional arguments with some
  example code available at
  \url{http://cm.bell-labs.com/stat/duncan/R/dynload}.
#endif

#ifdef windows
  External code must not change the floating point control word, but
  many DLLs do so.  Common changes are to set it to use 53 bit 
  precision instead of R's default 64 bit precision, or to unmask 
  some exceptions.  \code{dyn.load} detects such changes, 
  and restores R's control word to its default value of hex 8001F.  
  This may cause the DLL to malfunction; if so, it should be rewritten
  to save and restore the control word itself.  If \code{warn.FPU}
  is set to \code{TRUE} using the \code{\link{options}} function, 
  a warning will be printed.  (If the warning says
  that the control word was changed from some other value than 8001F, 
  please   report the circumstances to the Windows maintainers:  
  that probably indicates an internal bug.)
#endif
}
\value{
  The function \code{dyn.load} is used for its side effect which links
  the specified shared library to the executing \R image.  Calls to
  \code{.C}, \code{.Fortran} and \code{.External} can then be used to
  execute compiled C functions or Fortran subroutines contained in the
  library. 

  The function \code{dyn.unload} unlinks the shared library.

  Functions \code{symbol.C} and \code{symbol.For} map function or
  subroutine names to the symbol name in the compiled code:
  \code{is.loaded} checks if the symbol name is loaded and hence
  available for use in \code{.C} or \code{.Fortran}.
}
\note{
  The creation of shared libraries and the runtime linking of them into
  executing programs is very platform dependent.  In recent years there
  has been some simplification in the process because the C subroutine
  call \code{dlopen} has become the standard for doing this under UNIX.
  Under UNIX \code{dyn.load} uses the \code{dlopen} mechanism and should
  work on all platforms which support it.  On Windows it uses the
  standard mechanisms for loading 32-bit DLLs.

  The original code for loading DLLs in UNIX was provided by Heiner
  Schwarte.  The compatibility code for HP-UX was provided by Luke
  Tierney.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{library.dynam}} to be used inside a package's
  \code{\link{.First.lib}} initialization.

#ifdef unix
  \code{\link{SHLIB}} for how to create suitable shared objects.
#endif
#ifdef windows
  \code{\link{SHLIB}} for how to create suitable DLLs.
#endif
  
  \code{\link{.C}},
  \code{\link{.Fortran}},
  \code{\link{.External}},
  \code{\link{.Call}}.
}
\examples{
is.loaded(symbol.For("hcass2")) #-> probably TRUE, as mva is loaded
}
\keyword{interface}
\eof
\name{edit}
\alias{edit}
\alias{edit.default}
\alias{vi}
\alias{emacs}
\alias{pico}
\alias{xemacs}
\alias{xedit}
\title{Invoke a Text Editor}
\description{
  Invoke a text editor on an \R object.
}
\usage{
\method{edit}{default}(name = NULL, file = "", editor = getOption("editor"), \dots)
vi(name = NULL, file = "")
emacs(name = NULL, file = "")
pico(name = NULL, file = "")
xemacs(name = NULL, file = "")
xedit(name = NULL, file = "")
}
\arguments{
  \item{name}{a named object that you want to edit. If name is missing
    then the file specified by \code{file} is opened for editing.}
  \item{file}{a string naming the file to write the edited version to.}
  \item{editor}{a string naming the text editor you want to use.  On
    Unix the default is set from the environment variables \env{EDITOR}
    or \env{VISUAL} if either is set, otherwise \code{vi} is used.  On
    Windows it defaults to \code{notepad}.}
  \item{\dots}{further arguments to be passed to or from methods.}
}
\details{
  \code{edit} invokes the text editor specified by \code{editor} with
  the object \code{name} to be edited.  It is a generic function,
  currently with a default method and one for data frames and matrices.

  \code{data.entry} can be used to edit data, and is used by \code{edit}
  to edit matrices and data frames on systems for which
  \code{data.entry} is available.

  It is important to realize that \code{edit} does not change the object
  called \code{name}. Instead, a copy of name is made and it is that copy
  which is changed. Should you want the changes to apply to the object
  \code{name} you must assign the result of \code{edit} to
  \code{name}. (Try \code{\link{fix}} if you want to make permanent
  changes to an object.)
  
  In the form \code{edit(name)},
  \code{edit} deparses \code{name} into a temporary file and invokes the
  editor \code{editor} on this file. Quitting from the editor causes
  \code{file} to be parsed and that value returned.
  Should an error occur in parsing, possibly due to incorrect syntax, no
  value is returned. Calling \code{edit()}, with no arguments, will
  result in the temporary file being reopened for further editing.
}
\seealso{
  \code{\link{edit.data.frame}},
  \code{\link{data.entry}},
  \code{\link{fix}}.
}
\note{
  The functions \code{vi}, \code{emacs}, \code{pico}, \code{xemacs},
  \code{xedit} rely on the corresponding editor being available and
  being on the path. This is system-dependent.
}
\examples{
\dontrun{
# use xedit on the function mean and assign the changes
mean <- edit(mean, editor = "xedit")

# use vi on mean and write the result to file mean.out
vi(mean, file = "mean.out")
}
}
\keyword{utilities}
\eof
\name{edit.data.frame}
\alias{edit.data.frame}
\alias{edit.matrix}
\title{Edit Data Frames and Matrices}
\description{
  Use data editor on data frame or matrix contents.
}
\usage{
\method{edit}{data.frame}(name, factor.mode = c("character", "numeric"),
     edit.row.names = any(row.names(name) != 1:nrow(name)), \dots)

\method{edit}{matrix}(name, edit.row.names = any(rownames(name) != 1:nrow(name)), \dots)
}
\arguments{
  \item{name}{A data frame or matrix.}
  \item{factor.mode}{How to handle factors (as integers or using
    character levels) in a data frame.}
  \item{edit.row.names}{logical. Show the row names be displayed as
    a separate editable column?}
  \item{\dots}{further arguments passed to or from other methods.}
}
\details{
  At present, this only works on simple data frames containing numeric, 
  logical or character vectors and factors. Factors are represented in the
  spreadsheet as either numeric vectors (which is more suitable for data
  entry) or character vectors (better for browsing). After editing,
  vectors are padded with \code{NA} to have the same length and
  factor attributes are restored.  The set of factor levels can not be
  changed by editing in numeric mode; invalid levels are changed to
  \code{NA} and a warning is issued.  If new factor levels are
  introduced in character mode, they are added at the end of the list of
  levels in the order in which they encountered.

  It is possible to use the data-editor's facilities to select the mode
  of columns to swap between numerical and factor columns in a data
  frame.  Changing any column in a numerical matrix to character will
  cause the result to be coerced to a character matrix.  Changing 
  the mode of logical columns is not supported.
}
\value{
  The edited data frame.
}
\author{ Peter Dalgaard }
\note{
  \code{fix(dataframe)} works for in-place editing by calling this
  function.

  If the data editor is not available, a dump of the object is presented
  for editing using the default method of \code{edit}.

  At present the data editor is limited to 65535 rows.
}
\seealso{\code{\link{data.entry}}, \code{\link{edit}}}
\examples{
\dontrun{
data(InsectSprays)
edit(InsectSprays)
edit(InsectSprays, factor.mode="numeric")
}
}

\keyword{utilities}
\eof
\name{eff.aovlist}
\title{Compute Efficiencies of Multistratum Analysis of Variance}
\usage{
eff.aovlist(aovlist)
}
\alias{eff.aovlist}
\arguments{
  \item{aovlist}{
    The result of a call to \code{aov} with a \code{Error} term.
  }
}
\description{
  Computes the efficiencies of fixed-effect terms in an analysis of
  variance model with multiple strata.
}
\details{
  Fixed-effect terms in an analysis of variance model with multiple strata
  may be estimable in more than one stratum, in which case there is less
  than complete information in each. The efficiency is the fraction of
  the maximum possible precision (inverse variance) obtainable by
  estimating in just that stratum.

  This is used to pick strata in which to estimate terms in
  \code{model.tables.aovlist} and elsewhere.
}
\value{
  A matrix giving for each non-pure-error stratum (row) the efficiencies
  for each fixed-effect term in the model.
}

\seealso{\code{\link{aov}}, \code{\link{model.tables.aovlist}},
  \code{\link{se.contrast.aovlist}} }

\examples{
## for balanced designs all efficiencies are zero or one.
## so as a statistically meaningless test:
options(contrasts=c("contr.helmert", "contr.poly"))
## From Venables and Ripley (2002) p.165.
N <- c(0,1,0,1,1,1,0,0,0,1,1,0,1,1,0,0,1,0,1,0,1,1,0,0)
P <- c(1,1,0,0,0,1,0,1,1,1,0,0,0,1,0,1,1,0,0,1,0,1,1,0)
K <- c(1,0,0,1,0,1,1,0,0,1,0,1,0,1,1,0,0,0,1,1,1,0,1,0)
yield <- c(49.5,62.8,46.8,57.0,59.8,58.5,55.5,56.0,62.8,55.8,69.5,
55.0, 62.0,48.8,45.5,44.2,52.0,51.5,49.8,48.8,57.2,59.0,53.2,56.0)

npk <- data.frame(block=gl(6,4), N=factor(N), P=factor(P),
                  K=factor(K), yield=yield)
npk.aovE <- aov(yield ~  N*P*K + Error(block), npk)
eff.aovlist(npk.aovE)
}
\keyword{models}
\eof
\name{effects}
\title{Effects from Fitted Model}
\usage{
effects(object, \dots)

\method{effects}{lm}(object, set.sign=FALSE, \dots)
}
\alias{effects}
\alias{effects.lm}
\alias{effects.glm}
\arguments{
 \item{object}{an \R object; typically, the result of a model fitting function
   such as \code{\link{lm}}.}
 \item{set.sign}{logical. If \code{TRUE}, the sign of the effects
   corresponding to coefficients in the model will be set to agree with the
   signs of the corresponding coefficients, otherwise the sign is
   arbitrary.}
 \item{\dots}{arguments passed to or from other methods.}
}
\description{
  Returns (orthogonal) effects from a fitted model, usually a linear
  model. This is a generic function, but currently only has a methods for
  objects inheriting from classes \code{"lm"} and \code{"glm"}.
}
\details{
  For a linear model fitted by \code{\link{lm}} or \code{\link{aov}},
  the effects are the uncorrelated single-degree-of-freedom values
  obtained by projecting the data onto the successive orthogonal
  subspaces generated by the QR decomposition during the fitting
  process. The first \eqn{r} (the rank of the model) are associated with
  coefficients and the remainder span the space of residuals (but are
  not associated with particular residuals).

  Empty models do not have effects.
}
\value{
  A (named) numeric vector of the same length as
  \code{\link{residuals}}, or a matrix if there were multiple responses
  in the fitted model, in either case of class \code{"coef"}.

  The first \eqn{r} rows are labelled by the corresponding coefficients,
  and the remaining rows are unlabelled.  Note that in rank-deficient
  models the \dQuote{corresponding} coefficients will be in a different
  order if pivoting occurred.
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S.}
  Wadsworth \& Brooks/Cole.
}
\seealso{\code{\link{coef}}}
\examples{
y <- c(1:3,7,5)
x <- c(1:3,6:7)
( ee <- effects(lm(y ~ x)) )
c(round(ee - effects(lm(y+10 ~ I(x-3.8))),3))# just the first is different
}
\keyword{models}
\keyword{regression}
\eof
\name{eigen}
\alias{eigen}
\alias{La.eigen}
\title{Spectral Decomposition of a Matrix}
\usage{
eigen(x, symmetric, only.values = FALSE, EISPACK = FALSE)
La.eigen(x, symmetric, only.values = FALSE,
         method = c("dsyevr", "dsyev"))
}
\arguments{
  \item{x}{a matrix whose spectral decomposition is to be computed.}
  \item{symmetric}{if \code{TRUE}, the matrix is assumed to be symmetric
    (or Hermitian if complex) and only its lower triangle is used.
    If \code{symmetric} is not specified, the matrix is inspected for
    symmetry.}
  \item{only.values}{if \code{TRUE}, only the eigenvalues are computed
    and returned, otherwise both eigenvalues and eigenvectors are
    returned.}
  \item{EISPACK}{logical. Should EISPACK be used (for compatibility with
    \R < 1.7.0)?}
  \item{method}{The LAPACK routine to use in the real symmetric case.}
}
\description{
  Computes eigenvalues and eigenvectors.
}
\details{
  These functions use the LAPACK routines DSYEV/DSYEVR,
  DGEEV, ZHEEV and ZGEEV, and \code{eigen(EISPACK=TRUE)} provides an
  interface to the EISPACK routines \code{RS}, \code{RG}, \code{CH}
  and \code{CG}.
   
  If \code{symmetric} is unspecified, the code attempts to
  determine if the matrix is symmetric up to plausible numerical
  inaccuracies.  It is faster and surer to set the value yourself.

  \code{eigen} is preferred to \code{eigen(EISPACK=TRUE)}
  for new projects, but its eigenvectors may differ in sign and
  (in the asymmetric case) in normalization. (They may also differ
  between methods and between platforms.)

  The LAPACK routine DSYEVR is usually substantially
  faster than DSYEV: see
  \url{http://www.cs.berkeley.edu/~demmel/DOE2000/Report0100.html}.
  Most benefits are seen with an optimized BLAS system.

  Using \code{method="dsyevr"} requires IEEE 754 arithmetic.  Should
  this not be supported on your platform, \code{method="dsyev"} is
  used, with a warning.

  Computing the eigenvectors is the slow part for large matrices.
}
\value{
  The spectral decomposition of \code{x} is returned
  as components of a list.
  \item{values}{a vector containing the \eqn{p} eigenvalues of \code{x},
    sorted in \emph{decreasing} order, according to \code{Mod(values)}
    if they are complex.
  }
  \item{vectors}{a \eqn{p\times p}{p * p} matrix whose columns contain the
    eigenvectors of \code{x}, or \code{NULL} if \code{only.values} is
    \code{TRUE}.
    
    For \code{eigen(, symmetric = FALSE, EISPACK =TRUE)}
    the choice of length of the
    eigenvectors is not defined by EISPACK. In all other cases the
    vectors are normalized to unit length.

    Recall that the eigenvectors are only defined up to a constant: even
    when the length is specified they are still only defined up to a
    scalar of modulus one (the sign for real matrices).
  }
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Smith, B. T, Boyle, J. M., Dongarra, J. J., Garbow, B. S., Ikebe,Y.,
  Klema, V., and  Moler, C. B. (1976).
  \emph{Matrix Eigensystems Routines -- EISPACK Guide}.
  Springer-Verlag Lecture Notes in Computer Science.

  Anderson. E. and ten others (1999)
  \emph{LAPACK Users' Guide}. Third Edition. SIAM.\cr
  Available on-line at
  \url{http://www.netlib.org/lapack/lug/lapack_lug.html}.
}

\seealso{
  \code{\link{svd}}, a generalization of \code{eigen}; \code{\link{qr}}, and
  \code{\link{chol}} for related decompositions.

  To compute the determinant of a matrix, the \code{\link{qr}}
  decomposition is much more efficient: \code{\link{det}}.

  \code{\link{capabilities}} to test for IEEE 754 arithmetic.
}
\examples{
eigen(cbind(c(1,-1),c(-1,1)))
eigen(cbind(c(1,-1),c(-1,1)), symmetric = FALSE)# same (different algorithm).

eigen(cbind(1,c(1,-1)), only.values = TRUE)
eigen(cbind(-1,2:1)) # complex values
eigen(print(cbind(c(0,1i), c(-1i,0))))# Hermite ==> real Eigen values
## 3 x 3:
eigen(cbind( 1,3:1,1:3))
eigen(cbind(-1,c(1:2,0),0:2)) # complex values

}
\keyword{algebra}
\keyword{array}
\eof
\name{environment}
\alias{environment}
\alias{environment<-}
\alias{.GlobalEnv}
\alias{globalenv}
\alias{is.environment}
\alias{new.env}
\alias{parent.env}
\alias{parent.env<-}
\alias{.BaseNamespaceEnv}
\title{Environment Access}
\description{
  Get, set, test for and create environments.
}
\usage{
environment(fun = NULL)
environment(fun) <- value
is.environment(obj)
.GlobalEnv
globalenv()
new.env(hash=FALSE, parent=parent.frame())
parent.env(env)
parent.env(env) <- value
}
\arguments{
  \item{fun}{a \code{\link{function}}, a \code{\link{formula}}, or
    \code{NULL}, which is the default.}
  \item{value}{an environment to associate with the function}
  \item{obj}{an arbitrary \R object.}
  \item{hash}{a logical, if \code{TRUE} the environment will be hashed}
  \item{parent}{an environment to be used as the parent of the
    environment created.}
  \item{env}{an environment}
}
\value{
  If \code{fun} is a function or a formula then \code{environment(fun)}
  returns the environment associated with that function or formula.
  If \code{fun} is \code{NULL} then the current evaluation environment is
  returned.

  The assignment form sets the environment of the function or formula
  \code{fun} to the \code{value} given.

  \code{is.environment(obj)} returns \code{TRUE} iff \code{obj} is an
  \code{environment}.

  \code{new.env} returns a new (empty) environment enclosed in the
  parent's environment, by default.

  \code{parent.env} returns the parent environment of its argument.

  \code{parent.env<-} sets the parent environment of its first argument.
}
\details{
  The global environment \code{.GlobalEnv} is the first item on the
  search path, more often known as the user's workspace.  It can also be
  accessed by \code{globalenv()}.

  The variable \code{.BaseNamespaceEnv} is part of some experimental
  support for name space management.

  The replacement function \code{parent.env<-} is extremely dangerous as
  it can be used to destructively change environments in ways that
  violate assumptions made by the internal C code.  It may be removed
  in the near future.

  \code{is.environment} is generic: you can write methods to handle
  of specific classes of objects, see \link{InternalMethods}.
}
\seealso{
  The \code{envir} argument of \code{\link{eval}}.
}
\examples{
##-- all three give the same:
environment()
environment(environment)
.GlobalEnv

ls(envir=environment(approxfun(1:2,1:2, method="const")))

is.environment(.GlobalEnv)# TRUE

e1 <- new.env(TRUE, NULL)
e2 <- new.env(FALSE, NULL)
assign("a", 3, env=e2)
parent.env(e1) <- e2
get("a", env=e1)

}
\keyword{data}
\keyword{programming}
\eof
\name{esoph}
\docType{data}
\alias{esoph}
\title{Smoking, Alcohol and (O)esophageal Cancer}
\description{
  Data from a case-control study of (o)esophageal cancer in
  Ile-et-Vilaine, France.
}
\usage{data(esoph)}
\format{
  A data frame with records for 88 age/alcohol/tobacco combinations.

  \tabular{rlll}{
    [,1] \tab "agegp" \tab Age group \tab 1  25--34 years\cr
    \tab \tab \tab 2  35--44\cr
    \tab \tab \tab 3  45--54\cr
    \tab \tab \tab 4  55--64\cr
    \tab \tab \tab 5  65--74\cr
    \tab \tab \tab 6  75+\cr
    [,2] \tab "alcgp" \tab Alcohol consumption \tab 1   0--39 gm/day\cr
    \tab \tab \tab 2  40--79\cr
    \tab \tab \tab 3  80--119\cr
    \tab \tab \tab 4  120+\cr
    [,3] \tab "tobgp" \tab Tobacco consumption \tab 1   0-- 9 gm/day\cr
    \tab \tab \tab 2  10--19\cr
    \tab \tab \tab 3  20--29\cr
    \tab \tab \tab 4  30+\cr
    [,4] \tab "ncases" \tab Number of cases \tab \cr
    [,5] \tab "ncontrols" \tab Number of controls \tab
  }
}
\source{
  Breslow, N. E. and Day, N. E. (1980)
  \emph{Statistical Methods in Cancer Research. 1: The Analysis of
    Case-Control Studies.}  IARC Lyon / Oxford University Press.
}
\author{Thomas Lumley}
\examples{
data(esoph)
summary(esoph)
## effects of alcohol, tobacco and interaction, age-adjusted
model1 <- glm(cbind(ncases, ncontrols) ~ agegp + tobgp * alcgp,
              data = esoph, family = binomial())
anova(model1)
## Try a linear effect of alcohol and tobacco
model2 <- glm(cbind(ncases, ncontrols) ~ agegp + unclass(tobgp)
                                         + unclass(alcgp),
              data = esoph, family = binomial())
summary(model2)
## Re-arrange data for a mosaic plot
ttt <- table(esoph$agegp, esoph$alcgp, esoph$tobgp)
ttt[ttt == 1] <- esoph$ncases
tt1 <- table(esoph$agegp, esoph$alcgp, esoph$tobgp)
tt1[tt1 == 1] <- esoph$ncontrols
tt <- array(c(ttt, tt1), c(dim(ttt),2),
            c(dimnames(ttt), list(c("Cancer", "control"))))
mosaicplot(tt, main = "esoph data set", color = TRUE)
}
\keyword{datasets}
\eof
\name{euro}
\docType{data}
\alias{euro}
\alias{euro.cross}
\title{Conversion Rates of Euro Currencies}
\description{Conversion rates between the various Euro currencies.}
\usage{data(euro)}
\format{
  \code{euro} is a named vector of length 11, \code{euro.cross} a named
  matrix of size 11 by 11.
}
\details{
  The data set \code{euro} contains the value of 1 Euro in all
  currencies participating in the European monetary union (Austrian
  Schilling ATS, Belgian Franc BEF, German Mark DEM, Spanish Peseta ESP,
  Finnish Markka FIM, French Franc FRF, Irish Punt IEP, Italian Lira
  ITL, Luxembourg Franc LUF, Dutch Guilder NLG and Portugese Escudo
  PTE).  These conversion rates were fixed by the European Union on
  December 31, 1998.  To convert old prices to Euro prices, divide by
  the respective rate and round to 2 digits.

  The data set \code{euro.cross} contains conversion rates between the
  various Euro currencies, i.e., the result of
  \code{outer(1 / euro, euro)}.
}
\examples{
data(euro)
cbind(euro)

## These relations hold:
euro == signif(euro,6) # [6 digit precision in Euro's definition]
all(euro.cross == outer(1/euro, euro))

## Convert 20 Euro to Belgian Franc
20 * euro["BEF"]
## Convert 20 Austrian Schilling to Euro
20 / euro["ATS"]
## Convert 20 Spanish Pesetas to Italian Lira
20 * euro.cross["ESP", "ITL"]

dotchart(euro,
         main = "euro data: 1 Euro in currency unit")
dotchart(1/euro,
         main = "euro data: 1 currency unit in Euros")
dotchart(log(euro, 10),
         main = "euro data: log10(1 Euro in currency unit)")
}
\keyword{datasets}
\eof
\name{eurodist}
\docType{data}
\alias{eurodist}
\title{Distances Between European Cities}
\description{
  The data give the road distances (in km) between 21 cities in Europe.
  The data are taken from a table in \dQuote{The Cambridge Encyclopaedia}.
}
\usage{data(eurodist)}
\format{
  A \code{dist} object based on 21 objects.
  (You must have the \pkg{mva} package loaded to have the methods for this
  kind of object available).
}
\source{
  Crystal, D. Ed. (1990)
  \emph{The Cambridge Encyclopaedia}.
  Cambridge: Cambridge University Press,
}
\keyword{datasets}
\eof
\name{eval}
\alias{eval}
\alias{evalq}
\alias{eval.parent}
\alias{local}
\title{Evaluate an (Unevaluated) Expression}
\description{
  Evaluate an \R expression in a specified environment.
}
\usage{
eval(expr, envir = parent.frame(),
     enclos = if(is.list(envir) || is.pairlist(envir)) parent.frame())
evalq(expr, envir, enclos)
eval.parent(expr, n = 1)
local(expr, envir = new.env())
}
\arguments{
  \item{expr}{object of mode \code{\link{expression}} or\code{call} or
    an \dQuote{unevaluated expression}.}
  \item{envir}{the \code{\link{environment}} in which \code{expr} is to
    be evaluated.  May also be a list, a data frame, or an integer as in
    \code{sys.call}.}
  \item{enclos}{Relevant when \code{envir} is a list or a data frame.
    Specifies the
    enclosure, i.e., where \R looks for objects not found in
    \code{envir}.}
  \item{n}{parent generations to go back}
}
\details{
  \code{eval} evaluates the expression \code{expr} argument in the
  environment specified by \code{envir} and returns the computed value.
  If \code{envir} is not specified, then
  \code{\link{sys.frame}(\link{sys.parent}())}, the environment where
  the call to \code{eval} was made is used.

  The \code{evalq} form is equivalent to \code{eval(quote(expr), \dots)}.

  As \code{eval} evaluates its first argument before passing it to the
  evaluator, it allows you to assign complicated expressions to symbols
  and then evaluate them.  \code{evalq} avoids this.

  \code{eval.parent(expr, n)} is a shorthand for \code{eval(expr,
    parent.frame(n))}.

  \code{local} evaluates an expression in a local environment.  It is
  equivalent to \code{evalq} except the its default argument creates a
  new, empty environment.  This is useful to create anonymous recursive
  functions and as a kind of limited namespace feature since variables
  defined in the environment are not visible from the outside.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole. (\code{eval} only.)
}
\seealso{
  \code{\link{expression}}, \code{quote}, \code{\link{sys.frame}},
  \code{\link{parent.frame}}, \code{\link{environment}}.
}
\note{
  Due to the difference in scoping rules, there are some differences
  between \R and S in this area.  In particular, the default enclosure
  in S is the global environment.

  When evaluating expressions in data frames that has been passed as
  argument to a function, the relevant enclosure is often the caller's
  environment, i.e., one needs
  \code{eval(x, data, parent.frame())}.
}
\examples{
eval(2 ^ 2 ^ 3)
mEx <- expression(2^2^3); mEx; 1 + eval(mEx)
eval({ xx <- pi; xx^2}) ; xx

a <- 3 ; aa <- 4 ; evalq(evalq(a+b+aa, list(a=1)), list(b=5)) # == 10
a <- 3 ; aa <- 4 ; evalq(evalq(a+b+aa, -1), list(b=5))         # == 12

ev <- function() {
   e1 <- parent.frame()
   ## Evaluate a in e1
   aa <- eval(expression(a),e1)
   ## evaluate the expression bound to a in e1
   a <- expression(x+y)
   list(aa = aa, eval = eval(a, e1))
}
tst.ev <- function(a = 7) { x <- pi; y <- 1; ev() }
tst.ev()#-> aa : 7,  eval : 4.14

##
## Uses of local()
##

# Mutual recursives.
# gg gets value of last assignment, an anonymous version of f.

gg <- local({
    k <- function(y)f(y)
    f <- function(x) if(x) x*k(x-1) else 1
})
gg(10)
sapply(1:5, gg)

# Nesting locals. a is private storage accessible to k
gg <- local({
    k <- local({
        a <- 1
        function(y){print(a <<- a+1);f(y)}
    })
    f <- function(x) if(x) x*k(x-1) else 1
})
sapply(1:5, gg)

ls(envir=environment(gg))
ls(envir=environment(get("k", envir=environment(gg))))
}
\keyword{data}
\keyword{programming}
\eof
\name{example}
\alias{example}
\title{Run an Examples Section from the Online Help}
\description{
  Run all the \R code from the \bold{Examples} part of \R's online help
  topic \code{topic} with two possible exceptions, \code{dontrun} and
  \code{dontshow}, see Details below.
}
\usage{
example(topic, package = .packages(), lib.loc = NULL,
        local = FALSE, echo = TRUE, verbose = getOption("verbose"),
        prompt.echo = paste(abbreviate(topic, 6),"> ", sep=""))
}
\arguments{
  \item{topic}{name or literal character string: the online
    \code{\link{help}} topic the examples of which should be run.}
  \item{package}{a character vector with package names.  By default,
    all packages in the search path are used.}
  \item{lib.loc}{a character vector of directory names of \R libraries,
    or \code{NULL}.  The default value of \code{NULL} corresponds to all
    libraries currently known.  If the default is used, the loaded
    packages are searched before the libraries.}
  \item{local}{logical: if \code{TRUE} evaluate locally, if \code{FALSE}
    evaluate in the workspace.}
  \item{echo}{logical;  if \code{TRUE}, show the \R input when sourcing.}
  \item{verbose}{logical;  if \code{TRUE}, show even more when running
    example code.}
  \item{prompt.echo}{character; gives the prompt to be used if
    \code{echo = TRUE}.}
}
\value{(the value of the last evaluated expression).}
\details{
  If \code{lib.loc} is not specified, the packages are searched for
  amongst those already loaded, then in the specified libraries.
  If \code{lib.loc} is specified, they are searched for only
  in the specified libraries, even if they are already loaded from
  another library.

  An attempt is made to load the package before running the examples,
  but this will not replace a package loaded from another location.

  If \code{local=TRUE} objects are not created in the workspace and so
  not available for examination after \code{example} completes: on the
  other hand they cannot clobber objects of the same name in the
  workspace.

  As detailed in the manual \emph{Writing \R Extensions}, the author of
  the help page can markup parts of the examples for two exception rules
  \describe{
    \item{\code{dontrun}}{encloses code that should not be run.}
    \item{\code{dontshow}}{encloses code that is invisible on help
      pages, but will be run both by the package checking tools,
      and the \code{example()} function.  This was previously
      \code{testonly}, and that form is still accepted.}
    }
}
\note{
  The examples can be many small files.  On some file systems it is
  desirable to save space, and the files in the \file{R-ex} directory
  of an installed package can be zipped up as a zip archive
  \file{Rex.zip}.
}
\author{Martin Maechler and others}
\seealso{\code{\link{demo}}}
\examples{
example(InsectSprays)
## force use of the standard package 'eda':
example("smooth", package="eda", lib.loc=.Library)
}
\keyword{documentation}
\keyword{utilities}
\eof
\name{exists}
\title{Is an Object Defined?}
\usage{
exists(x, where = -1, envir = , frame, mode = "any", inherits = TRUE)
}
\alias{exists}
\arguments{
  \item{x}{a variable name (given as a character string).}
  \item{where}{where to look for the object (see the details section); if
    omitted, the function will search, as if the name of the object
    appeared in unquoted in an expression.}
  \item{envir}{an alternative way to specify an environment to look in,
    but it's usually simpler to just use the \code{where} argument.}
  \item{frame}{a frame in the calling list.  Equivalent to giving \code{where}
    as \code{sys.frame(frame)}.}
  \item{mode}{the mode of object sought.}
  \item{inherits}{should the enclosing frames of the environment be inspected.}
}
\description{
  Search for an \R object of the given name on the search path.
}
\value{
  Logical, true if and only if the object is found on the search path.
}
\details{
  The \code{where} argument can specify the  environment in which to look
  for the object in any of several ways:
  as an integer (the position in the \code{\link{search}} list); as
  the character string name of an element in the search list; or as an
  \code{\link{environment}} (including using \code{\link{sys.frame}} to
  access the currently active function calls).
  The \code{envir} argument is an alternative way to specify an
  environment, but is primarily there for back compatibility.

  This function looks to see if the name \code{x} has a value bound to it.
  If \code{inherits} is \code{TRUE} and a value is not found for \code{x},
  then the parent frames of the environment are searched until the name
  \code{x} is encountered.  \bold{Warning:} This is the default behaviour
  for \R but not for S.

  If \code{mode} is specified then only objects of that mode are sought.
  The function returns \code{TRUE} if the variable is encountered and
  \code{FALSE} if not.

  The \code{mode} includes collections such as \code{"numeric"} and
  \code{"function"}: any member of the collection will suffice.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{get}}.
}
\examples{
##  Define a substitute function if necessary:
if(!exists("some.fun", mode="function"))
 some.fun <- function(x) { cat("some.fun(x)\n"); x }
search()
exists("ls", 2) # true even though ls is in pos=3
exists("ls", 2, inherits=FALSE) # false
}
\keyword{data}
\eof
\name{expand.grid}
\title{Create a Data Frame from All Combinations of Factors}
\usage{
expand.grid(\dots)
}
\alias{expand.grid}
\arguments{
  \item{\dots}{Vectors, factors or a list containing these. }
}
\description{
  Create a data frame from all combinations of the supplied vectors or
  factors. See the description of the return value for precise details of
  the way this is done.
}
\value{
  A data frame containing one row for each combination of the supplied
  factors. The first factors vary fastest. The columns are labelled by
  the factors if these are supplied as named arguments or named
  components of a list.
}

\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S.}
  Wadsworth \& Brooks/Cole.
}
\examples{
expand.grid(height = seq(60, 80, 5), weight = seq(100, 300, 50),
            sex = c("Male","Female"))
}
\keyword{models}
\keyword{array}
\eof
\name{expand.model.frame}
\alias{expand.model.frame}
\title{Add new variables to a model frame}
\description{
  Evaluates new variables as if they had been part of the formula of the
  specified model.  This ensures that the same \code{na.action} and
  \code{subset} arguments are applied and allows, for example, \code{x}
  to be recovered for a model using \code{sin(x)} as a predictor.
}
\usage{
expand.model.frame(model, extras, envir=environment(formula(model)),
                   na.expand = FALSE)
}
\arguments{
  \item{model}{a fitted model}
  \item{extras}{one-sided formula or vector of character strings
    describing new variables to be added}
  \item{envir}{an environment to evaluate things in}
  \item{na.expand}{logical; see below}
}
\details{
  If \code{na.expand=FALSE} then \code{NA} values in the extra variables
  will be passed to the \code{na.action} function used in
  \code{model}.  This may result in a shorter data frame (with
  \code{\link{na.omit}}) or an error (with \code{\link{na.fail}}).  If
  \code{na.expand=TRUE} the returned data frame will have precisely the
  same rows as \code{model.frame(model)}, but the columns corresponding to
  the extra variables may contain \code{NA}.
}
\value{
  A data frame.
}
\seealso{\code{\link{model.frame}},\code{\link{predict}}}

\examples{
data(trees)
model <- lm(log(Volume) ~ log(Girth) + log(Height), data=trees)
expand.model.frame(model, ~ Girth) # prints data.frame like

dd <- data.frame(x=1:5, y=rnorm(5), z=c(1,2,NA,4,5))
model <- glm(y ~ x, data=dd, subset=1:4, na.action=na.omit)
expand.model.frame(model, "z", na.expand=FALSE) # = default
expand.model.frame(model, "z", na.expand=TRUE)
}
\keyword{manip}
\keyword{regression}
\eof
\name{expression}
\alias{expression}
\alias{is.expression}
\alias{as.expression}
\alias{as.expression.default}
\title{Unevaluated Expressions}
\description{
  Creates or tests for objects of mode \code{"expression"}.
}
\usage{
expression(\dots)

is.expression(x)
as.expression(x, \dots)
}
\arguments{
  \item{\dots}{valid \R expressions.}
  \item{x}{an arbitrary \R object.}
}
\value{
  \code{expression} returns a vector of mode \code{"expression"}
  containing its arguments as unevaluated \dQuote{\link{call}s}.

  \code{is.expression} returns \code{TRUE} if \code{expr} is an
  expression object and \code{FALSE} otherwise.

  \code{as.expression} attempts to coerce its argument into an
  expression object.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{call}},
  \code{\link{eval}},
  \code{\link{function}}.
  Further,
  \code{\link{text}} and
  \code{\link{legend}}
  for plotting math expressions.
}
\examples{
length(ex1 <- expression(1+ 0:9))# 1
ex1
eval(ex1)# 1:10

length(ex3 <- expression(u,v, 1+ 0:9))# 3
mode(ex3 [3]) # expression
mode(ex3[[3]])# call
rm(ex3)
}
\keyword{programming}
\keyword{dplot}
\eof
%-- This page by Martin Maechler,  improvements welcome!
\name{extractAIC}
\title{Extract AIC from a Fitted Model}
%
\alias{extractAIC}
\alias{extractAIC.aov}  
\alias{extractAIC.lm}
\alias{extractAIC.glm}    
\alias{extractAIC.coxph}  
\alias{extractAIC.negbin}
\alias{extractAIC.survreg}
\usage{
extractAIC(fit, scale,     k = 2, \dots)  
}
\arguments{
  \item{fit}{fitted model, usually the result of a fitter like
    \code{\link{lm}}.}
 \item{scale}{optional numeric specifying the scale parameter of the
   model, see \code{scale} in \code{\link{step}}.
 }
 \item{k}{numeric specifying the \dQuote{weight} of the
   \emph{equivalent degrees of freedom} (\eqn{\equiv}{=:}\code{edf})
   part in the AIC formula.}
 \item{\dots}{further arguments (currently unused in base \R).}
}
%-- Source in ../R/add.R
\description{
  Computes the (generalized) Akaike \bold{A}n \bold{I}nformation
  \bold{C}riterion for a fitted parametric model.
}
\details{
  This is a generic function, with methods in base \R for \code{"aov"},
  \code{"coxph"}, \code{"glm"}, \code{"lm"}, \code{"negbin"}
  and \code{"survreg"} classes.
  
  The criterion used is 
 \deqn{AIC = - 2\log L +  k \times \mbox{edf},}{AIC = - 2*log L +  k * edf,}
  where \eqn{L} is the likelihood
  and \code{edf} the equivalent degrees of freedom (i.e., the number of
  parameters for usual parametric models) of \code{fit}.
 
  For linear models with unknown scale (i.e., for \code{\link{lm}} and
  \code{\link{aov}}), \eqn{-2\log L} is computed from the
  \emph{deviance} and uses a different additive constant to \code{\link{AIC}}.
      
  \code{k = 2} corresponds to the traditional AIC, using \code{k =
    log(n)} provides the BIC (Bayes IC) instead.
  
  For further information, particularly about \code{scale}, see
  \code{\link{step}}.
}
\note{
  These functions are used in \code{\link{add1}},
  \code{\link{drop1}} and \code{\link{step}} and that may be their
  main use.
}
\value{
  A numeric vector of length 2, giving

  \item{edf}{the \dQuote{\bold{e}quivalent \bold{d}egrees of \bold{f}reedom}
  of the fitted model \code{fit}.}

\item{AIC}{the (generalized) Akaike Information Criterion for \code{fit}.}
}
%-- Source in ../R/add.R
\author{B. D. Ripley}
\references{
  Venables, W. N. and Ripley, B. D. (2002)
  \emph{Modern Applied Statistics with S.}
  New York: Springer (4th ed).
}
\seealso{
  \code{\link{AIC}}, \code{\link{deviance}}, \code{\link{add1}},
  \code{\link{step}}
}
\examples{
example(glm)
extractAIC(glm.D93)#>>  5  15.129
}
\keyword{models}

\eof
\name{factor}
\title{Factors}
\alias{factor}
\alias{ordered}
\alias{is.factor}
\alias{is.ordered}
\alias{as.factor}
\alias{as.ordered}
\alias{is.na<-.factor}
\concept{categorical variable}
\description{
  The function \code{factor} is used to encode a vector as a factor (the
  names category and enumerated type are also used for factors).  If
  \code{ordered} is \code{TRUE}, the factor levels are assumed to be ordered.
  For compatibility with S there is also a function \code{ordered}.

  \code{is.factor}, \code{is.ordered}, \code{as.factor} and \code{as.ordered}
  are the membership and coercion functions for these classes.
}
\usage{
factor(x, levels = sort(unique.default(x), na.last = TRUE),
       labels = levels, exclude = NA, ordered = is.ordered(x))
ordered(x, \dots)

is.factor(x)
is.ordered(x)

as.factor(x)
as.ordered(x)
}
\arguments{
  \item{x}{a vector of data, usually taking a small number of distinct values}
  \item{levels}{an optional vector of the values that \code{x} might
    have taken. The default is the set of values taken by \code{x},
    sorted into increasing order.}
  \item{labels}{\emph{either} an optional vector of labels for the
    levels (in the same order as \code{levels} after removing those in
    \code{exclude}), \emph{or} a character string of length 1.}
  \item{exclude}{a vector of values to be excluded when forming the
    set of levels. This should be of the same type as \code{x}, and
    will be coerced if necessary.}
  \item{ordered}{logical flag to determine if the levels should be regarded
    as ordered (in the order given).}
  \item{\dots}{(in \code{ordered(.)}): any of the above, apart from
    \code{ordered} itself.}
}
\value{
  \code{factor} returns an object of class \code{"factor"} which has a
  set of numeric codes the length of \code{x} with a \code{"levels"}
  attribute of mode \code{\link{character}}.  If \code{ordered} is true
  (or \code{ordered} is used) the result has class
  \code{c("ordered", "factor")}.

  Applying \code{factor} to an ordered or unordered factor returns a
  factor (of the same type) with just the levels which occur: see also
  \code{\link{[.factor}} for a more transparent way to achieve this.

  \code{is.factor} returns \code{TRUE} or \code{FALSE} depending on
  whether its argument is of type factor or not.  Correspondingly,
  \code{is.ordered} returns \code{TRUE} when its
  argument is ordered and \code{FALSE} otherwise.

  \code{as.factor} coerces its argument to a factor.
  It is an abbreviated form of \code{factor}.

  \code{as.ordered(x)} returns \code{x} if this is ordered, and
  \code{ordered(x)} otherwise.
}
\details{
  The type of the vector \code{x} is not restricted.

  Ordered factors differ from factors only in their class, but methods
  and the model-fitting functions treat the two classes quite differently.

  The encoding of the vector happens as follows. First all the values
  in \code{exclude} are removed from \code{levels}. If \code{x[i]} equals
  \code{levels[j]}, then the \code{i}-th element of the result is
  \code{j}.  If no match is found for \code{x[i]} in \code{levels},
  then the \code{i}-th element of the result is set to \code{\link{NA}}.

  Normally the \sQuote{levels} used as an attribute of the result are
  the reduced set of levels after removing those in \code{exclude}, but
  this can be altered by supplying \code{labels}. This should either
  be a set of new labels for the levels, or a character string, in
  which case the levels are that character string with a sequence
  number appended.

  \code{factor(x, exclude=NULL)} applied to a factor is a no-operation
  unless there are unused levels: in that case, a factor with the
  reduced level set is returned.  If \code{exclude} is used it should
  also be a factor with the same level set as \code{x} or a set of codes
  for the levels to be excluded.

  The codes of a factor may contain \code{\link{NA}}. For a numeric
  \code{x}, set \code{exclude=NULL} to make \code{\link{NA}} an extra
  level (\code{"NA"}), by default the last level.

  If \code{"NA"} is a level, the way to set a code to be missing is to
  use \code{\link{is.na}} on the left-hand-side of an assignment.
  Under those circumstances missing values are printed as \code{<NA>}.

  \code{is.factor} is generic: you can write methods to handle
  of specific classes of objects, see \link{InternalMethods}.
}
\section{Warning}{
  The interpretation of a factor depends on both the codes and the
  \code{"levels"} attribute.  Be careful only to compare factors with
  the same set of levels (in the same order).  In particular,
  \code{as.numeric} applied to a factor is meaningless, and may
  happen by implicit coercion.	To \dQuote{revert} a factor \code{f} to
  its original numeric values, \code{as.numeric(levels(f))[f]} is
  recommended and slightly more efficient than
  \code{as.numeric(as.character(f))}.

  The levels of a factor are by default sorted, but the sort order
  may well depend on the locale at the time of creation, and should
  not be assumed to be ASCII.
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{[.factor}} for subsetting of factors.

  \code{\link{gl}} for construction of \dQuote{balanced} factors and
  \code{\link{C}} for factors with specified contrasts.
  \code{\link{levels}} and \code{\link{nlevels}} for accessing the
  levels, and \code{\link{codes}} to get integer codes.
}
\examples{
(ff <- factor(substring("statistics", 1:10, 1:10), levels=letters))
as.integer(ff) # the internal codes
factor(ff)	# drops the levels that do not occur
ff[, drop=TRUE] # the same, more transparently

factor(letters[1:20], label="letter")

class(ordered(4:1))# "ordered", inheriting from "factor"

## suppose you want "NA" as a level, and to allowing missing values.
(x <- factor(c(1, 2, "NA"), exclude = ""))
is.na(x)[2] <- TRUE
x  # [1] 1    <NA> NA, <NA> used because NA is a level.
is.na(x)
# [1] FALSE  TRUE FALSE
}
\keyword{category}
\keyword{NA}
\eof
\name{factor.scope}
\title{Compute Allowed Changes in Adding to or Dropping from a Formula}
\usage{
add.scope(terms1, terms2)
drop.scope(terms1, terms2)
factor.scope(factor, scope)
}
\alias{add.scope}
\alias{drop.scope}
\alias{factor.scope}
\arguments{
 \item{terms1}{the terms or formula for the base model.}
 \item{terms2}{the terms or formula for the upper (\code{add.scope}) or
   lower (\code{drop.scope}) scope. If missing for \code{drop.scope} it is
   taken to be the null formula, so all terms (except any intercept) are
   candidates to be dropped.}
 \item{factor}{the \code{"factor"} attribute of the terms of the base object.}
 \item{scope}{a list with one or both components \code{drop} and
   \code{add} giving the \code{"factor"} attribute of the lower and
   upper scopes respectively.}
}
\description{
 \code{add.scope} and \code{drop.scope} compute those terms that can be
 individually added to or dropped from a model while respecting the
 hierarchy of terms.
}
\details{
 \code{factor.scope} is not intended to be called directly by users.
}
\value{
  For \code{add.scope} and \code{drop.scope} a character vector of
  terms labels. For \code{factor.scope}, a list with components
  \code{drop} and \code{add}, character vectors of terms labels.
}

\seealso{\code{\link{add1}}, \code{\link{drop1}},
  \code{\link{aov}}, \code{\link{lm}}}

\examples{
add.scope( ~ a + b + c + a:b,  ~ (a + b + c)^3)
# [1] "a:c" "b:c"
drop.scope( ~ a + b + c + a:b)
# [1] "c"   "a:b"
}
\keyword{models}
\eof
\name{faithful}
\docType{data}
\alias{faithful}
\title{Old Faithful Geyser Data}
\description{
  Waiting time between eruptions and the duration of the eruption for
  the Old Faithful geyser in Yellowstone National Park, Wyoming, USA.
}
\usage{data(faithful)}
\format{A data frame with 272 observations on 2 variables.
  \tabular{rlll}{
    [,1]  \tab eruptions  \tab numeric  \tab Eruption time in mins \cr
    [,2]  \tab waiting    \tab numeric  \tab Waiting time to next
    eruption \cr
  }
}
\source{W. Härdle.}
\references{
  Härdle, W. (1991)
  \emph{Smoothing Techniques with Implementation in S}.
  New York: Springer.

  Azzalini, A. and Bowman, A. W. (1990).
  A look at some data on the Old Faithful geyser.
  \emph{Applied Statistics} \bold{39}, 357--365.
}
\details{
  A closer look at \code{faithful$eruptions} reveals that these are
  heavily rounded times originally in seconds, where multiples of 5 are
  more frequent than expected under non-human measurement.  For a
  \dQuote{better} version of the eruptions times, see the example below.

  There are many versions of this dataset around: Azzalini and Bowman
  (1990) use a more complete version.
}
\seealso{
  \code{geyser} in package \pkg{MASS} for the Azzalini-Bowman version.
}
\examples{
data(faithful)
f.tit <-  "faithful data: Eruptions of Old Faithful"

ne60 <- round(e60 <- 60 * faithful$eruptions)
all.equal(e60, ne60)             # relative diff. ~ 1/10000
table(zapsmall(abs(e60 - ne60))) # 0, 0.02 or 0.04
faithful$better.eruptions <- ne60 / 60
te <- table(ne60)
te[te >= 4]                      # (too) many multiples of 5 !
plot(names(te), te, type="h", main = f.tit, xlab = "Eruption time (sec)")

plot(faithful[, -3], main = f.tit,
     xlab = "Eruption time (min)",
     ylab = "Waiting time to next eruption (min)")
lines(lowess(faithful$eruptions, faithful$waiting, f = 2/3, iter = 3),
      col = "red")
}
\keyword{datasets}
\eof
\name{family}
\title{Family Objects for Models}
\usage{
family(object, \dots)

binomial(link = "logit")
gaussian(link ="identity")
Gamma(link = "inverse")
inverse.gaussian(link = "1/mu^2")
poisson(link = "log")
quasi(link = "identity", variance = "constant")
quasibinomial(link = "logit")
quasipoisson(link = "log")
}
\alias{family}
\alias{binomial}
\alias{gaussian}
\alias{Gamma}
\alias{inverse.gaussian}
\alias{poisson}
\alias{quasi}
\alias{quasibinomial}
\alias{quasipoisson}
\alias{print.family}
\arguments{
  \item{link}{a specification for the model link function.
    The \code{gaussian} family accepts the links \code{"identity"},
    \code{"log"} and \code{"inverse"};
    the \code{binomial} family the links \code{"logit"},
    \code{"probit"}, \code{"log"} and \code{"cloglog"} (complementary
    log-log);
    the \code{Gamma} family the links \code{"inverse"}, \code{"identity"}
     and \code{"log"};
    the \code{poisson} family the links \code{"log"}, \code{"identity"}, 
    and \code{"sqrt"} and the \code{inverse.gaussian} family the links
    \code{"1/mu^2"}, \code{"inverse"}, \code{"inverse"} and \code{"log"}.
    
    The \code{quasi} family allows the links \code{"logit"}, \code{"probit"},
    \code{"cloglog"},  \code{"identity"}, \code{"inverse"},
    \code{"log"}, \code{"1/mu^2"} and \code{"sqrt"}.
    The function \code{\link{power}} can also be used to create a
    power link function for the \code{quasi} family.
  }
  \item{variance}{for all families, other than \code{quasi}, the
    variance function is determined by the family.  The \code{quasi}
    family will accept the specifications \code{"constant"},
    \code{"mu(1-mu)"}, \code{"mu"}, \code{"mu^2"} and \code{"mu^3"} for
    the variance function.}
  \item{object}{the function \code{family} accesses the \code{family}
    objects which are stored within objects created by modelling
    functions (e.g., \code{glm}).}
  \item{\dots}{further arguments passed to methods.}
}
\description{
  Family objects provide a convenient way to specify the details of the
  models used by functions such as \code{\link{glm}}.  See the
  documentation for \code{\link{glm}} for the details on how such model
  fitting takes place.
}
\details{
  The \code{quasibinomial} and \code{quasipoisson} families differ from
  the \code{binomial} and \code{poisson} families only in that the
  dispersion parameter is not fixed at one, so they can \dQuote{model}
  over-dispersion.  For the binomial case see McCullagh and Nelder
  (1989, pp. 124--8).  Although they show that there is (under some
  restrictions) a model with
  variance proportional to mean as in the quasi-binomial model, note
  that \code{glm} does not compute maximum-likelihood estimates in that
  model.  The behaviour of S is closer to the quasi- variants. 
}
\references{
  McCullagh P. and Nelder, J. A. (1989)
  \emph{Generalized Linear Models.}
  London: Chapman and Hall.

  Dobson, A. J. (1983)
  \emph{An Introduction to Statistical Modelling.}
  London: Chapman and Hall.

  Cox, D. R. and  Snell, E. J. (1981).
  \emph{Applied Statistics; Principles and Examples.}
  London: Chapman and Hall.

  Hastie, T. J. and Pregibon, D. (1992)
  \emph{Generalized linear models.}
  Chapter 6 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\author{
  The design was inspired by S functions of the same names described
  in Hastie \& Pregibon (1992).
}
\seealso{
  \code{\link{glm}}, \code{\link{power}}.
}
\examples{
nf <- gaussian()# Normal family
nf
str(nf)# internal STRucture

gf <- Gamma()
gf
str(gf)
gf$linkinv
gf$variance(-3:4) #- == (.)^2

## quasipoisson. compare with example(glm)
counts <- c(18,17,15,20,10,20,25,13,12)
outcome <- gl(3,1,9)
treatment <- gl(3,3)
d.AD <- data.frame(treatment, outcome, counts)
glm.qD93 <- glm(counts ~ outcome + treatment, family=quasipoisson())
glm.qD93
anova(glm.qD93, test="F")
summary(glm.qD93)
## for Poisson results use
anova(glm.qD93, dispersion = 1, test="Chisq")
summary(glm.qD93, dispersion = 1)


## tests of quasi
x <- rnorm(100)
y <- rpois(100, exp(1+x))
glm(y ~x, family=quasi(var="mu", link="log"))
# which is the same as
glm(y ~x, family=poisson)
glm(y ~x, family=quasi(var="mu^2", link="log"))
\dontrun{glm(y ~x, family=quasi(var="mu^3", link="log")) # should fail}
y <- rbinom(100, 1, plogis(x))
# needs to set a starting value for the next fit
glm(y ~x, family=quasi(var="mu(1-mu)", link="logit"), start=c(0,1))
}
\keyword{models}
\eof
\name{fft}
\alias{fft}
\alias{mvfft}
\title{Fast Discrete Fourier Transform}
\description{
  Performs the Fast Fourier Transform of an array.
}
\usage{
fft(z, inverse = FALSE)
mvfft(z, inverse = FALSE)
}
\arguments{
  \item{z}{a real or complex array containing the values to be
    transformed.}
  \item{inverse}{if \code{TRUE}, the unnormalized inverse transform is
    computed (the inverse has a \code{+} in the exponent of \eqn{e},
    but here, we do \emph{not} divide by \code{1/length(x)}).}
}
\value{
  When \code{z} is a vector, the value computed and returned by
  \code{fft} is the unnormalized univariate Fourier transform of the
  sequence of values in \code{z}.
  %%
  %% Here, we should really have a nice  \deqn{}{} giving the definition
  %% of the DFT !
  %%
  When \code{z} contains an array, \code{fft} computes and returns the
  multivariate (spatial) transform.  If \code{inverse} is \code{TRUE},
  the (unnormalized) inverse Fourier transform is returned, i.e.,
  if \code{y <- fft(z)}, then \code{z} is
  \code{fft(y, inverse = TRUE) / length(y)}.

  By contrast, \code{mvfft} takes a real or complex matrix as argument,
  and returns a similar shaped matrix, but with each column replaced by
  its discrete Fourier transform.  This is useful for analyzing
  vector-valued series.

  The FFT is fastest when the length of of the series being transformed
  is highly composite (i.e., has many factors).  If this is not the
  case, the transform may take a long time to compute and will use a
  large amount of memory.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Singleton, R. C. (1979)
  Mixed Radix Fast Fourier Transforms,
  in \emph{Programs for Digital Signal Processing},
  IEEE Digital Signal Processing Committee eds.
  IEEE Press.
}
\seealso{
  \code{\link{convolve}}, \code{\link{nextn}}.
}
\examples{
x <- 1:4
fft(x)
fft(fft(x), inverse = TRUE)/length(x)
}
\keyword{math}
\keyword{dplot}
\eof
\name{file.access}
\alias{file.access}
\title{Ascertain File Accessibility}
\description{
  Utility function to access information about files on the user's
  file systems.
}
\usage{
file.access(names, mode = 0)
}
\arguments{
  \item{names}{character vector containing file names.}
  \item{mode}{integer specifying access mode required.}
}
\details{
  The \code{mode} value can be the exclusive or of the following values
  \describe{
    \item{0}{test for existence.}
    \item{1}{test for execute permission.}
    \item{2}{test for write permission.}
    \item{4}{test for read permission.}
  }
#ifdef unix
Permission will be computed for real user ID and real group ID (rather
than the effective IDs).
#endif
#ifdef windows
Execute permission is ignored (always granted) under Windows, and all
directories have both read and write permissions.
#endif
}
\value{
  An integer vector with values \code{0} for success and \code{-1} for failure.
}

\note{
  This is intended as a replacement for the S-PLUS function
  \code{access}, a wrapper for the C function of the same name, which
  explains the return value encoding.  Note that
  the return value is \bold{false} for \bold{success}.
}

\seealso{\code{\link{file.info}}}

\examples{
fa <- file.access(dir("."))
table(fa) # count successes & failures
}
\keyword{file}
\eof
\name{file.choose}
\alias{file.choose}
\title{Choose a File Interactively}
\description{
 Choose a file interactively.
}
\usage{
file.choose(new = FALSE)
}
\arguments{
 \item{new}{Logical: choose the style of dialog box
     presented to the user: at present only new = FALSE is used.}
}
\value{
  A character vector of length one giving the file path.
}
\keyword{file}
\eof
\name{file.info}
\alias{file.info}
\title{Extract File Information}
\description{
  Utility function to extract information about files on the user's
  file systems.
}
\usage{
file.info(\dots)
}
\arguments{
  \item{\dots}{character vectors containing file names.}
}
\details{
  What is meant by \dQuote{file access} and hence the last access time
  is system-dependent.

#ifdef unix
  On most systems symbolic links are followed, so information is given
  about the file to which the link points rather than about the link.
#endif
#ifdef windows
  File modes are probably only useful on Windows NT/2000 machines.
#endif
}
\value{
  A data frame with row names the file names and columns
  \item{size}{integer: File size in bytes.}
  \item{isdir}{logical: Is the file a directory?}
  \item{mode}{integer of class \code{"octmode"}.  The file permissions,
    printed in octal, for example \code{644}.}
  \item{mtime, ctime, atime}{integer of class \code{"POSIXct"}:
    file modification, creation and last access times.}
#ifdef unix
  \item{uid}{integer: the user ID of the file's owner.}
  \item{gid}{integer: the group ID of the file's group.}
  \item{uname}{character: \code{uid} interpreted as a user name.}
  \item{grname}{character: \code{gid} interpreted as a group name.}
  Unknown user and group names will be \code{NA}.
#endif

Entries for non-existent or non-readable files will be \code{NA}.
#ifdef unix
The \code{uid}, \code{gid}, \code{uname} and \code{grname} columns
may not be supplied on a non-POSIX Unix system.
#endif
}
\note{
  This function will only be operational on systems with the
  \code{stat} system call, but that seems very widely available.
}

\seealso{
  \code{\link{files}}, \code{\link{file.access}},
  \code{\link{list.files}},
  and \code{\link{DateTimeClasses}} for the date formats.
}
\examples{
%-- the output of this should be "diff"able, says MM: why?
ncol(finf <- file.info(dir()))# at least six
\dontrun{finf # the whole list}
## Those that are more than 100 days old :
finf[difftime(Sys.time(), finf[,"mtime"], units="days") > 100 , 1:4]

file.info("no-such-file-exists")
}
\keyword{file}
\eof
\name{file.path}
\alias{file.path}
\title{Construct Path to File}
\description{
  Construct the path to a file from components in a platform-independent
  way.
}
\usage{
file.path(\dots, fsep = .Platform$file.sep)
}
\arguments{
  \item{\dots}{character vectors.}
  \item{fsep}{the path separator to use.}
}
\value{
  A character vector of the arguments concatenated term-by-term and
  separated by \code{fsep} if all arguments have positive length;
  otherwise, an empty character vector.
}
\keyword{file}
\eof
\name{file.show}
\alias{file.show}
\title{Display One or More Files}
\description{Display one or more files.}
\usage{
file.show(\dots, header = rep("",nfiles), title = "R Information",
          delete.file=FALSE, pager=getOption("pager"))
}
\arguments{
  \item{\dots}{one or more character vectors containing the names of the
    files to be displayed.}
  \item{header}{character vector (of the same length as the number of files
    specified in \code{\dots}) giving a header for each file being
    displayed.  Defaults to empty strings.}
  \item{title}{an overall title for the display.  If a single separate
    window is used for the display, \code{title} will be used as the window
    title. If multiple windows are used, their titles should combine the title
    and the file-specific header.}
  \item{delete.file}{should the files be deleted after display?  Used
    for temporary files.}
  \item{pager}{the pager to be used.}
}
\details{
  This function provides the core of the R help system, but it can be
  used for other purposes as well.
}
\note{
  How the pager is implemented is highly system dependent.

  The basic Unix version concatenates the files (using the headers) to a
  temporary file, and displays it in the
  pager selected by the \code{pager} argument, which is a character
  vector specifying a system command to run on the set of files.

  Most GUI systems will use a separate pager window for each file,
  and let the user leave it up while \R
  continues running.  The selection of such pagers could either be done
  using \dQuote{magic} pager names being intercepted by lower-level code
  (such as \code{"internal"} and \code{"console"} on Windows), or
  by letting \code{pager} be an R function which will be called with the
  same arguments as \code{file.show} and take care of interfacing to the
  GUI.

  Not all implementations will honour \code{delete.file}.
#ifdef windows
  In particular, using an external pager on Windows does not, as there
  is no way to know when the external application has finished with
  the file.
#endif
}
\author{Ross Ihaka, Brian Ripley.}
\seealso{
  \code{\link{files}},
  \code{\link{list.files}},
  \code{\link{help}}.
}
\examples{
file.show(file.path(R.home(), "COPYRIGHTS"))
}
\keyword{file}
\eof
\name{files}
\alias{files}
\title{File Manipulation}
\usage{
file.create(\dots)
file.exists(\dots)
file.remove(\dots)
file.rename(from, to)
file.append(file1, file2)
file.copy(from, to, overwrite = FALSE)
file.symlink(from, to)
dir.create(path)
}
\alias{file.append}
\alias{file.copy}
\alias{file.create}
\alias{file.exists}
\alias{file.remove}
\alias{file.rename}
\alias{file.symlink}
\alias{dir.create}
\arguments{
  \item{\dots, file1, file2, from, to}{character vectors,
    containing file names.}
  \item{path}{a character vector containing a single path name.}
  \item{overwrite}{logical; should the destination files be overwritten?}
}
\description{
  These functions provide a low-level interface to the computer's
  file system.
}
\details{
  The \code{\dots} arguments are concatenated to form one character
  string: you can specify the files separately or as one vector.
  All of these functions expand path names: see \code{\link{path.expand}}.

  \code{file.create} creates files with the given names if they
  do not already exist and truncates them if they do.

  \code{file.exists} returns a logical vector indicating whether
  the files named by its argument exist.

  \code{file.remove} attempts to remove the files named in its
  argument.

  \code{file.rename} attempts to rename a single file.
#ifdef windows
  On Windows 9x/ME rename is not atomic, so it is possible that
  \code{to} will be deleted but \code{from} will not be renamed.
#endif

  \code{file.append} attempts to append the files named by its
  second argument to those named by its first.  The \R subscript
  recycling rule is used to align names given in vectors
  of different lengths.

  \code{file.copy} works in a similar way to \code{file.append} but with
  the arguments in the natural order for copying. Copying to existing
  destination files is skipped unless \code{overwrite = TRUE}.
  The \code{to} argument can specify a single existing directory.

  \code{file.symlink} makes symbolic links on those Unix-like platforms
  which support them.  The \code{to} argument can specify a single
  existing directory.
  
  \code{dir.create} creates the last element of the path.
}
\value{
  \code{dir.create} and \code{file.rename} return a logical,
  true for success.

  The remaining functions return a logical vector indicating which
  operation succeeded for each of the files attempted.
}
\author{
  Ross Ihaka, Brian Ripley
}
\seealso{
  \code{\link{file.info}}, \code{\link{file.access}}, \code{\link{file.path}},
  \code{\link{file.show}}, \code{\link{list.files}},
  \code{\link{unlink}}, \code{\link{basename}}, \code{\link{path.expand}}.
}

\examples{
cat("file A\n", file="A")
cat("file B\n", file="B")
file.append("A", "B")
file.create("A")
file.append("A", rep("B", 10))
if(interactive()) file.show("A")
file.copy("A", "C")
dir.create("tmp")
file.copy(c("A", "B"), "tmp")
list.files("tmp")
#ifdef unix
setwd("tmp")
file.remove("B")
file.symlink(file.path("..", c("A", "B")), ".")
setwd("..")
#endif
unlink("tmp", recursive=TRUE)
file.remove("A", "B", "C")
}
\keyword{file}
\eof
\name{filled.contour}
\alias{filled.contour}
\title{Level (Contour) Plots}
\usage{
filled.contour(x = seq(0, 1, len = nrow(z)),
               y = seq(0, 1, len = ncol(z)),
               z,
               xlim = range(x, finite=TRUE),
               ylim = range(y, finite=TRUE),
               zlim = range(z, finite=TRUE),
               levels = pretty(zlim, nlevels), nlevels = 20,
               color.palette = cm.colors,
               col = color.palette(length(levels) - 1),
               plot.title, plot.axes, key.title, key.axes,
               asp = NA, xaxs = "i", yaxs = "i", las = 1,
               axes = TRUE, frame.plot = axes, \dots)
}
\arguments{
 \item{x,y}{locations of grid lines at which the values in \code{z} are
    measured.  These must be in ascending order.  By default, equally
    spaced values from 0 to 1 are used.  If \code{x} is a \code{list},
    its components \code{x$x} and \code{x$y} are used for \code{x}
    and \code{y}, respectively. If the list has component \code{z} this
    is used for \code{z}.}
 \item{z}{a matrix containing the values to be plotted (\code{NA}s are
    allowed).  Note that \code{x} can be used instead of \code{z} for
    convenience.}
 \item{xlim}{x limits for the plot.}
 \item{ylim}{y limits for the plot.}
 \item{zlim}{z limits for the plot.}
 \item{levels}{a set of levels which are used to partition the range
    of \code{z}.  Must be \bold{strictly} increasing (and finite).  Areas
    with \code{z} values between consecutive levels are painted with the
    same color.}
 \item{nlevels}{if \code{levels} is not specified, the range of \code{z},
    values is divided into approximately this many levels.}
 \item{color.palette}{a color palette function to be used to assign
    colors in the plot.}
 \item{col}{an explicit set of colors to be used in the plot.
    This argument overrides any palette function specification.}
 \item{plot.title}{statements which add titles the main plot.}
 \item{plot.axes}{statements which draw axes (and a \code{\link{box}})
   on the main plot.  This overrides the default axes.}
 \item{key.title}{statements which add titles for the plot key.}
 \item{key.axes}{statements which draw axes on the plot key.
    This overrides the default axis.}
 \item{asp}{the \eqn{y/x} aspect ratio, see \code{\link{plot.window}}.}
 \item{xaxs}{the x axis style.  The default is to use internal
    labeling.}
 \item{yaxs}{the y axis style.  The default is to use internal
    labeling.}
 \item{las}{the style of labeling to be used.  The default is to
    use horizontal labeling. }
 \item{axes, frame.plot}{logicals indicating if axes and a box should be
   drawn, as in \code{\link{plot.default}}.}
 \item{\dots}{additional graphical parameters, currently only passed to
   \code{\link{title}()}.}
}
\description{
  This function produces a contour plot with the areas between the
  contours filled in solid color (Cleveland calls this a level plot).  A
  key showing how the colors map to z values is shown to the right of
  the plot.
}
\references{
  Cleveland, W. S. (1993)
  \emph{Visualizing Data}.
  Summit, New Jersey: Hobart.
}
\author{Ross Ihaka.}
\note{
  This function currently uses the \code{layout} function and so is
  restricted to a full page display.  As an alternative consider the
  \code{\link[lattice]{levelplot}} function from the \pkg{lattice}
  package which works in multipanel displays.

  The ouput produced by \code{filled.contour} is actually a combination
  of two plots; one is the filled contour and one is the legend.  Two
  separate coordinate systems are set up for these two plots, but they
  are only used internally - once the function has returned these
  coordinate systems are lost.  If you want to annotate the main contour
  plot, for example to add points, you can specify graphics commands in
  the \code{plot.axes} argument.  An example is given below.
}
\seealso{\code{\link{contour}}, \code{\link{image}},
  \code{\link{palette}}; \code{\link[lattice]{levelplot}} from package
  \pkg{lattice}.}
\examples{
data(volcano)
filled.contour(volcano, color = terrain.colors, asp = 1)# simple

x <- 10*1:nrow(volcano)
y <- 10*1:ncol(volcano)
filled.contour(x, y, volcano, color = terrain.colors,
    plot.title = title(main = "The Topography of Maunga Whau",
    xlab = "Meters North", ylab = "Meters West"),
    plot.axes = { axis(1, seq(100, 800, by = 100))
                  axis(2, seq(100, 600, by = 100)) },
    key.title = title(main="Height\n(meters)"),
    key.axes = axis(4, seq(90, 190, by = 10)))# maybe also asp=1
mtext(paste("filled.contour(.) from", R.version.string),
      side = 1, line = 4, adj = 1, cex = .66)

# Annotating a filled contour plot
a <- expand.grid(1:20, 1:20)
b <- matrix(a[,1] + a[,2], 20)
filled.contour(x = 1:20, y = 1:20, z = b,
               plot.axes={ axis(1); axis(2); points(10,10) })

## Persian Rug Art:
x <- y <- seq(-4*pi, 4*pi, len = 27)
r <- sqrt(outer(x^2, y^2, "+"))
filled.contour(cos(r^2)*exp(-r/(2*pi)), axes = FALSE)
## rather, the key *should* be labeled:
filled.contour(cos(r^2)*exp(-r/(2*pi)), frame.plot = FALSE, plot.axes = {})
}
\keyword{hplot}
\keyword{aplot}
\eof
\name{findInterval}
\alias{findInterval}
\title{Find Interval Numbers or Indices}
\usage{
findInterval(x, vec, rightmost.closed = FALSE, all.inside = FALSE)
}
\arguments{
  \item{x}{numeric.}
  \item{vec}{numeric, sorted (weakly) increasingly, of length \code{N},
    say.}
  \item{rightmost.closed}{logical; if true, the rightmost interval,
    \code{vec[N-1] .. vec[N]} is treated as \emph{closed}, see below.}
  \item{all.inside}{logical; if true, the returned indices are coerced
    into \eqn{\{1,\dots,N-1\}}, i.e., 0 is mapped to 1 and \eqn{N} to
    \eqn{N-1}.}
}
\description{
  Find the indices of \code{x} in \code{vec}, where \code{vec} must be
  sorted (non-decreasingly); i.e., if \code{i <- findInterval(x,v)},
  we have \eqn{v_{i_j} \le x_j < v_{i_j + 1}}{v[i[j]] <= x[j] < v[i[j] + 1]}
  where \eqn{v_0 := -\infty}{v[0] := - Inf},
  \eqn{v_{N+1} := +\infty}{v[N+1] := + Inf}, and \code{N <- length(vec)}.
  At the two boundaries, the returned index may differ by 1, depending
  on the optional arguments \code{rightmost.closed} and \code{all.inside}.
}
\details{
  The function \code{findInterval} finds the index of one vector \code{x} in
  another, \code{vec}, where the latter must be non-decreasing.  Where
  this is trivial, equivalent to \code{apply( outer(x, vec, ">="), 1, sum)},
  as a matter of fact, the internal algorithm uses interval search
  ensuring \eqn{O(n \log N)}{O(n * log(N))} complexity where
  \code{n <- length(x)} (and \code{N <- length(vec)}).  For (almost)
  sorted \code{x}, it will be even faster, basically \eqn{O(n)}.

  This is the same computation as for the empirical distribution
  function, and indeed, \code{findInterval(t, sort(X))} is
  \emph{identical} to \eqn{n F_n(t; X_1,\dots,X_n)}{n * Fn(t;
    X[1],..,X[n])} where \eqn{F_n}{Fn} is the empirical distribution
  function of \eqn{X_1,\dots,X_n}{X[1],..,X[n]}.

  When \code{rightmost.closed = TRUE}, the result
  for \code{x[j] = vec[N]} (\eqn{ = \max(vec)}), is \code{N - 1} as for
  all other values in the last interval.
}
\value{
  vector of length \code{length(x)} with values in \code{0:N} where
  \code{N <- length(vec)}, or values coerced to \code{1:(N-1)} iff
  \code{all.inside = TRUE} (equivalently coercing all x values
  \emph{inside} the intervals).
}
\author{Martin Maechler}
\seealso{\code{\link{approx}(*, method = "constant")} which is a
  generalization of \code{findInterval()}, \code{\link[stepfun]{ecdf}} for
  computing the empirical distribution function which is (up to a factor
  of \eqn{n}) also basically the same as findInterval(.).
}
\examples{
N <- 100
X <- sort(round(rt(N, df=2), 2))
tt <- c(-100, seq(-2,2, len=201), +100)
it <- findInterval(tt, X)
tt[it < 1 | it >= N] # only first and last are outside range(X)
}
\keyword{arith}
\keyword{utilities}
\eof
\name{fitted}
\title{Extract Model Fitted Values}
\usage{
fitted(object, \dots)
fitted.values(object, \dots)
}
\alias{fitted.values}
\alias{fitted}
%%- methods:
\alias{fitted.default}
\alias{fitted.lm}
\alias{fitted.glm}
\arguments{
  \item{object}{an object for which the extraction of model fitted values is
    meaningful.}
  \item{\dots}{other arguments.}
}
\description{
  \code{fitted} is a generic function which extracts fitted values from
  objects returned by modeling functions.  \code{fitted.values} is an
  alias for it.

  All object classes which are returned by model fitting functions
  should provide a \code{fitted} method.  (Note that the generic is
  \code{fitted} and not \code{fitted.values}.)

  Methods can make use of \code{\link{napredict}} methods to compensate
  for the omission of missing values.  The default, \code{lm} and
  \code{glm} methods do.
}
\value{
  Fitted values extracted from the object \code{x}.
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{coefficients}}, \code{\link{glm}}, \code{\link{lm}},
  \code{\link{residuals}}.
}
\keyword{models}
\keyword{regression}
\eof
\name{fivenum}
\alias{fivenum}
\title{Tukey Five-Number Summaries}
\description{
  Returns Tukey's five number summary (minimum, lower-hinge, median,
  upper-hinge, maximum) for the input data.
}
\usage{
fivenum(x, na.rm = TRUE)
}
\arguments{
  \item{x}{numeric, maybe including \code{\link{NA}}s and
    +/-\code{\link{Inf}}s.}
  \item{na.rm}{logical; if \code{TRUE}, all \code{\link{NA}} and
    \code{\link{NaN}}s are dropped, before the statistics are computed.}
}
\value{
  A numeric vector of length 5 containing the summary information.  See
  \code{\link{boxplot.stats}} for more details.
}
\seealso{
  \code{\link{IQR}},
  \code{\link{boxplot.stats}},
  \code{\link{median}},
  \code{\link{quantile}},
  \code{\link{range}}.
}
\examples{
fivenum(c(rnorm(100),-1:1/0))
}
\keyword{univar}
\keyword{robust}
\keyword{distribution}

\eof
\name{fix}
\alias{fix}
\title{Fix an Object}
\description{
  \code{fix} invokes \code{\link{edit}} on \code{x} and then assigns the new
  (edited) version of \code{x} in the user's workspace.
}
\usage{
fix(x, \dots)
}
\arguments{
  \item{x}{the name of an \R object, as a name or a character string.}
  \item{\dots}{arguments to pass to editor: see \code{\link{edit}}.}
}
\details{
  The name supplied as \code{x} need not exist as an \R object, when a
  function with no arguments and an empty body is supplied for editing.
}
\seealso{
  \code{\link{edit}},
  \code{\link{edit.data.frame}}
}
\examples{
\dontrun{
 ## Assume 'my.fun' is a user defined function :
 fix(my.fun)
 ## now my.fun is changed
 ## Also,
 fix(my.data.frame) # calls up data editor
 fix(my.data.frame, factor.mode="char") # use of ...
}}
\keyword{utilities}
\eof
\name{force}
\alias{force}
\title{Force evaluation of an Argument}
\description{
  Forces the evaluation of a function argument.
}
\usage{
force(x)
}
\arguments{
  \item{x}{a formal argument.}
}
\details{
  \code{force} forces the evaluation of a formal argument.  This can
  be useful if the argument will be captured in a closure by the lexical
  scoping rules and will later be altered by an explicit assignment or
  an implicit assignment in a loop or an apply function.
}
\examples{
f <- function(y) function() y
lf <- vector("list", 5)
for (i in seq(along = lf)) lf[[i]] <- f(i)
lf[[1]]()  # returns 5

g <- function(y) { force(y); function() y }
lg <- vector("list", 5)
for (i in seq(along = lg)) lg[[i]] <- g(i)
lg[[1]]()  # returns 1
}
\keyword{data}
\keyword{programming}
\eof
\name{formals}
\alias{formals}
\alias{formals<-}
\title{Access to and Manipulation of the Formal Arguments}
\description{
  Get or set the formal arguments of a function.
}
\usage{
formals(fun = sys.function(sys.parent()))
formals(fun, envir = parent.frame()) <- value
}
\arguments{
  \item{fun}{a function object, or see Details.}
  \item{envir}{environment in which the function should be defined.}
  \item{value}{a list of \R expressions.}
}
\value{
  \code{formals} returns the formal argument list of the function
  specified.

  The assignment form sets the formals of a function to the list on the
  right hand side.
}
\details{
  For the first form, \code{fun} can be a character string
  naming the function to be manipulated, which is searched for from the
  parent environment.
  If it is not specified, the function calling \code{formals} is used.
}
\seealso{
  \code{\link{args}} for a \dQuote{human-readable} version,
  \code{\link{alist}},
  \code{\link{body}},
  \code{\link{function}}.
}
\examples{
length(formals(lm))      # the number of formal arguments
names(formals(boxplot))  # formal arguments names

f <- function(x)a+b
formals(f) <- alist(a=,b=3) # function(a,b=3)a+b
f(2) # result = 5
}
\keyword{programming}
\eof
\name{format}
\title{Encode in a Common Format}
\usage{
format(x, \dots)

\method{format}{AsIs}(x, width = 12, \dots)

\method{format}{data.frame}(x, \dots, justify = "none")

\method{format}{default}(x, trim = FALSE, digits = NULL,
       nsmall = 0, justify = c("left", "right", "none"),
       big.mark = "",   big.interval = 3,
     small.mark = "", small.interval = 5,
   decimal.mark = ".", \dots)

\method{format}{factor}(x, \dots)

format.pval(pv, digits = max(1, getOption("digits") - 2),
            eps = .Machine$double.eps, na.form = "NA")

prettyNum(x, big.mark = "",   big.interval = 3,
           small.mark = "", small.interval = 5,
         decimal.mark = ".", \dots)
}
\alias{format}
\alias{format.AsIs}
\alias{format.data.frame}
\alias{format.default}
\alias{format.factor}
\alias{format.pval}
\alias{prettyNum}
\description{
  Format an \R object for pretty printing: \code{format.pval} is
  intended for formatting p-values.
}
\arguments{
  \item{x}{any \R object (conceptually); typically numeric.}
  \item{trim}{logical; if \code{TRUE}, leading blanks are trimmed off the
    strings.}
  \item{digits}{how many significant digits are to be used for
    \code{\link{numeric} x}.  The default, \code{NULL}, uses
    \code{\link{options}()$digits}.  This is a suggestion: enough decimal
    places will be used so that the smallest (in magnitude) number has
    this many significant digits.}
  \item{nsmall}{number of digits which will always appear to the right of
    the decimal point in formatting real/complex numbers in
    non-scientific formats. Allowed values \code{0 <= nsmall <= 20}.}
  \item{justify}{should character vector be left-justified,
    right-justified or left alone.  When justifying, the field width is
    that of the longest string.}

  \item{big.mark}{character; if not empty used as mark between every
    \code{big.interval} decimals \emph{before} (hence \code{big}) the
    decimal point.}
  \item{big.interval}{see \code{big.mark} above; defaults to 3.}
  \item{small.mark}{character; if not empty used as mark between every
    \code{small.interval} decimals \emph{after} (hence \code{small}) the
    decimal point.}
  \item{small.interval}{see \code{small.mark} above; defaults to 5.}
  \item{decimal.mark}{the character used to indicate the numeric
    decimal point.}

  \item{pv}{a numeric vector.}
  \item{eps}{a numerical tolerance: see Details.}
  \item{na.form}{character representation of \code{NA}s.}
  \item{width}{the returned vector has elements of at most \code{width}.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\details{
  These functions convert their first argument to a vector (or array) of
  character strings which have a common format (as is done by
  \code{\link{print}}), fulfilling \code{length(format*(x, *)) ==
    length(x)}.  The trimming with \code{trim = TRUE} is useful
  when the strings are to be used for plot \code{\link{axis}} annotation.

  \code{format.AsIs} deals with columns of complicated objects that
  have been extracted from a data frame.

  \code{format.pval} is mainly an auxiliary function for
  \code{\link{print.summary.lm}} etc., and does separate formatting for
  fixed, floating point and very small values; those less than
  \code{eps} are formatted as \code{"< [eps]"} (where \dQuote{[eps]}
  stands for \code{format(eps, digits)}.

  The function \code{\link{formatC}} provides a rather more flexible
  formatting facility for numbers, but does \emph{not} provide a common
  format for several numbers, nor it is platform-independent.

  \code{format.data.frame} formats the data frame column by column,
  applying the appropriate method of \code{format} for each column.

  \code{prettyNum} is the utility function for prettifying \code{x}. If
  \code{x} is not a character, \code{format(x[i], ...)} is applied to
  each element, and then it is left unchanged if all the other arguments
  are at their defaults.  Note that \code{prettyNum(x)} may behave
  unexpectedly if \code{x} is a \code{character} not resulting from
  something like \code{format(<number>)}.
}
\note{
  Currently \code{format} drops trailing zeroes, so \code{format(6.001,
    digits=2)} gives \code{"6"} and \code{format(c(6.0, 13.1),
    digits=2)} gives \code{c(" 6", "13")}.

  Character(s) \code{"} in input strings \code{x} are escaped to \code{\\"}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}

\seealso{
  \code{\link{format.info}} indicates how something would be formatted;
  \code{\link{formatC}}, \code{\link{paste}}, \code{\link{as.character}},
  \code{\link{sprintf}}.
}
\examples{
format(1:10)

zz <- data.frame("(row names)"= c("aaaaa", "b"), check.names=FALSE)
format(zz)
format(zz, justify="left")

## use of nsmall
format(13.7)
format(13.7, nsmall=3)

r <- c("76491283764.97430", "29.12345678901", "-7.1234", "-100.1","1123")
## American:
prettyNum(r, big.mark = ",")
## Some Europeans:
prettyNum(r, big.mark = "'", decimal.mark = ",")

(dd <- sapply(1:10, function(i)paste((9:0)[1:i],collapse="")))
prettyNum(dd, big.mark="'")

pN <- pnorm(1:7, lower=FALSE)
cbind(format (pN, small.mark = " ", digits = 15))
cbind(formatC(pN, small.mark = " ", digits = 17, format = "f"))
}
\keyword{character}
\keyword{print}
\eof
\name{format.info}
\title{format(.) Information}
\usage{
format.info(x, nsmall = 0)
}
\alias{format.info}
\arguments{
 \item{x}{(numeric) vector; potential argument of
   \code{\link{format}(x,\dots)}.}
 \item{nsmall}{ (see \code{\link{format}(*, nsmall)}).}
}
\description{
  Information is returned on how \code{\link{format}(x, digits =
    options("digits"))} would be formatted.
}
\value{
  An \code{\link{integer}} \code{\link{vector}} of length 3, say
  \code{r}.
  \item{r[1]}{width (number of characters) used for \code{format(x)}}
  \item{r[2]}{number of digits after decimal point.}
  \item{r[3]}{in \code{0:2}; if \eqn{\ge}{>=}\code{1}, \emph{exponential}
    representation would be used, with exponent length of \code{r[3]+1}.}
}
\note{The result \bold{depends} on the value of
  \code{\link{options}("digits")}.}
\seealso{\code{\link{format}}, \code{\link{formatC}}.}
\examples{
dd <- options("digits") ; options(digits = 7) #-- for the following
format.info(123) # 3 0 0
format.info(pi)  # 8 6 0
format.info(1e8) # 5 0 1 - exponential "1e+08"
format.info(1e222)#6 0 2 - exponential "1e+222"

x <- pi*10^c(-10,-2,0:2,8,20)
names(x) <- formatC(x,w=1,dig=3,format="g")
cbind(sapply(x,format))
t(sapply(x, format.info))

## using at least 8 digits right of "."
t(sapply(x, format.info, nsmall = 8))

# Reset old options:
options(dd)
}
\keyword{character}
\keyword{print}
\keyword{programming}
\eof
\name{formatDL}
\alias{formatDL}
\title{Format Description Lists}
\description{Format vectors of items and their descriptions as 2-column
  tables or LaTeX-style description lists.
}
\usage{
formatDL(x, y, style = c("table", "list"),
         width = 0.9 * getOption("width"), indent = NULL)
}
\arguments{
  \item{x}{a vector giving the items to be described, or a list of
    length 2 or a matrix with 2 columns giving both items and
    descriptions.}
  \item{y}{a vector of the same length as \code{x} with the
    corresponding descriptions.  Only used if \code{x} does not already
    give the descriptions.}
  \item{style}{a character string specifying the rendering style of the
    description information.  If \code{"table"}, a two-column table with
    items and descriptions as columns is produced (similar to Texinfo's
    \code{@table} environment.  If \code{"list"}, a LaTeX-style tagged
    description list is obtained.}  
  \item{width}{a positive integer giving the target column for wrapping
    lines in the output.}
  \item{indent}{a positive integer specifying the indentation of the
    second column in table style, and the indentation of continuation
    lines in list style.  Must not be greater than \code{width/2}, and
    defaults to \code{width/3} for table style and \code{width/9} for
    list style.} 
}
\value{
  a character vector with the formatted entries.
}
\details{
  After extracting the vectors of items and corresponding descriptions
  from the arguments, both are coerced to character vectors.
  
  In table style, items with more than \code{indent - 3} characters are
  displayed on a line of their own.
}
\examples{
## Use R to create the 'INDEX' for package 'eda' from its 'CONTENTS'
x <- read.dcf(file = system.file("CONTENTS", package = "eda"),
               fields = c("Entry", "Description"))
x <- as.data.frame(x)
writeLines(formatDL(x$Entry, x$Description))
## or equivalently: writeLines(formatDL(x))
## Same information in tagged description list style:
writeLines(formatDL(x$Entry, x$Description, style = "list"))
## or equivalently: writeLines(formatDL(x, style = "list"))
}
\keyword{print}
\eof
\name{formatC}
\title{Formatting Using C-style Formats}
\usage{
formatC(x, digits = NULL, width = NULL,
        format = NULL, flag = "", mode = NULL,
        big.mark = "", big.interval = 3,
      small.mark = "", small.interval = 5,
    decimal.mark = ".")

format.char(x, width = NULL, flag = "-")
}
\alias{formatC}
\alias{format.char}
\arguments{
  \item{x}{an atomic numerical or character object, typically a vector
    of real numbers.}

  \item{digits}{the desired number of digits after the decimal
    point (\code{format = "f"}) or \emph{significant} digits
    (\code{format = "g"}, \code{= "e"} or \code{= "fg"}).

    Default: 2 for integer, 4 for real numbers.  If less than 0,
    the C default of 6 digits is used.}

  \item{width}{the total field width; if both \code{digits} and
    \code{width} are unspecified, \code{width} defaults to 1,
    otherwise to \code{digits + 1}.  \code{width = 0} will use
    \code{width = digits}, \code{width < 0} means left
    justify the number in this field (equivalent to \code{flag ="-"}).
    If necessary, the result will have more characters than \code{width}.}

  \item{format}{equal to \code{"d"}  (for integers), \code{"f"},
    \code{"e"}, \code{"E"}, \code{"g"}, \code{"G"}, \code{"fg"} (for
    reals), or \code{"s"} (for strings). Default is \code{"d"} for
    integers, \code{"g"} for reals.

    \code{"f"} gives numbers in the usual
    \code{xxx.xxx} format;  \code{"e"} and \code{"E"} give \code{n.ddde+nn} or
    \code{n.dddE+nn} (scientific format); \code{"g"} and \code{"G"} put
    \code{x[i]} into scientific format only if it saves space to do so.

    \code{"fg"} uses fixed format as \code{"f"}, but \code{digits} as
    the minimum number of \emph{significant} digits.  That this can lead
    to quite long result strings, see examples below.  Note that unlike
    \code{\link{signif}} this prints large numbers with
    more significant digits than \code{digits}.}

  \item{flag}{format modifier as in Kernighan and Ritchie (1988, page 243).
    \code{"0"}  pads leading zeros; \code{"-"} does left adjustment,
    others are \code{"+"}, \code{" "}, and \code{"#"}.}

  \item{mode}{\code{"double"} (or \code{"real"}), \code{"integer"} or
    \code{"character"}.
    Default: Determined from the storage mode of \code{x}.}

  \item{big.mark, big.interval,
    small.mark, small.interval,
    decimal.mark}{used for prettying longer decimal sequences, passed to
    \code{\link{prettyNum}}: that help page explains the details.}
}
\description{
    Formatting numbers individually and flexibly, using \code{C} style
    format specifications.  \code{format.char} is a helper function for
    \code{formatC}.
}
\value{
  A character object of same size and attributes as \code{x}.
  Unlike \code{\link{format}}, each number is formatted individually.
  Looping over each element of \code{x}, \code{sprintf(\dots)} is
  called (inside the C function \code{str_signif}).

  \code{format.char(x)} and \code{formatC}, for character \code{x}, do
  simple (left or right) padding with white space.
}
\details{
  If you set \code{format} it over-rides the setting of \code{mode}, so
  \code{formatC(123.45, mode="double", format="d")} gives \code{123}.

  The rendering of scientific format is platform-dependent: some systems
  use \code{n.ddde+nnn} or \code{n.dddenn} rather than \code{n.ddde+nn}.

  \code{formatC} does not necessarily align the numbers on the decimal
  point, so \code{formatC(c(6.11, 13.1), digits=2, format="fg")} gives
  \code{c("6.1", " 13")}.  If you want common formatting for several
  numbers, use \code{\link{format}}.
}
\author{
  Originally written by Bill Dunlap, later much improved by Martin Maechler,
  it was first adapted for \R by Friedrich Leisch.
}
\references{
  Kernighan, B. W. and Ritchie, D. M. (1988)
  \emph{The C Programming Language.}  Second edition. Prentice Hall.
}
\seealso{
  \code{\link{format}}, \code{\link{sprintf}} for more general C like
  formatting.
}
\examples{
xx  <- pi * 10^(-5:4)
cbind(format(xx, digits=4), formatC(xx))
cbind(formatC(xx, wid = 9, flag = "-"))
cbind(formatC(xx, dig = 5, wid = 8, format = "f", flag = "0"))
cbind(format(xx, digits=4), formatC(xx, dig = 4, format = "fg"))

format.char(c("a", "Abc", "no way"), wid = -7)  # <=> flag = "-"
formatC(    c("a", "Abc", "no way"), wid = -7)  # <=> flag = "-"
formatC(c((-1:1)/0,c(1,100)*pi), wid=8, dig=1)

xx <- c(1e-12,-3.98765e-10,1.45645e-69,1e-70,pi*1e37,3.44e4)
##       1        2             3        4      5       6
formatC(xx)
formatC(xx, format="fg")       # special "fixed" format.
formatC(xx, format="f", dig=80)#>> also long strings
}
\keyword{character}
\keyword{print}
\eof
\name{formula}
\title{Model Formulae}
\usage{
y ~ model
formula(x, \dots)
as.formula(object, env = parent.frame())
}
\alias{~}
\alias{formula}
\alias{formula.default}
\alias{formula.formula}
\alias{formula.terms}
\alias{formula.data.frame}
\alias{as.formula}
\alias{print.formula}
\description{
  The generic function \code{formula} and its specific methods provide a
  way of extracting formulae which have been included in other objects.

  \code{as.formula} is almost identical, additionally preserving
  attributes when \code{object} already inherits from
  \code{"formula"}. The default value of the \code{env} argument is
  used only when the formula would otherwise lack an environment.
}
\arguments{
  \item{x, object}{an object}
  \item{\dots}{further arguments passed to or from other methods.}
  \item{env}{the environment to associate with the result.}
}
\details{
  The models fit by, e.g., the \code{\link{lm}} and \code{\link{glm}} functions
  are specified in a compact symbolic form.
  The \code{~} operator is basic in the formation of such models.
  An expression of the form \code{y ~ model} is interpreted
  as a specification that the response \code{y} is modelled
  by a linear predictor specified symbolically by \code{model}.
  Such a model consists of a series of terms separated
  by \code{+} operators.
  The terms themselves consist of variable and factor
  names separated by \code{:} operators.
  Such a term is interpreted as the interaction of
  all the variables and factors appearing in the term.

  In addition to \code{+} and \code{:}, a number of other operators are
  useful in model formulae.  The \code{*} operator denotes factor
  crossing: \code{a*b} interpreted as \code{a+b+a:b}.  The \code{^}
  operator indicates crossing to the specified degree.  For example
  \code{(a+b+c)^2} is identical to \code{(a+b+c)*(a+b+c)} which in turn
  expands to a formula containing the main effects for \code{a},
  \code{b} and \code{c} together with their second-order interactions.
  The \code{\%in\%} operator indicates that the terms on its left are
  nested within those on the right.  For example \code{a+b\%in\%a}
  expands to the formula \code{a+a:b}.  The \code{-} operator removes
  the specified terms, so that \code{(a+b+c)^2 - a:b} is identical to
  \code{a + b + c + b:c + a:c}.  It can also used to remove the intercept
  term: \code{y~x - 1} is a line through the origin.  A model with no
  intercept can be also specified as \code{y~x + 0} or \code{0 + y~x}.

  While formulae usually involve just variable and factor
  names, they can also involve arithmetic expressions.
  The formula \code{log(y) ~ a + log(x)} is quite legal.
  When such arithmetic expressions involve
  operators which are also used symbolically
  in model formulae, there can be confusion between
  arithmetic and symbolic operator use.

  To avoid this confusion, the function \code{\link{I}()}
  can be used to bracket those portions of a model
  formula where the operators are used in their
  arithmetic sense.  For example, in the formula
  \code{y ~ a + I(b+c)}, the term \code{b+c} is to be
  interpreted as the sum of \code{b} and \code{c}.

  As from \R 1.8.0 variable names can be quoted by backticks \code{`like
    this`} in formulae, although there is no guarantee that all code
  using formulae will accept such non-syntactic names.
}
\section{Environments}{
  A formula object has an associated environment, and
  this environment (rather than the parent
  environment) is used by \code{\link{model.frame}} to evaluate variables
  that are not found in the supplied \code{data} argument.

  Formulas created with the \code{~} operator use the
  environment in which they were created. Formulas created with
  \code{as.formula} will use the \code{env} argument for their
  environment. Pre-existing formulas extracted with
  \code{as.formula} will only have their environment changed if
  \code{env} is explicitly given.
}
\value{
  All the functions above produce an object of class \code{"formula"}
  which contains a symbolic model formula.
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical models.}
  Chapter 2 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{I}}.
  
  For formula manipulation: \code{\link{terms}}, and \code{\link{all.vars}};
  for typical use: \code{\link{lm}}, \code{\link{glm}}, and
  \code{\link{coplot}}.
}
\examples{
class(fo <- y ~ x1*x2) # "formula"
fo
typeof(fo)# R internal : "language"
terms(fo)

environment(fo)
environment(as.formula("y ~ x"))
environment(as.formula("y ~ x",env=new.env()))


## Create a formula for a model with a large number of variables:
xnam <- paste("x", 1:25, sep="")
(fmla <- as.formula(paste("y ~ ", paste(xnam, collapse= "+"))))
}
\keyword{models}
\eof
\name{fourfoldplot}
\alias{fourfoldplot}
\title{Fourfold Plots}
\description{
  Creates a fourfold display of a 2 by 2 by \eqn{k} contingency table on
  the current graphics device, allowing for the visual inspection of the
  association between two dichotomous variables in one or several
  populations (strata).
}
\usage{
fourfoldplot(x, color = c("#99CCFF", "#6699CC"), conf.level = 0.95,
             std = c("margins", "ind.max", "all.max"),
             margin = c(1, 2), space = 0.2, main = NULL,
             mfrow = NULL, mfcol = NULL)
}
\arguments{
  \item{x}{a 2 by 2 by \eqn{k} contingency table in array form, or as a
    2 by 2 matrix if \eqn{k} is 1.}
  \item{color}{a vector of length 2 specifying the colors to use for the
    smaller and larger diagonals of each 2 by 2 table.}
  \item{conf.level}{confidence level used for the confidence rings on
    the odds ratios.  Must be a single nonnegative number less than 1;
    if set to 0, confidence rings are suppressed.}
  \item{std}{a character string specifying how to standardize the table.
    Must be one of \code{"margins"}, \code{"ind.max"}, or
    \code{"all.max"}, and can be abbreviated by the initial letter.
    If set to \code{"margins"}, each 2 by 2 table is standardized to
    equate the margins specified by \code{margin} while preserving the
    odds ratio.  If \code{"ind.max"} or \code{"all.max"}, the tables are
    either individually or simultaneously standardized to a maximal cell
    frequency of 1.}
  \item{margin}{a numeric vector with the margins to equate.  Must be
    one of \code{1}, \code{2}, or \code{c(1, 2)} (the default), which
    corresponds to standardizing the row, column, or both margins in
    each 2 by 2 table.
    Only used if \code{std} equals \code{"margins"}.}
  \item{space}{the amount of space (as a fraction of the maximal radius
    of the quarter circles) used for the row and column lebals.}
  \item{main}{character string for the fourfold title.}
  \item{mfrow}{a numeric vector of the form \code{c(nr, nc)}, indicating
    that the displays for the 2 by 2 tables should be arranged in an
    \code{nr} by \code{nc} layout, filled by rows.}
  \item{mfcol}{a numeric vector of the form \code{c(nr, nc)}, indicating
    that the displays for the 2 by 2 tables should be arranged in an
    \code{nr} by \code{nc} layout, filled by columns.}
}
\details{
  The fourfold display is designed for the display of 2 by 2 by \eqn{k}
  tables.

  Following suitable standardization, the cell frequencies
  \eqn{f_{ij}}{f[i,j]} of each 2 by 2 table are shown as a quarter
  circle whose radius is proportional to
  \eqn{\sqrt{f_{ij}}}{sqrt(f[i,j])} so that its area is proportional to
  the cell frequency.  An association (odds ratio different from 1)
  between the binary row and column variables is indicated by the
  tendency of diagonally opposite cells in one direction to differ in
  size from those in the other direction; color is used to show this
  direction.  Confidence rings for the odds ratio allow a visual test of
  the null of no association; the rings for adjacent quadrants overlap
  iff the observed counts are consistent with the null hypothesis.

  Typically, the number \eqn{k} corresponds to the number of levels of a
  stratifying variable, and it is of interest to see whether the
  association is homogeneous across strata.  The fourfold display
  visualizes the pattern of association.  Note that the confidence rings
  for the individual odds ratios are not adjusted for multiple testing.
}
\references{
  Friendly, M. (1994).
  A fourfold display for 2 by 2 by \eqn{k} tables.
  Technical Report 217, York University, Psychology Department.
  \url{http://www.math.yorku.ca/SCS/Papers/4fold/4fold.ps.gz}
}
\seealso{
  \code{\link{mosaicplot}}
}
\examples{
data(UCBAdmissions)
## Use the Berkeley admission data as in Friendly (1995).
x <- aperm(UCBAdmissions, c(2, 1, 3))
dimnames(x)[[2]] <- c("Yes", "No")
names(dimnames(x)) <- c("Sex", "Admit?", "Department")
ftable(x)

## Fourfold display of data aggregated over departments, with
## frequencies standardized to equate the margins for admission
## and sex.
## Figure 1 in Friendly (1994).
fourfoldplot(margin.table(x, c(1, 2)))

## Fourfold display of x, with frequencies in each table
## standardized to equate the margins for admission and sex.
## Figure 2 in Friendly (1994).
fourfoldplot(x)

## Fourfold display of x, with frequencies in each table
## standardized to equate the margins for admission. but not
## for sex.
## Figure 3 in Friendly (1994).
fourfoldplot(x, margin = 2)
}
\keyword{hplot}
\eof
\name{frame}
\title{Create / Start a New Plot Frame}
\usage{
plot.new()
frame()
}
\alias{plot.new}
\alias{frame}
\description{
  This function (\code{frame} is an alias for
  \code{plot.new}) causes the completion of plotting in the current plot
  (if there is one) and an advance to a new graphics frame.  This is
  used in all high-level plotting functions and also useful for skipping
  plots when a multi-figure region is in use.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole. (\code{frame}.)
}
\seealso{
  \code{\link{plot.window}}, \code{\link{plot.default}}.
}
\keyword{iplot}
\keyword{aplot}
\eof
\name{freeny}
\docType{data}
\alias{freeny}
\alias{freeny.x}
\alias{freeny.y}
\title{Freeny's Revenue Data}
\description{
  Freeny's data on quarterly revenue and explanatory variables.
}
\usage{data(freeny)}
\format{
  There are three \sQuote{freeny} data sets.

  \code{freeny.y} is a time series with 39 observations on quarterly
  revenue from (1962,2Q) to (1971,4Q).
  
  \code{freeny.x} is a matrix of explanatory variables.  The columns
  are \code{freeny.y} lagged 1 quarter, price index, income level, and
  market potential.

  Finally, \code{freeny} is a data frame with variables \code{y},
  \code{lag.quarterly.revenue}, \code{price.index}, \code{income.level},
  and \code{market.potential} obtained from the above two data objects.
}
\source{
  A. E. Freeny (1977)
  \emph{A Portable Linear Regression Package with Test Programs}.
  Bell Laboratories memorandum.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
data(freeny)
summary(freeny)
pairs(freeny, main = "freeny data")
summary(fm1 <- lm(y ~ ., data = freeny))
opar <- par(mfrow = c(2, 2), oma = c(0, 0, 1.1, 0),
            mar = c(4.1, 4.1, 2.1, 1.1))
plot(fm1)
par(opar)
}
\keyword{datasets}
\eof
\name{ftable}
\alias{ftable}
\alias{ftable.default}
\alias{print.ftable}
\title{Flat Contingency Tables}
\description{Create \dQuote{flat} contingency tables.}
\usage{
ftable(x, \dots)

\method{ftable}{default}(\dots, exclude = c(NA, NaN), row.vars = NULL, col.vars = NULL)
}
\arguments{
  \item{x, \dots}{\R objects which can be interpreted as factors (including
    character strings), or a list (or data frame) whose components can
    be so interpreted, or a contingency table object of class
    \code{"table"} or \code{"ftable"}.}
  \item{exclude}{values to use in the exclude argument of \code{factor}
    when interpreting non-factor objects.}
  \item{row.vars}{a vector of integers giving the numbers of the
    variables, or a character vector giving the names of the variables
    to be used for the rows of the flat contingency table.}
  \item{col.vars}{a vector of integers giving the numbers of the
    variables, or a character vector giving the names of the variables
    to be used for the columns of the flat contingency table.}
}
\value{
  \code{ftable} returns an object of class \code{"ftable"}, which is a
  matrix with counts of each combination of the levels of variables with
  information on the names and levels of the (row and columns) variables
  stored as attributes \code{"row.vars"} and \code{"col.vars"}.
}
\details{
  \code{ftable} creates \dQuote{flat} contingency tables.  Similar to the
  usual contingency tables, these contain the counts of each combination
  of the levels of the variables (factors) involved.  This information
  is then re-arranged as a matrix whose rows and columns correspond to
  unique combinations of the levels of the row and column variables (as
  specified by \code{row.vars} and \code{col.vars}, respectively).  The
  combinations are created by looping over the variables in reverse
  order (so that the levels of the \dQuote{left-most} variable vary the
  slowest).  Displaying a contingency table in this flat matrix form
  (via \code{print.ftable}, the print method for objects of class
  \code{"ftable"}) is often preferable to showing it as a
  higher-dimensional array.

  \code{ftable} is a generic function.  Its default method,
  \code{ftable.default}, first creates a contingency table in array
  form from all arguments except \code{row.vars} and \code{col.vars}.
  If the first argument is of class \code{"table"}, it represents a
  contingency table and is used as is; if it is a flat table of class
  \code{"ftable"}, the information it contains is converted to the usual
  array representation using \code{as.ftable}.  Otherwise, the arguments
  should be \R objects which can be interpreted as factors (including
  character strings), or a list (or data frame) whose components can be
  so interpreted, which are cross-tabulated using \code{\link{table}}.
  Then, the arguments \code{row.vars} and \code{col.vars} are used to
  collapse the contingency table into flat form.  If neither of these
  two is given, the last variable is used for the columns.  If both are
  given and their union is a proper subset of all variables involved,
  the other variables are summed out.

  Function \code{\link{ftable.formula}} provides a formula method for
  creating flat contingency tables.
}
\seealso{
  \code{\link{ftable.formula}} for the formula interface (which allows a
  \code{data = .} argument);
  \code{\link{read.ftable}} for information on reading, writing and
  coercing flat contingency tables;
  \code{\link{table}} for \dQuote{ordinary} cross-tabulation;
  \code{\link{xtabs}} for formula-based cross-tabulation.
}
\examples{
## Start with a contingency table.
data(Titanic)
ftable(Titanic, row.vars = 1:3)
ftable(Titanic, row.vars = 1:2, col.vars = "Survived")
ftable(Titanic, row.vars = 2:1, col.vars = "Survived")

## Start with a data frame.
data(mtcars)
x <- ftable(mtcars[c("cyl", "vs", "am", "gear")])
x
ftable(x, row.vars = c(2, 4))
}
\keyword{category}
\eof
\name{ftable.formula}
\alias{ftable.formula}
\title{Formula Notation for Flat Contingency Tables}
\description{Produce or manipulate a flat contingency table using
  formula notation.}
\usage{
\method{ftable}{formula}(formula, data = NULL, subset, na.action, \dots)
}
\arguments{
  \item{formula}{a formula object with both left and right hand sides
    specifying the column and row variables of the flat table.}
  \item{data}{a data frame, list or environment containing the variables
    to be cross-tabulated, or a contingency table (see below).}
  \item{subset}{an optional vector specifying a subset of observations
    to be used.
    Ignored if \code{data} is a contingency table.}
  \item{na.action}{a function which indicates what should happen when
    the data contain \code{NA}s.
    Ignored if \code{data} is a contingency table.}
  \item{\dots}{further arguments to the default ftable method may also
    be passed as arguments, see \code{\link{ftable.default}}.}
}
\details{
  This is a method of the generic function \code{\link{ftable}}.

  The left and right hand side of \code{formula} specify the column and
  row variables, respectively, of the flat contingency table to be
  created.  Only the \code{+} operator is allowed for combining the
  variables.  A \code{.} may be used once in the formula to indicate
  inclusion of all the \dQuote{remaining} variables.

  If \code{data} is an object of class \code{"table"} or an array with
  more than 2 dimensions, it is taken as a contingency table, and hence
  all entries should be nonnegative.  Otherwise, if it is not a flat
  contingency table (i.e., an object of class \code{"ftable"}), it
  should be a data frame or matrix, list or environment containing the
  variables to be cross-tabulated.  In this case, \code{na.action} is
  applied to the data to handle missing values, and, after possibly
  selecting a subset of the data as specified by the \code{subset}
  argument, a contingency table is computed from the variables.

  The contingency table is then collapsed to a flat table, according to
  the row and column variables specified by \code{formula}.
}
\value{
  A flat contingency table which contains the counts of each combination
  of the levels of the variables, collapsed into a matrix for suitably
  displaying the counts.
}
\seealso{
  \code{\link{ftable}},
  \code{\link{ftable.default}};
  \code{\link{table}}.
}
\examples{
data(Titanic)
Titanic
x <- ftable(Survived ~ ., data = Titanic)
x
ftable(Sex ~ Class + Age, data = x)
}
\keyword{category}
\eof
\name{function}
\title{Function Definition}
\usage{
function( arglist ) expr
return(value)
}
\alias{function}
\alias{return}
\description{
  These functions provide the base mechanisms for defining
  new functions in the \R language.
}
\arguments{
    \item{arglist}{Empty or one or more name or name=expression terms.}
    \item{value}{An expression.}
}
\details{
  In \R (unlike S) the names in an argument list cannot be quoted
  non-standard names.

  If \code{value} is missing, \code{NULL} is returned.  If it is a
  single expression, the value of the evaluated expression is returned.

  If the end of a function is reached without calling \code{return}, the
  value of the last evaluated expression is returned.
}
\section{Warning}{
  Prior to \R 1.8.0, \code{value} could be a series of non-empty
  expressions separated by commas.  In that case the value
  returned is a list of the evaluated expressions, with names set to
  the expressions where these are the names of \R objects. That is,
  \code{a=foo()} names the list component \code{a} and gives it value
  the result of evaluating \code{foo()}.

  This has been deprecated (and a warning is given), as it was never
  documented in S, and whether or not the list is named differs by S versions.
}
\seealso{
  \code{\link{args}} and \code{\link{body}} for accessing the arguments
  and body of a function.

  \code{\link{debug}} for debugging; \code{\link{invisible}} for
  \code{return(.)}ing \emph{invisibly}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
norm <- function(x) sqrt(x\%*\%x)
norm(1:4)

## An anonymous function:
(function(x,y){ z <- x^2 + y^2; x+y+z })(0:7, 1)
}
\keyword{programming}
\eof
\name{gc}
\title{Garbage Collection}
\usage{
gc(verbose = getOption("verbose"))
gcinfo(verbose)
}
\alias{gc}
\alias{gcinfo}
\arguments{
  \item{verbose}{logical; if \code{TRUE}, the garbage collection prints
    statistics about cons cells and the vector heap.}
}
\description{
  A call of \code{gc} causes a garbage collection to take place.
  \code{gcinfo} sets a flag so that
  automatic collection is either silent (\code{verbose=FALSE}) or
  prints memory usage statistics (\code{verbose=TRUE}).
}
\details{
  A call of \code{gc} causes a garbage collection to take place.
  This takes place automatically without user intervention, and the
  primary purpose of calling \code{gc} is for the report on memory usage.

  However, it can be useful to call \code{gc} after a large object
  has been removed, as this may prompt \R to return memory to the
  operating system.
}

\value{
  \code{gc} returns a matrix with rows \code{"Ncells"} (\emph{cons
    cells}, usually 28 bytes each on 32-bit systems and 56 bytes on
  64-bit systems, and \code{"Vcells"} (\emph{vector cells}, 8 bytes
  each), and columns \code{"used"} and \code{"gc trigger"},
  each also interpreted in megabytes (rounded up to the next 0.1Mb).

  If maxima have been set for either \code{"Ncells"} or \code{"Vcells"},
  a fifth column is printed giving the current limits in Mb (with
  \code{NA} denoting no limit).

  \code{gcinfo} returns the previous value of the flag.
}
\seealso{\code{\link{Memory}} on \R's memory management
  and \code{\link{gctorture}} if you are an \R hacker.}
\examples{
gc() #- do it now
gcinfo(TRUE) #-- in the future, show when R does it
x <- integer(100000); for(i in 1:18) x <- c(x,i)
gcinfo(verbose = FALSE)#-- don't show it anymore

gc(TRUE)
}
\keyword{environment}
\eof
\name{gc.time}
\alias{gc.time}
\title{Report Time Spent in Garbage Collection}
\description{
  This function reports the time spent in garbage collection so far in
  the \R session while GC timing was enabled..
}
\usage{
gc.time(on = TRUE)
}
\arguments{
  \item{on}{logical; if \code{TRUE}, GC timing is enabled.}
}
\value{
  A numerical vector of length 5 giving the user CPU time, the system
  CPU time, the elapsed time and children's user and system CPU times
  (normally both zero).
}
#ifdef windows
\note{
  CPU times will be returned as \code{NA} on Windows 9x/ME systems, but
  are genuine times on NT4/2000/XP systems.  Times of child processes are
  not available and will always be given as \code{NA}.
}
#endif
\section{Warnings}{
  This is experimental functionality, likely to be removed as soon as
  the next release.

  The timings are rounded up by the sampling interval for timing
  processes, and so are likely to be over-estimates.
}
\seealso{\code{\link{gc}},
  \code{\link{proc.time}} for the timings for the session.}

\examples{
gc.time()
}
\keyword{utilities}
\eof
\name{gctorture}
\title{Torture Garbage Collector}
\usage{
gctorture(on = TRUE)
}
\alias{gctorture}
\arguments{
  \item{on}{logical; turning it on/off.}
}
\description{
  Provokes garbage collection on (nearly) every memory allocation.
  Intended to ferret out memory protection bugs.  Also makes \R run
  \emph{very} slowly, unfortunately.
}
\value{
  Previous value.
}
\author{Peter Dalgaard}
\keyword{environment}

\eof
\name{get}
\alias{get}
\title{Return a Variable's Value}
\description{
  Search for an \R object with a given name and return it if found.
}
 
\usage{
get(x, pos=-1, envir=as.environment(pos), mode="any", inherits=TRUE)
}
\arguments{
  \item{x}{a variable name (given as a character string).}
  \item{pos}{where to look for the object (see the details section); if
    omitted, the function will search, as if the name of the object
    appeared in unquoted in an expression.
  }
  \item{envir}{an alternative way to specify an environment to look in;
    see the details section.}
  \item{mode}{the mode of object sought.}
  \item{inherits}{should the enclosing frames of the environment be
    inspected?}
}
\details{
  The \code{pos} argument can specify the  environment in which to look
  for the object in any of several ways:
  as an integer (the position in the \code{\link{search}} list); as
  the character string name of an element in the search list; or as an
  \code{\link{environment}} (including using \code{\link{sys.frame}} to
  access the currently active function calls).
  The \code{envir} argument is an alternative way to specify an
  environment, but is primarily there for back compatibility.
  
   The \code{mode} includes collections such as \code{"numeric"} and
   \code{"function"}: any member of the collection will suffice. 
}
\value{
  This function searches the specified environment for a bound variable
  whose name is given by the character string \code{x}.  If the
  variable's value is not of the correct \code{mode}, it is ignored.

  If \code{inherits} is \code{FALSE}, only the first frame of the
  specified environment is inspected.  If \code{inherits} is
  \code{TRUE}, the search is continued up through the parent frames
  until a bound value of the right mode is found.

  Using a \code{NULL} environment is equivalent to using the current
  environment.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{exists}}.
}
\examples{
get("\%o\%")
}
\keyword{data}
\eof
\name{getAnywhere}
\alias{getAnywhere}
\alias{[.getAnywhere}
\alias{print.getAnywhere}
\title{Retrieve an R Object, Including from a Namespace}
\description{
  This functions locates all objects with name matching its argument,
  whether visible on the search path, registered as an S3 method or in a
  namespace but not exported.
}
\usage{
getAnywhere(x)
}
\arguments{
  \item{x}{a character string or name.}
}
\details{
  The function looks at all loaded namespaces, whether or not they are
  associated with a package on the search list.

  Where functions are found as an S3 method, an attempt is made to find
  which namespace registered them.  This may not be correct, especially
  if a namespace is unloaded.
}
\value{
  An object of class \code{"getAnywhere"}.  This is a list with components
  \item{name}{the name searched for.}
  \item{funs}{a list of objects found}
  \item{where}{a character vector explaining where the object(s) were found}
  \item{visible}{logical: is the object visible}
  \item{dups}{logical: is the object identical to one earlier in the
    list.}

  Normally the structure will be hidden by the \code{print} method.
  There is a \code{[} method to extract one or more of the objects found.
}
\seealso{
  \code{\link{get}},  \code{\link{getFromNamespace}}
}
\examples{
getAnywhere("format.dist")
getAnywhere("simpleLoess") # not exported from modreg
}
\keyword{data}
\eof
\name{getFromNamespace}
\alias{getFromNamespace}
\alias{fixInNamespace}
\title{Utility functions for Developing Namespaces}
\description{
  Utility functions to access and replace the non-exported functions in
  a namespace, for use in developing packages with namespaces.
}
\usage{
getFromNamespace(x, ns, pos = -1, envir = as.environment(pos))
fixInNamespace(x, ns, pos = -1, envir = as.environment(pos), \dots)
}
\arguments{
  \item{x}{an object name (given as a character string).}
  \item{ns}{a namespace, or character string giving the namespace.}
  \item{pos}{where to look for the object: see \code{\link{get}}.}
  \item{envir}{an alternative way to specify an environment to look in.}
  \item{\dots}{arguments to pass to the editor: see \code{\link{edit}}.}
}
\details{
  The namespace can be specified in several ways.  Using, for example,
  \code{ns="modreg"} is the most direct, but a loaded package with a
  namespace can be specified via any of the methods used for
  \code{\link{get}}: \code{ns} can also be the environment
  \code{<namespace:foo>}.

  \code{fixInNamespace} invokes \code{\link{edit}} on the object named
  \code{x} and assigns the revised object in place of the original
  object.  For compatibility with \code{fix}, \code{x} can be unquoted.
}
\note{
  \code{fixInNamespace} will alter the copy of the object in the
  namespace, and also a copy registered as an S3 method.  There can be other
  copies, so the function is not foolproof, but should be helpful for
  debugging.
}
\value{
  \code{getFromNamespace} returns the object found (or gives an error).

  \code{fixInNamespace} is invoked for its side effect of changing the
  object in the namespace.
}

\seealso{
  \code{\link{get}}, \code{\link{fix}}, \code{\link{getS3method}}
}
\examples{\dontrun{
fixInNamespace("predict.ppr", "modreg")
## alternatively
fixInNamespace("predict.ppr", pos = 5)
}}
\keyword{data}
\eof
\name{getNativeSymbolInfo}
\alias{getNativeSymbolInfo}
\title{Obtain a description of a native (C/Fortran) symbol}
\description{
  This finds and returns as comprehensive a description of a
  dynamically loaded or \dQuote{exported} built-in native
  symbol. It returns information about the
  name of the symbol, the library in which it is located
  and, if available, the number of arguments it expects
  and by which interface it should be called (i.e
  \code{\link{.Call}},   \code{\link{.C}},
  \code{\link{.Fortran}},  or \code{\link{.External}}).
  Additionally, it returns the address of the symbol and this
  can be passed to other C routines which can invoke.
  Specifically, this provides a way to explicitly share
  symbols between different dynamically loaded package libraries.
  Also, it provides a way to query where symbols were resolved,
  and aids diagnosing strange behavior associated with dynamic
  resolution.
}
\usage{
getNativeSymbolInfo(name, PACKAGE)
}
\arguments{
  \item{name}{the name of the native symbol as used in a call
    to \code{\link{is.loaded}}, etc.}
  \item{PACKAGE}{an optional argument that specifies to which
    dynamically loaded library we restrict the search for this symbol.
    If this is \code{"base"}, we search in the R executable itself.}
}
\details{
  This uses the same mechanism for resolving symbols as is used
  in all the native interfaces (\code{\link{.Call}}, etc.).
  If the symbol has been explicitly registered by the shared library
  in which it is contained, information about the number of arguments
  and the interface by which it should be called will be returned.
  Otherwise, a generic native symbol object is returned.
}
\value{
  If the symbol is not found, an error is raised.
  Otherwise, the value is a list containing the following elements:
  \item{name}{the name of the symbol, as given by the
  \code{name} argument.}
  \item{address}{the native memory address of the symbol which can
    be used to invoke the routine, and also
    compare with other symbol address. This is an external pointer
    object and of class \code{NativeSymbol}.}
  \item{package}{a list containing 3 elements:
    \describe{
      \item{name}{the short form of the library name which can be used
	as the value of the \code{PACKAGE} argument in
	the different native interface functions.}
      \item{path}{the fully qualified name of the shared library file.}
      \item{dynamicLookup}{a logical value indicating whether dynamic
	resolution is used when looking for symbols in this library,
	or only registered routines can be located.}
    }    
  }
  The class of this list object is \code{NativeSymbolInfo}.
  If the routine was explicitly registered by the dynamically
  loaded library, the list contains a fourth field
  \item{numParameters}{the number of arguments that should be passed
    in a call to this routine.}
  Additionally, the list will have an additional class,
  being \code{CRoutine},   \code{CallRoutine},
  \code{FortranRoutine} or \code{ExternalRoutine}
  corresponding to the R interface by which it should be invoked.
  
}
\references{
  For information about registering native routines,
  see \dQuote{In Search of {C/C++} \& {FORTRAN} Routines},
  R News, volume 1, number 3, 2001, p20--23
  (\url{http://CRAN.R-project.org/doc/Rnews/}).  
}
\author{Duncan Temple Lang}
\note{
  One motivation for accessing this reflectance information
  is to be able to pass native routines to 
  C routines as \dQuote{function pointers} in C.
  This allows us to treat native routines and R functions
  in a similar manner, such as when passing an R function
  to C code that makes callbacks to that function
  at different points in its computation
  (e.g., \code{\link[nls:nls]{nls}}).
  Additionally, we can resolve the symbol just once and
  avoid resolving it repeatedly or using the internal
  cache.
  In the future, one may be able to treat \code{NativeSymbol}
  objects as directly callback objects.
}
\seealso{
  \code{\link{is.loaded}},
  \code{\link{.C}},
  \code{\link{.Fortran}},
  \code{\link{.External}},
  \code{\link{.Call}},
  \code{\link{dyn.load}}.  
}

\examples{
library(ctest) # normally loaded
getNativeSymbolInfo("dansari")

library(mva)   # normally loaded
getNativeSymbolInfo(symbol.For("hcass2"))
}
\keyword{interface}
\eof
\name{getS3method}
\alias{getS3method}
\title{Get An S3 Method}
\description{
  Get a method for an S3 generic, possibly from a namespace. 
}
\usage{
getS3method(f, class, optional = FALSE)
}
\arguments{
  \item{f}{character: name of the generic.}
  \item{class}{character: name of the class.}
  \item{optional}{logical: should failure to find the generic or a
    method be allowed?}
}
\details{
  S3 methods may be hidden in packages with namespaces, and will not
  then be found by \code{\link{get}}: this function can retrieve
  such functions, primarily for debugging purposes.
}
\value{
  The function found, or \code{NULL} if no function is found and
  \code{optional = TRUE}.
}
\seealso{
  \code{\link{methods}}, \code{\link{get}}
}
\examples{
require(modreg)
exists("predict.ppr") # false
getS3method("predict", "ppr")
}
\keyword{data}

\eof
\name{Sys.getenv}
\title{Get Environment Variables}
\usage{
Sys.getenv(x)
}
\alias{Sys.getenv}
\arguments{
  \item{x}{a character vector, or missing}
}
\description{
  \code{Sys.getenv} obtains the values of the environment variables named by
  \code{x}.
}
\value{
  A vector of the same length as \code{x}, with the variable names as
  its \code{names} attribute.  Each element holds the value of the
  environment variable named by the corresponding component of \code{x}
  (or \code{""} if no environment variable with that name was found).

  On most platforms \code{Sys.getenv()} will return a named vector giving
  the values of all the environment variables.
}
\seealso{
  \code{\link{Sys.putenv}},
  \code{\link{getwd}} for the working directory.
}
\examples{
Sys.getenv(c("R_HOME", "R_PAPERSIZE", "R_PRINTCMD", "HOST"))
}
\keyword{environment}
\keyword{utilities}
\eof
\name{getpid}
\alias{Sys.getpid}

\title{Get the Process ID of the R Session}
\description{
  Get the process ID of the \R Session.  It is guaranteed by the
  operating system that two \R sessions running simultaneously will
  have different IDs, but it is possible that \R sessions running at
  different times will have the same ID.
}
\usage{
Sys.getpid()
}
\value{
  An integer, usually a small integer between 0 and 32767 under
  Unix-alikes and a much small integer under Windows.
}
\examples{
Sys.getpid()
}
\keyword{utilities}
\eof
\name{getwd}
\alias{getwd}
\alias{setwd}
\title{Get or Set Working Directory}
\usage{
getwd()
setwd(dir)
}
\arguments{
  \item{dir}{A character string.}
}
\description{
  \code{getwd} returns an absolute filename representing the current
  working directory of the \R process; \code{setwd(dir)} is used to set
  the working directory to \code{dir}.
}
\note{
  These functions are not implemented on all platforms.
}
\value{
  \code{getwd} returns a character vector, or \code{NULL} if the
  working directory is not available on that platform.

  \code{setwd} returns \code{NULL} invisibly.  It will give an error if
  it does not succeed.
}
\examples{
(WD <- getwd())
if (!is.null(WD)) setwd(WD)
}
\keyword{utilities}
\eof
\name{gl}
\alias{gl}
\title{Generate Factor Levels}
\description{
  Generate factors by specifying the pattern of their levels.
}
\usage{
gl(n, k, length = n*k, labels = 1:n, ordered = FALSE)
}
\arguments{
  \item{n}{an integer giving the number of levels.}
  \item{k}{an integer giving the number of replications.}
  \item{length}{an integer giving the length of the result.}
  \item{labels}{an optional vector of labels for the resulting factor
    levels.}
  \item{ordered}{a logical indicating whether the result should be
    ordered or not.}
}
\value{
  The result has levels from \code{1} to \code{n} with each value
  replicated in groups of length \code{k} out to a total length of
  \code{length}.

  \code{gl} is modelled on the \emph{GLIM} function of the same name.
}
\seealso{
  The underlying \code{\link{factor}()}.
}
\examples{
## First control, then treatment:
gl(2, 8, label = c("Control", "Treat"))
## 20 alternating 1s and 2s
gl(2, 1, 20)
## alternating pairs of 1s and 2s
gl(2, 2, 20)
}
\keyword{category}
\keyword{arith}
\eof
\name{glm}
\title{Fitting Generalized Linear Models}
\alias{glm}
\alias{glm.fit}
\alias{weights.glm}
\alias{print.glm}
\description{
  \code{glm} is used to fit generalized linear models, specified by
  giving a symbolic description of the linear predictor and a
  description of the error distribution.
}
\usage{
glm(formula, family = gaussian, data, weights = NULL, subset = NULL,
    na.action, start = NULL, etastart = NULL, mustart = NULL,
    offset = NULL, control = glm.control(\dots), model = TRUE,
    method = "glm.fit", x = FALSE, y = TRUE, contrasts = NULL, \dots)

glm.fit(x, y, weights = rep(1, nobs),
        start = NULL, etastart = NULL, mustart = NULL,
        offset = rep(0, nobs), family = gaussian(),
        control = glm.control(), intercept = TRUE)

\method{weights}{glm}(object, type = c("prior", "working"), \dots)
}
\arguments{
  \item{formula}{a symbolic description of the model to be fit.
    The details of model specification are given below.}

  \item{family}{a description of the error distribution and link
    function to be used in the model. This can be a character string
    naming a family function, a family function or the result of a call
    to a family function.  (See \code{\link{family}} for details of
    family functions.)}

  \item{data}{an optional data frame containing the variables
    in the model.  By default the variables are taken from
    \code{environment(formula)}, typically the environment from which
    \code{glm} is called.}

  \item{weights}{an optional vector of weights to be used
    in the fitting process.}

  \item{subset}{an optional vector specifying a subset of observations
    to be used in the fitting process.}

  \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{start}{starting values for the parameters in the linear predictor.}

  \item{etastart}{starting values for the linear predictor.}

  \item{mustart}{starting values for the vector of means.}

  \item{offset}{this can be used to specify an \emph{a priori}
    known component to be included in the linear predictor
    during fitting.}

  \item{control}{a list of parameters for controlling the fitting
    process.  See the documentation for \code{\link{glm.control}}
    for details.}

  \item{model}{a logical value indicating whether \emph{model frame}
    should be included as a component of the returned value.}

  \item{method}{the method to be used in fitting the model.
    The default method \code{"glm.fit"} uses iteratively reweighted
    least squares (IWLS).  The only current alternative is
    \code{"model.frame"} which returns the model frame and does no fitting.}

  \item{x, y}{For \code{glm}:
    logical values indicating whether the response
    vector and model matrix used in the fitting process
    should be returned as components of the returned value.

    For \code{glm.fit}: \code{x} is a design matrix of dimension \code{n
      * p}, and \code{y} is a vector of observations of length \code{n}.
  }

  \item{contrasts}{an optional list. See the \code{contrasts.arg}
    of \code{model.matrix.default}.}

  \item{object}{an object inheriting from class \code{"glm"}.}
  \item{type}{character, partial matching allowed.  Type of weights to
    extract from the fitted model object.}

  \item{intercept}{logical. Should an intercept be included?}

  \item{\dots}{further arguments passed to or from other methods.}
}
\details{
  A typical predictor has the form \code{response ~ terms} where
  \code{response} is the (numeric) response vector and \code{terms} is a
  series of terms which specifies a linear predictor for \code{response}.
  For \code{binomial} models the response can also be specified as a
  \code{\link{factor}} (when the first level denotes failure and all
  others success) or as a two-column matrix with the columns giving the
  numbers of successes and failures.  A terms specification of the form
  \code{first + second} indicates all the terms in \code{first} together
  with all the terms in \code{second} with duplicates removed.

  A specification of the form \code{first:second} indicates the
  the set of terms obtained by taking the interactions of
  all terms in \code{first} with all terms in \code{second}.
  The specification \code{first*second} indicates the \emph{cross}
  of \code{first} and \code{second}.
  This is the same as \code{first + second + first:second}.

  \code{glm.fit} and \code{glm.fit.null} are the workhorse functions:
  the former calls the latter for a null model (with no intercept).

  If more than one of \code{etastart}, \code{start} and \code{mustart}
  is specified, the first in the list will be used.
}
\value{
  \code{glm} returns an object of class inheriting from \code{"glm"}
  which inherits from the class \code{"lm"}. See later in this section.

  The function \code{\link{summary}} (i.e., \code{\link{summary.glm}}) can
  be used to obtain or print a summary of the results and the function
  \code{\link{anova}} (i.e., \code{\link{anova.glm}})
  to produce an analysis of variance table.

  The generic accessor functions \code{\link{coefficients}},
  \code{effects}, \code{fitted.values} and \code{residuals} can be used to
  extract various useful features of the value returned by \code{glm}.

  \code{weights} extracts a vector of weights, one for each case in the
  fit (after subsetting and \code{na.action}).

  An object of class \code{"glm"} is a list containing at least the
  following components:

  \item{coefficients}{a named vector of coefficients}
  \item{residuals}{the \emph{working} residuals, that is the residuals
    in the final iteration of the IWLS fit.}
  \item{fitted.values}{the fitted mean values, obtained by transforming
    the linear predictors by the inverse of the link function.}
  \item{rank}{the numeric rank of the fitted linear model.}
  \item{family}{the \code{\link{family}} object used.}
  \item{linear.predictors}{the linear fit on link scale.}
  \item{deviance}{up to a constant, minus twice the maximized
    log-likelihood.  Where sensible, the constant is chosen so that a
    saturated model has deviance zero.}
  \item{aic}{Akaike's \emph{An Information Criterion}, minus twice the
    maximized log-likelihood plus twice the number of coefficients (so
    assuming that the dispersion is known.}
  \item{null.deviance}{The deviance for the null model, comparable with
    \code{deviance}. The null model will include the offset, and an
    intercept if there is one in the model}
  \item{iter}{the number of iterations of IWLS used.}
  \item{weights}{the \emph{working} weights, that is the weights
    in the final iteration of the IWLS fit.}
  \item{prior.weights}{the case weights initially supplied.}
  \item{df.residual}{the residual degrees of freedom.}
  \item{df.null}{the residual degrees of freedom for the null model.}
  \item{y}{the \code{y} vector used. (It is a vector even for a binomial
    model.)}
  \item{converged}{logical. Was the IWLS algorithm judged to have converged?}
  \item{boundary}{logical. Is the fitted value on the boundary of the
    attainable values?}
  \item{call}{the matched call.}
  \item{formula}{the formula supplied.}
  \item{terms}{the \code{\link{terms}} object used.}
  \item{data}{the \code{data argument}.}
  \item{offset}{the offset vector used.}
  \item{control}{the value of the \code{control} argument used.}
  \item{method}{the name of the fitter function used, in \R always
    \code{"glm.fit"}.}
  \item{contrasts}{(where relevant) the contrasts used.}
  \item{xlevels}{(where relevant) a record of the levels of the factors
    used in fitting.}

  In addition, non-empty fits will have components \code{qr}, \code{R}
  and \code{effects} relating to the final weighted linear fit.

  Objects of class \code{"glm"} are normally of class \code{c("glm",
    "lm")}, that is inherit from class \code{"lm"}, and well-designed
  methods for class \code{"lm"} will be applied to the weighted linear
  model at the final iteration of IWLS.  However, care is needed, as
  extractor functions for class \code{"glm"} such as
  \code{\link{residuals}} and \code{weights} do \bold{not} just pick out
  the component of the fit with the same name.

  If a \code{\link{binomial}} \code{glm} model is specified by giving a
  two-column response, the weights returned by \code{prior.weights} are
  the total numbers of cases (factored by the supplied case weights) and
  the component \code{y} of the result is the proportion of successes.
}
\seealso{
  \code{\link{anova.glm}}, \code{\link{summary.glm}}, etc. for
  \code{glm} methods,
  and the generic functions \code{\link{anova}}, \code{\link{summary}},
  \code{\link{effects}}, \code{\link{fitted.values}},
  and \code{\link{residuals}}. Further, \code{\link{lm}} for
  non-generalized \emph{linear} models.

  \code{\link{esoph}}, \code{\link{infert}} and
  \code{\link{predict.glm}} have examples of fitting binomial glms.
}
\author{
  The original \R implementation of \code{glm} was written by Simon
  Davies working for Ross Ihaka at the University of Auckland, but has
  since been extensively re-written by members of the R Core team.

  The design was inspired by the S function of the same name described
  in Hastie \& Pregibon (1992).
}
\references{
  Dobson, A. J. (1990)
  \emph{An Introduction to Generalized Linear Models.}
  London: Chapman and Hall.

  Hastie, T. J. and Pregibon, D. (1992)
  \emph{Generalized linear models.}
  Chapter 6 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.

  McCullagh P. and Nelder, J. A. (1989)
  \emph{Generalized Linear Models.}
  London: Chapman and Hall.

  Venables, W. N. and Ripley, B. D. (2002)
  \emph{Modern Applied Statistics with S.}
  New York: Springer.
}

\examples{
## Dobson (1990) Page 93: Randomized Controlled Trial :
counts <- c(18,17,15,20,10,20,25,13,12)
outcome <- gl(3,1,9)
treatment <- gl(3,3)
print(d.AD <- data.frame(treatment, outcome, counts))
glm.D93 <- glm(counts ~ outcome + treatment, family=poisson())
anova(glm.D93)
summary(glm.D93)

## an example with offsets from Venables & Ripley (2002, p.189)
\dontshow{"anorexia" <-
structure(list(Treat = structure(c(2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3
), .Label = c("CBT", "Cont", "FT"), class = "factor"), Prewt = c(80.7,
89.4, 91.8, 74, 78.1, 88.3, 87.3, 75.1, 80.6, 78.4, 77.6, 88.7,
81.3, 78.1, 70.5, 77.3, 85.2, 86, 84.1, 79.7, 85.5, 84.4, 79.6,
77.5, 72.3, 89, 80.5, 84.9, 81.5, 82.6, 79.9, 88.7, 94.9, 76.3,
81, 80.5, 85, 89.2, 81.3, 76.5, 70, 80.4, 83.3, 83, 87.7, 84.2,
86.4, 76.5, 80.2, 87.8, 83.3, 79.7, 84.5, 80.8, 87.4, 83.8, 83.3,
86, 82.5, 86.7, 79.6, 76.9, 94.2, 73.4, 80.5, 81.6, 82.1, 77.6,
83.5, 89.9, 86, 87.3), Postwt = c(80.2, 80.1, 86.4, 86.3, 76.1,
78.1, 75.1, 86.7, 73.5, 84.6, 77.4, 79.5, 89.6, 81.4, 81.8, 77.3,
84.2, 75.4, 79.5, 73, 88.3, 84.7, 81.4, 81.2, 88.2, 78.8, 82.2,
85.6, 81.4, 81.9, 76.4, 103.6, 98.4, 93.4, 73.4, 82.1, 96.7,
95.3, 82.4, 72.5, 90.9, 71.3, 85.4, 81.6, 89.1, 83.9, 82.7, 75.7,
82.6, 100.4, 85.2, 83.6, 84.6, 96.2, 86.7, 95.2, 94.3, 91.5,
91.9, 100.3, 76.7, 76.8, 101.6, 94.9, 75.2, 77.8, 95.5, 90.7,
92.5, 93.8, 91.7, 98)), .Names = c("Treat", "Prewt", "Postwt"
), class = "data.frame", row.names = c("1", "2", "3", "4", "5",
"6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16",
"17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27",
"28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38",
"39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49",
"50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60",
"61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71",
"72"))}
%% "else" (not dontshow)
\dontrun{
## Need the anorexia data from a recent version of the package 'MASS':
library(MASS)
data(anorexia)
}
anorex.1 <- glm(Postwt ~ Prewt + Treat + offset(Prewt),
            family = gaussian, data = anorexia)
summary(anorex.1)

# A Gamma example, from McCullagh & Nelder (1989, pp. 300-2)
clotting <- data.frame(
    u = c(5,10,15,20,30,40,60,80,100),
    lot1 = c(118,58,42,35,27,25,21,19,18),
    lot2 = c(69,35,26,21,18,16,13,12,12))
summary(glm(lot1 ~ log(u), data=clotting, family=Gamma))
summary(glm(lot2 ~ log(u), data=clotting, family=Gamma))
}
\keyword{models}
\keyword{regression}
\eof
\name{glm.control}
\alias{glm.control}
\title{Auxiliary for Controlling GLM Fitting}
\description{
  Auxiliary function as user interface for \code{\link{glm}} fitting.
  Typically only used when calling \code{\link{glm}} or \code{\link{glm.fit}}.
}
\usage{
glm.control(epsilon=1e-8, maxit=25, trace=FALSE)
}
\arguments{
  \item{epsilon}{positive convergence tolerance \eqn{epsilon};
    the iterations converge when \eqn{|dev - devold|/(|dev| + 0.1) < epsilon}.}
  \item{maxit}{integer giving the maximal number of IWLS iterations.}
  \item{trace}{logical indicating if output should be produced for each
    iteration.}
}
\details{
  If \code{epsilon} is small, it is also used as the tolerance for the
  least squares solution.

  When \code{trace} is true, calls to \code{\link{cat}} produce the
  output for each IWLS iteration. Hence, \code{\link{options}(digits = *)}
  can be used to increase the precision, see the example.
}
\value{
  A list with the arguments as components.
}
\references{
  Hastie, T. J. and Pregibon, D. (1992)
  \emph{Generalized linear models.}
  Chapter 6 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\seealso{\code{\link{glm.fit}}, the fitting procedure used by
  \code{\link{glm}}.}
\examples{
### A variation on  example(glm) :

## Annette Dobson's example ...
counts <- c(18,17,15,20,10,20,25,13,12)
outcome <- gl(3,1,9)
treatment <- gl(3,3)
oo <- options(digits = 12) # to see more when tracing :
glm.D93X <- glm(counts ~ outcome + treatment, family=poisson(),
                trace = TRUE, epsilon = 1e-14)
options(oo)
coef(glm.D93X) # the last two are closer to 0 than in ?glm's  glm.D93
# put less so than in R < 1.8.0 when the default was 1e-4
}
\keyword{optimize}
\keyword{models}

\eof
\name{glm.summaries}
\alias{family.glm}
\alias{residuals.glm}
\title{Accessing Generalized Linear Model Fits}
\usage{
\method{family}{glm}(object, \dots)

\method{residuals}{glm}(object, type = c("deviance", "pearson", "working",
                      "response", "partial"), \dots)
}
\arguments{
  \item{object}{an object of class \code{glm}, typically the result of
    a call to \code{\link{glm}}.}
  \item{type}{the type of residuals which should be returned.
    The alternatives are: \code{"deviance"} (default), \code{"pearson"},
    \code{"working"}, \code{"response"}, and \code{"partial"}.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\description{
  These functions are all \code{\link{methods}} for class \code{glm} or
  \code{summary.glm} objects.
}
\details{
  The references define the types of residuals: Davison \& Snell is a
  good reference for the usages of each.
  
  The partial residuals are a matrix of working residuals, with each
  column formed by omitting a term from the model.
}
\seealso{
  \code{\link{glm}} for computing \code{glm.obj}, \code{\link{anova.glm}};
  the corresponding \emph{generic} functions, \code{\link{summary.glm}},
  \code{\link{coef}}, \code{\link{deviance}},
  \code{\link{df.residual}},
  \code{\link{effects}}, \code{\link{fitted}},
  \code{\link{residuals}}.
}
\references{
  Davison, A. C. and Snell, E. J. (1991)
  \emph{Residuals and diagnostics.}  In: Statistical Theory
  and Modelling. In Honour of Sir David Cox, FRS, eds.
  Hinkley, D. V., Reid, N. and Snell, E. J., Chapman \& Hall.
  
  Hastie, T. J. and Pregibon, D. (1992)
  \emph{Generalized linear models.}
  Chapter 6 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.

  McCullagh P. and Nelder, J. A. (1989)
  \emph{Generalized Linear Models.}
  London: Chapman and Hall.
}
\keyword{models}
\keyword{regression}

\eof
\name{gray}
\alias{gray}
\alias{grey}
\title{Gray Level Specification}
\description{
  Create a vector of colors from a vector of gray levels.
}
\usage{
gray(level)
grey(level)
}
\arguments{
  \item{level}{a vector of desired gray levels between \code{0} and
    \code{1}; zero indicates \code{"black"} and one indicates
    \code{"white"}.}
}
\details{
  The values returned by \code{gray} can be used with a \code{col=}
  specification in graphics functions or in \code{\link{par}}.

  \code{grey} is an alias for \code{gray}.
}
\value{
  A vector of \dQuote{colors} of the same length as \code{level}.
}
\seealso{
  \code{\link{rainbow}},
  \code{\link{hsv}},
  \code{\link{rgb}}.
}
\examples{
gray(0:8 / 8)
}
\keyword{color}
\eof
\name{grep}
\title{Pattern Matching and Replacement}
\alias{grep}
\alias{sub}
\alias{gsub}
\alias{regexpr}
\description{
  \code{grep} searches for matches to \code{pattern} (its first
  argument) within the character vector \code{x} (second
  argument).  \code{regexpr} does too, but returns more detail in a
  different format.

  \code{sub} and \code{gsub} perform replacement of matches determined
  by regular expression matching.
}
\usage{
grep(pattern, x, ignore.case = FALSE, extended = TRUE, perl = FALSE,
     value = FALSE, fixed = FALSE)
sub(pattern, replacement, x,
        ignore.case = FALSE, extended = TRUE, perl = FALSE)
gsub(pattern, replacement, x,
        ignore.case = FALSE, extended = TRUE, perl = FALSE)
regexpr(pattern, text,  extended = TRUE, perl = FALSE, fixed = FALSE)
}
\arguments{
  \item{pattern}{character string containing a regular expression (or
    character string for \code{fixed = TRUE}) to be matched in the given
    character vector.}
  \item{x, text}{a character vector where matches are sought.}
  \item{ignore.case}{if \code{FALSE}, the pattern matching is \emph{case
      sensitive} and if \code{TRUE}, case is ignored during matching.}
  \item{extended}{if \code{TRUE}, extended regular expression matching
    is used, and if \code{FALSE} basic regular expressions are used.}
  \item{perl}{logical. Should perl-compatible regexps be used if
    available?  Has priority over \code{extended}.}
  \item{value}{if \code{FALSE}, a vector containing the (\code{integer})
    indices of the matches determined by \code{grep} is returned, and if
    \code{TRUE}, a vector containing the matching elements themselves is
    returned.}
  \item{fixed}{logical.  If \code{TRUE}, \code{pattern} is a string to be
    matched as is.  Overrides all other arguments.} 
  \item{replacement}{a replacement for matched pattern in \code{sub} and
    \code{gsub}.}
}
\details{
  The two \code{*sub} functions differ only in that \code{sub} replaces
  only the first occurrence of a \code{pattern} whereas \code{gsub}
  replaces all occurrences.

  For \code{regexpr} it is an error for \code{pattern} to be \code{NA},
  otherwise \code{NA} is permitted and matches only itself.

  The regular expressions used are those specified by POSIX 1003.2,
  either extended or basic, depending on the value of the
  \code{extended} argument, unless \code{perl = TRUE} when they are
  those of PCRE,
  \url{ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/}.
}
\value{
  For \code{grep} a vector giving either the indices of the elements of
  \code{x} that yielded a match or, if \code{value} is \code{TRUE}, the
  matched elements.

  For \code{sub} and \code{gsub} a character vector of the same length
  as the original.

  For \code{regexpr} an integer vector of the same length as \code{text}
  giving the starting position of the first match, or \eqn{-1} if there
  is none, with attribute \code{"match.length"} giving the length of the
  matched text (or \eqn{-1} for no match).
}
% \note{
%   \code{perl = TRUE} will only be available if \R was compiled against 
%   PCRE: this is detected at configure time.  All Unix and Windows system
%   should have it.
% }
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole (\code{grep})
}
\seealso{
  \code{\link{agrep}} for approximate matching.
  
  \code{\link{tolower}}, \code{\link{toupper}} and \code{\link{chartr}}
  for character translations.
  \code{\link{charmatch}}, \code{\link{pmatch}}, \code{\link{match}}.
  \code{\link{apropos}} uses regexps and has nice examples.
}
\examples{
grep("[a-z]", letters)

txt <- c("arm","foot","lefroo", "bafoobar")
if(any(i <- grep("foo",txt)))
   cat("'foo' appears at least once in\n\t",txt,"\n")
i # 2 and 4
txt[i]

## Double all 'a' or 'b's;  "\\" must be escaped, i.e., 'doubled'
%% and escaped even once more in this *.Rd file!
gsub("([ab])", "\\\\1_\\\\1_", "abc and ABC")

txt <- c("The", "licenses", "for", "most", "software", "are",
  "designed", "to", "take", "away", "your", "freedom",
  "to", "share", "and", "change", "it.",
   "", "By", "contrast,", "the", "GNU", "General", "Public", "License",
   "is", "intended", "to", "guarantee", "your", "freedom", "to",
   "share", "and", "change", "free", "software", "--",
   "to", "make", "sure", "the", "software", "is",
   "free", "for", "all", "its", "users")
( i <- grep("[gu]", txt) ) # indices
stopifnot( txt[i] == grep("[gu]", txt, value = TRUE) )
(ot <- sub("[b-e]",".", txt))
txt[ot != gsub("[b-e]",".", txt)]#- gsub does "global" substitution

txt[gsub("g","#", txt) !=
    gsub("g","#", txt, ignore.case = TRUE)] # the "G" words

regexpr("en", txt)

## trim trailing white space
str = 'Now is the time      '
sub(' +$', '', str)  ## spaces only
sub('[[:space:]]+$', '', str) ## white space, POSIX-style
if(capabilities("PCRE"))
  sub('\\\\s+$', '', str, perl = TRUE) ## perl-style white space
}
\keyword{character}
\keyword{utilities}
\eof
\name{grid}
\alias{grid}
\title{Add Grid to a Plot}
\description{
  \code{grid} adds an \code{nx} by \code{ny} rectangular grid to an
  existing plot.
}
\usage{
grid(nx = NULL, ny = nx, col = "lightgray", lty = "dotted", lwd = NULL,
     equilogs = TRUE)
}
\arguments{
  \item{nx,ny}{number of cells of the grid in x and y direction.  When
    \code{NULL}, as per default, the grid aligns with the tick marks on
    the corresponding \emph{default} axis (i.e., tickmarks as computed by
    \code{\link{axTicks}}).  When \code{\link{NA}}, no grid lines are
    drawn in the corresponding direction.}
  \item{col}{character or (integer) numeric; color of the grid lines.}
  \item{lty}{character or (integer) numeric; line type of the grid lines.}
  \item{lwd}{non-negative numeric giving line width of the grid lines;
    defaults to \code{par("lwd")}.}
  \item{equilogs}{logical, only used when \emph{log} coordinates and
    alignment with the axis tick marks are active.  Setting{equilogs =
      FALSE} in that case gives \emph{non equidistant} tick aligned grid lines.}
}
\note{
  If more fine tuning is required, use \code{\link{abline}(h = ., v = .)}
  directly.
}
\seealso{
  \code{\link{plot}}, \code{\link{abline}}, \code{\link{lines}},
  \code{\link{points}}.
}
\examples{
plot(1:3)
grid(NA, 5, lwd = 2) # grid only in y-direction

data(iris)
## maybe change the desired number of tick marks:  par(lab=c(mx,my,7))
op <- par(mfcol = 1:2)
with(iris,
     {
     plot(Sepal.Length, Sepal.Width, col = as.integer(Species),
          xlim = c(4, 8), ylim = c(2, 4.5), panel.first = grid(),
          main = "with(iris,  plot(...., panel.first = grid(), ..) )")
     plot(Sepal.Length, Sepal.Width, col = as.integer(Species),
          panel.first = grid(3, lty=1,lwd=2),
          main = "... panel.first = grid(3, lty=1,lwd=2), ..")
     }
    )
par(op)

}
\keyword{aplot}
\eof
\name{groupGeneric}
\alias{.Method}
\alias{.Generic}
\alias{.Group}
\alias{.Class}
\alias{Math}
\alias{Math.data.frame}
\alias{Math.factor}
\alias{Ops}
\alias{Ops.data.frame}
\alias{Ops.factor}
\alias{Ops.ordered}
\alias{Summary}
\alias{Summary.data.frame}
\alias{Summary.factor}
\alias{Arith}
\alias{Compare}
\alias{Complex}
\alias{Math2}
\title{Group Generic Functions}
\description{
  Group generic functions can be defined with either S3 and S4 methods
  (with different groups).  Methods are defined for the group of functions
  as a whole.

  A method defined for an individual member of the group takes
  precedence over a method defined for the group as a whole.

  When package \pkg{methods} is attached there are objects visible with
  the names of the group generics: these functions should never be
  called directly (a suitable error message will result if they are).
}
\synopsis{
Math.data.frame(x, \dots)
Math.factor(x, \dots)

Ops.data.frame(e1, e2 = NULL)
Ops.factor(e1, e2)
Ops.ordered(e1, e2)

Summary.data.frame(x, \dots)
Summary.factor(x, \dots)
}
\usage{
## S3 methods have prototypes:
Math(x, \dots)
Ops(e1, e2)
Summary(x, \dots)

## S4 methods have prototypes:
Arith(e1, e2)
Compare(e1, e2)
Ops(e1, e2)
Math(x)
Math2(x, digits)
Summary(x, \dots, na.rm = FALSE)
Complex(z)
}
\arguments{
  \item{x, z, e1, e2}{objects.}
  \item{digits}{number of digits to be used in \code{round} or \code{signif}.}
  \item{\dots}{further arguments passed to or from methods.}
  \item{na.rm}{logical: should missing values be removed?}
}
 
\section{S3 Group Dispatching}{
  %% --------------- grep -nw DispatchGroup src/*/*[ch]

  There are three \emph{groups} for which S3 methods can be written, namely
  the \code{"Math"}, \code{"Ops"} and \code{"Summary"} groups.  These
  are not \R objects, but methods can be supplied for them and base \R
  contain \code{\link{factor}} and \code{\link{data.frame}} methods.
  (There is also a \code{\link{ordered}} method for \code{Ops}.)
  
%   A function \emph{\code{f}} belonging to one of these groups must be
%   \code{\link{.Internal}} or \code{\link{.Primitive}} and will
%   automatically be using \emph{\code{<grp>.<class> (ob)}} when
%   \emph{\code{f(<ob>)}} is called, \emph{\code{f}} belongs to group
%   \emph{\code{<grp>}} and \emph{\code{<ob>}} is of
%   \code{\link[base]{class}} \emph{\code{<class>}}.
    
  \enumerate{
    \item Group \code{"Math"}:
    \itemize{
      \item
      \code{abs}, \code{sign}, \code{sqrt}, \cr
      \code{floor}, \code{ceiling}, \code{trunc},\cr
      \code{round}, \code{signif}

      \item \code{exp}, \code{log}, \cr
      \code{cos}, \code{sin}, \code{tan},\cr
      \code{acos}, \code{asin}, \code{atan}
      
      \code{cosh}, \code{sinh}, \code{tanh},\cr
      \code{acosh}, \code{asinh}, \code{atanh}
            
      \item
      \code{lgamma}, \code{gamma}, \code{gammaCody},\cr
      \code{digamma}, \code{trigamma}, \code{tetragamma},
      \code{pentagamma}
      %   do_math1() [arithmetic.c:794]: if (DispatchGroup("Math",...))
      % 
      %
      % "atan", "round", "log", "signif":
      % do_atan()  [arithmetic.c:958]: if (DispatchGroup("Math", ..))
      % do_round() [arithmetic.c:981]: if (DispatchGroup("Math", ..))
      % do_log()   [arithmetic.c:1011]:if (DispatchGroup("Math", ..))
      % do_signif()[arithmetic.c:1034]:if (DispatchGroup("Math", ..))
      
      \item \code{cumsum}, \code{cumprod}, \code{cummax}, \code{cummin}
      % do_cum()   [cum.c:140]:    if (DispatchGroup("Math", ...))
    }
        
    \item Group \code{"Ops"}:
    \itemize{
      \item
      \code{"+"}, \code{"-"}, \code{"*"}, \code{"/"},
      \code{"^"}, \code{"\%\%"}, \code{"\%/\%"}
      % do_arith() [arithmetic.c:240]: if (DispatchGroup("Ops", ...))
            
      \item \code{"&"}, \code{"|"}, \code{"!"}
      % do_logic() [logic.c:32]:   if (DispatchGroup("Ops",...))
            
      \item \code{"=="}, \code{"!="}, 
      \code{"<"}, \code{"<="}, \code{">="}, \code{">"}
      % do_relop() [relop.c:35]:   if (DispatchGroup("Ops", ...))
    }
        
    \item Group \code{"Summary"}:
    \itemize{
      \item \code{all}, \code{any}
      % do_logic3()[logic.c:278]:  if(DispatchGroup("Summary", ...))
      \item \code{sum}, \code{prod}
      % /*NOMORE:\code{mean}, */
      \item \code{min}, \code{max}
      % do_summary() [summary.c:322]: if(DispatchGroup("Summary",...))
      \item \code{range}
    }
  }

  The number of arguments supplied for \code{"Math"} group generic
  methods is not checked prior to dispatch. (Prior to \R 1.7.0, all
  those whose default method has one argument were checked, but the
  others were not.)
}
\section{S4 Group Dispatching}{
  When package \pkg{methods} is attached, formal (S4) methods can be
  defined for groups.
  
  The functions belonging to the various groups are as follows:
  \describe{
    \item{\code{Arith}}{\code{"+"}, \code{"-"}, \code{"*"}, \code{"^"},
      \code{"\%\%"}, \code{"\%/\%"}, \code{"/"}}
    \item{\code{Compare}}{\code{"=="}, \code{">"}, \code{"<"},
      \code{"!="}, \code{"<="}, \code{">="}}
    \item{\code{Ops}}{\code{"Arith"}, \code{"Compare"}}
    \item{\code{Math}}{\code{"log"}, \code{"sqrt"}, \code{"log10"},
      \code{"cumprod"}, \code{"abs"}, \code{"acos"}, \code{"acosh"},
      \code{"asin"}, \code{"asinh"}, \code{"atan"}, \code{"atanh"},
      \code{"ceiling"}, \code{"cos"}, \code{"cosh"}, \code{"cumsum"},
      \code{"exp"}, \code{"floor"}, \code{"gamma"}, \code{"lgamma"},
      \code{"sin"}, \code{"sinh"}, \code{"tan"}, \code{"tanh"},
      \code{"trunc"}}
    \item{\code{Math2}}{\code{"round"}, \code{"signif"}}
    \item{\code{Summary}}{\code{"max"}, \code{"min"}, \code{"range"},
      \code{"prod"}, \code{"sum"}, \code{"any"}, \code{"all"}}
    \item{\code{Complex}}{\code{"Arg"}, \code{"Conj"}, \code{"Im"},
      \code{"Mod"}, \code{"Re"}}
  }
  Functions with the group names exist in the \pkg{methods} package but
  should not be called directly.

  All the functions in these groups (other than the group generics
  themselves) are basic functions in R.  They are not by default S4 generic
  functions, and many of them are defined as primitives, meaning that
  they do not have formal arguments.  However, you can still define
  formal methods for them.  The effect of doing so is to create an S4 generic
  function with the appropriate arguments, in the environment where the
  method definition is to be stored.  It all works more or less as you
  might expect, admittedly via a bit of trickery in the background.
}
\references{
  Appendix A, \emph{Classes and Methods} of\cr
  Chambers, J. M.  and Hastie, T. J. eds (1992)
  \emph{Statistical Models in S.}
  Wadsworth & Brooks/Cole.
}
\seealso{
  \code{\link{methods}} for methods of non-Internal generic functions.
}
\examples{
methods("Math")
methods("Ops")
methods("Summary")

d.fr <- data.frame(x=1:9, y=rnorm(9))
data.class(1 + d.fr) == "data.frame" ##-- add to d.f. ...
}
\keyword{methods}
\eof
\name{gzcon}
\alias{gzcon}
\title{
  (De)compress I/O Through Connections
}
\description{
  \code{gzcon} provides a modified connection that wraps an existing
  connection, and decompresses reads or compresses writes through that
  connection.  Standard \code{gzip} headers are assumed.
}
\usage{
gzcon(con, level = 6, allowNonCompressed = TRUE)
}
\arguments{
  \item{con}{a connection.}
  \item{level}{integer between 0 and 9, the compression level when writing.}
  \item{allowNonCompressed}{logical.  When reading, should
    non-compressed files (lacking the \code{gzip} magic header) be allowed?}
}
\details{
  If \code{con} is open then the modified
  connection is opened.  Closing the
  wrapper connection will also close the underlying connection.

  Reading from a connection which does not supply a \code{gzip} magic
  header is equivalent to reading from the original connection if
  \code{allowNonCompressed} is true, otherwise an error.

  The original connection is unusable: any object pointing to it will
  now refer to the modified connection.
}
\value{
  An object inheriting from class \code{"connection"}.  This is the same
  connection \emph{number} as supplied, but with a modified internal structure.
}
\seealso{\code{\link{gzfile}}}
\examples{
\dontrun{## This example may not still be available
## print the value to see what objects were created.
con <- url("http://hesweb1.med.virginia.edu/biostat/s/data/sav/kprats.sav")
print(load(con))}

## gzfile and gzcon can inter-work.
## Of course here one would used gzfile, but file() can be replaced by
## any other connection generator.
zz <- gzfile("ex.gz", "w")
cat("TITLE extra line", "2 3 5 7", "", "11 13 17", file = zz, sep = "\n")
close(zz)
readLines(zz<-gzcon(file("ex.gz")))
close(zz)
unlink("ex.gz")

zz <- gzcon(file("ex.gz", "wb"))
cat("TITLE extra line", "2 3 5 7", "", "11 13 17", file = zz, sep = "\n")
close(zz)
readLines(zz<-gzfile("ex.gz"))
close(zz)
unlink("ex.gz")
}
\keyword{file}
\keyword{connection}
\eof
\name{help}
\alias{help}
\alias{?}
\alias{topicName}               % internal
\alias{.helpForCall}		% internal
\alias{.tryHelp}		% internal
\title{Documentation}
\description{
  These functions provide access to documentation.
  Documentation on a topic with name \code{name} (typically, an \R
  object or a data set) can be printed with either \code{help(name)} or
  \code{?name}.
}
\usage{
help(topic, offline = FALSE, package = .packages(),
     lib.loc = NULL, verbose = getOption("verbose"),
     try.all.packages = getOption("help.try.all.packages"),
#ifdef unix
     htmlhelp = getOption("htmlhelp"),
#endif
#ifdef windows
     chmhelp = getOption("chmhelp"),
     htmlhelp = getOption("htmlhelp"), winhelp = getOption("winhelp"),
#endif
     pager = getOption("pager"))
?topic
type?topic
}
\arguments{
 \item{topic}{usually, the name on  which documentation is sought.
   The name may be quoted or unquoted (but note that if \code{topic}
   is the name of a
   variable containing a character string  documentation is provided for
   the name, not for the character string).

   The \code{topic} argument may also be a function call, to ask for
   documentation on a corresponding method.  See the section on method
   documentation.
 }
 \item{offline}{a logical indicating whether documentation should be
   displayed on-line to the screen (the default) or hardcopy of it
   should be produced.}
 \item{package}{a name or character vector giving the packages to look
   into for documentation.  By default, all packages in the search path
   are used.}
 \item{lib.loc}{a character vector of directory names of \R libraries,
   or \code{NULL}.  The default value of \code{NULL} corresponds to all
   libraries currently known.  If the default is used, the loaded
   packages are searched before the libraries.}
 \item{verbose}{logical; if \code{TRUE}, the file name is reported.}
 \item{try.all.packages}{logical; see \code{Notes}.}
#ifdef unix
 \item{htmlhelp}{logical (or \code{NULL}).  If \code{TRUE} (which is the
   default after \code{\link{help.start}} has been called), the HTML
   version of the help will be shown in the browser specified by
   \code{options("browser")}.  See \code{\link{browseURL}} for details
   of the browsers that are supported.  Where possible an existing
   browser window is re-used.}
#endif
#ifdef windows
  \item{chmhelp}{logical (or \code{NULL}).  If \code{TRUE} the
    Compiled HTML version of the help will be shown in a help viewer.}
  \item{htmlhelp}{logical (or \code{NULL}).  If \code{TRUE}, the HTML
    version of the help will be shown in a browser specified by
    \code{options("browser")} or the file-association mechanism.
  }
  \item{winhelp}{logical (or \code{NULL}).  If \code{TRUE}, a Windows
    \code{.hlp} file will be used if one is available.}
#endif
  \item{pager}{the pager to be used for \code{\link{file.show}}.}
  \item{type}{the special type of documentation to use for this topic;
      for example, if the type is \code{class}, documentation is
      provided for the class with name \code{topic}.  The function
      \code{topicName} returns the actual name used in this case.
    See the section on method documentation for the uses of
      \code{type} to get help on formal methods.}
}
\details{
  In the case of unary and binary operators and control-flow special
  forms (including \code{if}, \code{for} and \code{function}), the topic
  may need to be quoted.

#ifdef unix
  If \code{offline} is \code{TRUE}, hardcopy of the documentation is
  produced by running the LaTeX version of the help page through
  \code{latex} (note that LaTeX 2e is needed) and \code{dvips}.
  Depending on your \code{dvips} configuration, hardcopy will be sent to
  the printer or saved in a file.  If the programs are in non-standard
  locations and hence were not found at compile time, you can either set
  the options \code{latexcmd} and \code{dvipscmd}, or the environment
  variables \env{R\_LATEXCMD} and \env{R\_DVIPSCMD} appropriately.
  The appearance of the output can be customized through a file
  \file{Rhelp.cfg} somewhere in your LaTeX search path.
#endif
#ifdef windows
  If \code{offline} is \code{TRUE}, hardcopy of the documentation is
  produced by running the LaTeX version of the help page through
  \code{latex} (note that LaTeX 2e is needed).  You need to customize
  the file \file{R\_HOME/bin/helpPRINT.bat} which contains an example.
  The appearance of the output can be customized through a file
  \file{Rhelp.cfg} somewhere in your LaTeX search path.
#endif

}
\note{
  Unless \code{lib.loc} is specified explicitly, the loaded packages are
  searched before those in the specified libraries.  This ensures that
  if a library is loaded from a library not in the known library trees,
  then the help from the loaded library is used.  If \code{lib.loc} is
  specified explicitly, the loaded packages are \emph{not} searched.

  If this search fails and argument \code{try.all.packages} is
  \code{TRUE} and neither \code{packages} nor \code{lib.loc} is
  specified, then all the packages in the known library trees are
  searched for help on \code{topic} and a list of (any) packages where
  help may be found is printed (but no help is shown).
  \bold{N.B.} searching all packages can be slow.

  The help files can be many small files.  On some file systems it is
  desirable to save space, and the text files in the \file{help} directory
  of an installed package can be zipped up as a zip archive
  \file{Rhelp.zip}. Ensure that file \file{AnIndex} remains un-zipped.
  Similarly, all the files in the \file{latex} directory can be zipped
  to \file{Rhelp.zip}.
#ifdef windows
  This is done on Windows for the larger packages.
#endif
}

\section{Method Documentation.}{
  The authors of formal (\sQuote{S4}) methods can provide documentation
  on specific methods, as well as overall documentation on the methods
  of a particular function.  The \code{"?"} operator allows access to
  this documentation in three ways.

  The expression \code{methods ? f} will look for the overall
  documentation methods for the function \code{f}.  Currently, this
  means the documentation file containing the alias \code{f-methods}.
  
  There are two different ways to look for documentation on a
  particular method.  The first is to supply the \code{topic} argument
  in the form of a function call, omitting the \code{type} argument.
  The effect is to look for documentation on the method that would be
  used if this function call were actually evaluated. See the examples
  below.  If the function is not a generic (no S4 methods are defined
  for it), the help reverts to documentation on the function name.

  The \code{"?"} operator can also be called with \code{type} supplied
  as \code{"method"}; in this case also, the \code{topic} argument is
  a function call, but the arguments are now interpreted as specifying
  the class of the argument, not the actual expression that will
  appear in a real call to the function.  See the examples below.
  
  The first approach will be tedious if the actual call involves
  complicated expressions, and may be slow if the arguments take a
  long time to evaluate.  The second approach avoids these
  difficulties, but you do have to know what the classes of the actual
  arguments will be when they are evaluated.

  Both approaches make use of any inherited methods; the signature of
  the method to be looked up is found by using \code{selectMethod}
 (see the documentation for  \code{\link[methods]{getMethod}}).

  
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{help.search}()} for finding help pages on a \dQuote{vague}
  topic;
  \code{\link{help.start}()} which opens the HTML version of the \R
  help pages;
  \code{\link{library}()} for listing available packages and the
  user-level objects they contain;
  \code{\link{data}()} for listing available data sets;
  \code{\link{methods}()}.

  See \code{\link{prompt}()} to get a prototype for writing \code{help}
  pages of private packages.
}
\examples{
help()
help(help)              # the same

help(lapply)
?lapply                 # the same

help("for")             # or ?"for", but the quotes are needed
?"+"

help(package = stepfun) # get help even when package is not loaded

data()                  # list all available data sets
?women                  # information about data set "women"

topi <- "women"
\dontrun{help(topi) ##--> Error: No documentation for 'topi'}

try(help("bs", try.all.packages=FALSE)) # reports not found (an error)
help("bs", try.all.packages=TRUE) # reports can be found in package 'splines'
}
\keyword{documentation}
\eof
\name{help.search}
\alias{help.search}
\alias{print.hsearch}
\title{Search the Help System}
\description{
  Allows for searching the help system for documentation matching a
  given character string in the (file) name, alias, title, or keyword
  entries (or any combination thereof), using either fuzzy matching or
  regular expression matching.  Names and titles of the matched help
  entries are nicely displayed.
}
\usage{
help.search(pattern, fields = c("alias", "concept", "title"),
            apropos, keyword, whatis, ignore.case = TRUE,
            package = NULL, lib.loc = NULL,
            help.db = getOption("help.db"),
            verbose = getOption("verbose"),
            rebuild = FALSE, agrep = NULL)
}
\arguments{
  \item{pattern}{a character string to be matched in the specified
    fields.  If this is given, the arguments \code{apropos},
    \code{keyword}, and \code{whatis} are ignored.}
  \item{fields}{a character vector specifying the fields of the help
    data bases to be searched.  The entries must be abbreviations of
    \code{"name"}, \code{"title"}, \code{"alias"}, \code{"concept"}, and
    \code{"keyword"}, corresponding to the help page's (file) name, its
    title, the topics and concepts it provides documentation for, and
    the keywords it can be classified to.}
  \item{apropos}{a character string to be matched in the help page
    topics and title.}
  \item{keyword}{a character string to be matched in the help page
    keywords.}
  \item{whatis}{a character string to be matched in the help page
    topics.}
  \item{ignore.case}{a logical.  If \code{TRUE}, case is ignored during
    matching; if \code{FALSE}, pattern matching is case sensitive.}
  \item{package}{a character vector with the names of packages to
    search through, or \code{NULL} in which case \emph{all} available
    packages in the library trees specified by \code{lib.loc} are
    searched.}
  \item{lib.loc}{a character vector describing the location of \R
    library trees to search through, or \code{NULL}.  The default value
    of \code{NULL} corresponds to all libraries currently known.}
  \item{help.db}{a character string giving the file path to a previously
    built and saved help data base, or \code{NULL}.}
  \item{verbose}{logical; if \code{TRUE}, the search process is traced.}
  \item{rebuild}{a logical indicating whether the help data base should
    be rebuilt.}
  \item{agrep}{if \code{NULL} (the default) and the character string to
    be matched consists of alphanumeric characters, whitespace or a dash
    only, approximate (fuzzy) matching via \code{\link{agrep}} is used
    unless the string has fewer than 5 characters; otherwise, it is
    taken to contain a regular expression to be matched via
    \code{\link{grep}}.  If \code{FALSE}, approximate matching is not
    used.  Otherwise, one can give a numeric or a list specifying the
    maximal distance for the approximate match, see argument
    \code{max.distance} in the documentation for \code{\link{agrep}}.}
}
\details{
  Upon installation of a package, a contents data base which contains
  the information on name, title, aliases and keywords and, concepts
  starting with \R 1.8, is computed from the Rd files in the package and
  serialized as \file{Rd.rds} in the \file{Meta} subdirectory of the
  top-level package installation directory (or, prior to \R 1.7, as
  \file{CONTENTS} in Debian Control Format with aliases and keywords
  collapsed to character strings in the top-level package installation
  directory).  This, or a pre-built help.search index serialized as
  \file{hsearch.rds} in the \file{Meta} directory, is the data base
  searched by \code{help.search()}.

  The arguments \code{apropos} and \code{whatis} play a role similar to
  the Unix commands with the same names.

  If possible, the help data base is saved to the file \file{help.db} in
  the \file{.R} subdirectory of the user's home directory or the current
  working directory.

  Note that currently, the aliases in the matching help files are not
  displayed.
}
\value{
  The results are returned in an object of class \code{"hsearch"}, which
  has a print method for nicely displaying the results of the query.
  This mechanism is experimental, and may change in future versions of
  R.
}
\seealso{
  \code{\link{help}};
  \code{\link{help.start}} for starting the hypertext (currently HTML)
  version of \R's online documentation, which offers a similar search
  mechanism.

  \code{\link{apropos}} uses regexps and has nice examples.
}
\examples{
help.search("linear models")    # In case you forgot how to fit linear
                                # models
help.search("non-existent topic")
\dontrun{
help.search("print")            # All help pages with topics or title
                                # matching 'print'
help.search(apropos = "print")  # The same

help.search(keyword = "hplot")  # All help pages documenting high-level
                                # plots.

## Help pages with documented topics starting with 'try'.
help.search("\\\\btry", fields = "alias")
## Do not use '^' or '$' when matching aliases or keywords
## (unless all packages were installed using R 1.7 or newer).
}
}
\keyword{documentation}
\eof
\name{help.start}
\title{Hypertext Documentation}
\alias{help.start}
\description{
  Start the hypertext (currently HTML) version of \R's online
  documentation.
}
\usage{
#ifdef unix  
help.start(gui = "irrelevant", browser = getOption("browser"),
           remote = NULL)
#endif
#ifdef windows  
help.start(update = TRUE, gui = "irrelevant",
           browser = getOption("browser"))
#endif
}
\arguments{
  \item{gui}{just for compatibility with S-PLUS.}
  \item{browser}{the name of the program to be used as hypertext
    browser. It should be in the PATH, or a full path specified.
  }
#ifdef unix  
  \item{remote}{A character giving a valid URL for the \file{\$R\_HOME}
    directory on a remote location.}
#endif
#ifdef windows  
  \item{update}{logical: should this attempt to update the indices to
    reflect the currently installed packages.}
#endif
}
\details{
#ifdef unix
  All the packages in the known library trees are linked to directory
  \file{.R} in the per-session temporary directory.  The links are
  re-made each time \code{help.start} is run, which should be done
  after packages are installed, updated or removed.

  If the browser given by the \code{browser} argument is different from
  the default browser as specified by \code{options("browser")}, the
  default is changed to the given browser so that it gets used for all
  future help requests.
#endif
#ifdef windows
  The Windows file association mechanism is used to send the HTML file
  to a browser, launching one if necessary.

  Unlike Unix systems, running \code{help.start} does not send all
  future help requests to the browser: use \code{options(htmlhelp=TRUE)}
  to set that.

  Alternatively, a specific browser can be started if \code{browser} is
  specified, but \code{help} will still use the file association mechanism.

  \code{help.start} and the Java-based search engine have been tested
  under Internet Explorer 6, Netscape 6.2.3/7.0, Opera 6.01 and
  Mozilla 1.0.
#endif
}

\seealso{
  \code{\link{help}()} for on- and off-line help in ASCII/Editor or
  PostScript format.

  \code{\link{browseURL}} for how the help file is displayed.
}
\examples{
\dontrun{help.start()
#ifdef windows
help.start(browser="C:\\\\Program Files\\\\Internet Explorer\\\\IEXPLORE.EXE")
help.start(browser="C:/Program Files/Netscape/Netscape/netscp.exe")
help.start(browser="C:/Program Files/Opera/Opera.exe")
#endif
}}
\keyword{documentation}
\eof
\name{hist.POSIXt}
\alias{hist.POSIXt}
\title{Histogram of a Date-Time Object}
\description{
  Method for \code{\link{hist}} applied to date-time objects.
}
\usage{
\method{hist}{POSIXt}(x, breaks, \dots, plot = TRUE, freq = FALSE,
     start.on.monday = TRUE, format)
}
\synopsis{
hist.POSIXt(x, breaks, ..., xlab = deparse(substitute(x)),
            plot = TRUE, freq = FALSE,
            start.on.monday = TRUE, format)
}
\arguments{
  \item{x}{an object inheriting from class \code{"POSIXt"}.}
  \item{breaks}{
    a vector of cut points \emph{or} number giving the number of
    intervals which \code{x} is to be cut into \emph{or} an
    interval specification, one of \code{"secs"}, \code{"mins"},
    \code{"hours"}, \code{"days"}, \code{"weeks"}, \code{"months"}
    or \code{"years"}.
 }
  \item{\dots}{graphical parameters, or arguments to
    \code{\link{hist.default}} such as \code{include.lowest},
      \code{right} and \code{labels}.}
  \item{plot}{logical.  If \code{TRUE} (default), a histogram is
    plotted, otherwise a list of breaks and counts is returned.}
  \item{freq}{logical; if \code{TRUE}, the
    histogram graphic is a representation of frequencies, i.e,
    the \code{counts} component of the result; if \code{FALSE},
    \emph{relative} frequencies (\dQuote{probabilities}) are plotted.}
  \item{start.on.monday}{logical. If \code{breaks = "weeks"}, should the
    week start on Mondays or Sundays?}
  \item{format}{for the x-axis labels. See \code{\link{strptime}}.}
}
\value{
  An object of class \code{"histogram"}: see \code{\link{hist}}.
}
\seealso{
  \code{\link{seq.POSIXt}}, \code{\link{axis.POSIXct}}, \code{\link{hist}}
}
\examples{
hist(.leap.seconds, "years", freq = TRUE)
hist(.leap.seconds,
     seq(ISOdate(1970, 1, 10), ISOdate(2002, 1, 1), "5 years"))

## 100 random dates in a 10-week period
random.dates <- ISOdate(2001, 1, 1) + 70*86400*runif(100)
hist(random.dates, "weeks", format = "\%d \%b")
}
\keyword{chron}
\keyword{dplot}
\keyword{hplot}
\eof
\name{hist}
\title{Histograms}
\usage{
hist(x, \dots)

\method{hist}{default}(x, breaks = "Sturges", freq = NULL, probability = !freq,
     include.lowest = TRUE, right = TRUE,
     density = NULL, angle = 45, col = NULL, border = NULL,
     main = paste("Histogram of" , xname),
     xlim = range(breaks), ylim = NULL,
     xlab = xname, ylab,
     axes = TRUE, plot = TRUE, labels = FALSE,
     nclass = NULL, \dots)
}
\alias{hist}
\alias{hist.default}
\arguments{
  \item{x}{a vector of values for which the histogram is desired.}
  \item{breaks}{one of:
    \itemize{
      \item a vector giving the breakpoints between histogram cells,
      \item a single number giving the number of cells for the histogram,
      \item a character string naming an algorithm to compute the
      number of cells (see Details),
      \item a function to compute the number of cells.
    }
    In the last three cases the number is a suggestion only.
  }
  \item{freq}{logical; if \code{TRUE}, the histogram graphic is a
    representation of frequencies, the \code{counts} component of
    the result; if \code{FALSE}, \emph{relative} frequencies
    (\dQuote{probabilities}), component \code{density},
    are plotted.   Defaults to \code{TRUE} \emph{iff} \code{breaks} are
    equidistant (and \code{probability} is not specified).}
  \item{probability}{an \emph{alias} for \code{!freq}, for S compatibility.}
  \item{include.lowest}{logical; if \code{TRUE}, an \code{x[i]} equal to
    the \code{breaks} value will be included in the first (or last, for
    \code{right = FALSE}) bar.  This will be ignored (with a warning)
    unless \code{breaks} is a vector.}
  \item{right}{logical; if \code{TRUE}, the histograms cells are
    right-closed (left open) intervals.}

  \item{density}{the density of shading lines, in lines per inch.
    The default value of \code{NULL} means that no shading lines
    are drawn. Non-positive values of \code{density} also inhibit the
    drawing of shading lines.}
  \item{angle}{the slope of shading lines, given as an angle in
    degrees (counter-clockwise).}
  \item{col}{a colour to be used to fill the bars.
    The default of \code{NULL} yields unfilled bars.}
  \item{border}{the color of the border around the bars.  The default
    is to use the standard foreground color.}
  \item{main, xlab, ylab}{these arguments to \code{title} have useful
    defaults here.}
  \item{xlim, ylim}{the range of x and y values with sensible defaults.
    Note that \code{xlim} is \emph{not} used to define the histogram (breaks),
    but only for plotting (when \code{plot = TRUE}).}
  \item{axes}{logical.  If \code{TRUE} (default), axes are draw if the
    plot is drawn.}
  \item{plot}{logical.  If \code{TRUE} (default), a histogram is
    plotted, otherwise a list of breaks and counts is returned.}
  \item{labels}{logical or character.  Additionally draw labels on top
    of bars, if not \code{FALSE}; see \code{\link{plot.histogram}}.}
  \item{nclass}{numeric (integer).  For S(-PLUS) compatibility only,
    \code{nclass} is equivalent to \code{breaks} for a scalar or
    character argument.}
  \item{\dots}{further graphical parameters to \code{title} and \code{axis}.}
}
\description{
  The generic function \code{hist} computes a histogram of the given
  data values.  If \code{plot=TRUE}, the resulting object of
  \code{\link[base]{class} "histogram"} is plotted by
  \code{\link{plot.histogram}}, before it is returned.
}
\details{
  The definition of \dQuote{histogram} differs by source (with
  country-specific biases).  \R's default with equi-spaced breaks (also
  the default) is to plot the counts in the cells defined by
  \code{breaks}. Thus the height of a rectangle is proportional to
  the number of points falling into the cell, as is the area
  \emph{provided} the breaks are equally-spaced.

  The default with non-equi-spaced breaks is to give
  a plot of area one, in which the \emph{area} of the rectangles is the
  fraction of the data points falling in the cells.

  If \code{right = TRUE} (default), the histogram cells are intervals
  of the form \code{(a, b]}, i.e., they include their right-hand endpoint,
  but not their left one, with the exception of the first cell when
  \code{include.lowest} is \code{TRUE}.

  For \code{right = FALSE}, the intervals are of the form \code{[a, b)},
  and \code{include.lowest} really has the meaning of
  \dQuote{\emph{include highest}}.

  A numerical tolerance of \eqn{10^{-7}}{1e-7} times the range of the
  breaks is applied when counting entries on the edges of bins.

  The default for \code{breaks} is \code{"Sturges"}: see
  \code{\link{nclass.Sturges}}.  Other names for which algorithms
  are supplied are \code{"Scott"} and \code{"FD"} /
  \code{"Friedman-Diaconis"} (with corresponding functions
  \code{\link{nclass.scott}} and \code{\link{nclass.FD}}).
  Case is ignored and partial matching is used.
  Alternatively, a function can be supplied which
  will compute the intended number of breaks as a function of \code{x}.
}
\value{
  an object of class \code{"histogram"} which is a list with components:
  \item{breaks}{the \eqn{n+1} cell boundaries (= \code{breaks} if that
  was a vector).}
  \item{counts}{\eqn{n} integers; for each cell, the number of
    \code{x[]} inside.}
  \item{density}{values \eqn{\hat f(x_i)}{f^(x[i])}, as estimated
    density values. If \code{all(diff(breaks) == 1)}, they are the
    relative frequencies \code{counts/n} and in general satisfy
    \eqn{\sum_i \hat f(x_i) (b_{i+1}-b_i) = 1}{sum[i; f^(x[i])
      (b[i+1]-b[i])] = 1}, where \eqn{b_i}{b[i]} = \code{breaks[i]}.}
  \item{intensities}{same as \code{density}. Deprecated, but retained
    for compatibility.}
  \item{mids}{the \eqn{n} cell midpoints.}
  \item{xname}{a character string with the actual \code{x} argument name.}
  \item{equidist}{logical, indicating if the distances between
    \code{breaks} are all the same.}
}
\note{
  The resulting value does \emph{not} depend on the values of
  the arguments \code{freq} (or \code{probability})
  or \code{plot}.  This is intentionally different from S.

  Prior to \R 1.7.0, the element \code{breaks} of the result was
  adjusted for numerical tolerances.  The nominal values are now
  returned even though tolerances are still used when counting.
}

\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Venables, W. N. and Ripley. B. D. (2002)
  \emph{Modern Applied Statistics with S}.  Springer.
}

\seealso{
  \code{\link{nclass.Sturges}}, \code{\link{stem}},
  \code{\link{density}},  \code{\link[MASS]{truehist}}.
}

\examples{
data(islands)
op <- par(mfrow=c(2, 2))
hist(islands)
str(hist(islands, col="gray", labels = TRUE))

hist(sqrt(islands), br = 12, col="lightblue", border="pink")
##-- For non-equidistant breaks, counts should NOT be graphed unscaled:
r <- hist(sqrt(islands), br = c(4*0:5, 10*3:5, 70, 100, 140), col='blue1')
text(r$mids, r$density, r$counts, adj=c(.5, -.5), col='blue3')
sapply(r[2:3], sum)
sum(r$density * diff(r$breaks)) # == 1
lines(r, lty = 3, border = "purple") # -> lines.histogram(*)
par(op)

str(hist(islands, plot= FALSE))        #-> 5  breaks
str(hist(islands, br=12, plot= FALSE)) #-> 10 (~= 12) breaks
str(hist(islands, br=c(12,20,36,80,200,1000,17000), plot = FALSE))
    hist(islands, br=c(12,20,36,80,200,1000,17000), freq = TRUE,
         main = "WRONG histogram") # and warning
}
\keyword{dplot}
\keyword{hplot}
\keyword{distribution}
\eof
\name{hsv}
\alias{hsv}
\title{HSV Color Specification}
\description{
  Create a vector of colors from vectors specifying hue, saturation and
  value.
}
\usage{
hsv(h=1, s=1, v=1, gamma=1)
}
\arguments{
  \item{h,s,v}{numeric vectors of values in the range \code{[0,1]} for
    \dQuote{hue}, \dQuote{saturation} and \dQuote{value} to be combined
    to form a vector of colors.  Values in shorter arguments are
    recycled.}
  \item{gamma}{a \dQuote{gamma correction}}
}
\value{
  This function creates a vector of \dQuote{colors} corresponding to the
  given values in HSV space.  The values returned by \code{hsv} can be
  used with a \code{col=} specification in graphics functions or in
  \code{par}.
}
\section{Gamma correction}{
  For each color, \eqn{(r,g,b)} in RGB space (with all values in \eqn{[0,1]}),
  the final color corresponds to \eqn{(r^gamma, g^gamma, b^gamma)}.
}
\seealso{
  \code{\link{rainbow}},
  \code{\link{rgb}},
  \code{\link{gray}}.
}
\examples{
hsv(.5,.5,.5)

## Look at gamma effect:
n <- 20;  y <- -sin(3*pi*((1:n)-1/2)/n)
op <- par(mfrow=c(3,2),mar=rep(1.5,4))
for(gamma in c(.4, .6, .8, 1, 1.2, 1.5))
  plot(y, axes = FALSE, frame.plot = TRUE,
       xlab = "", ylab = "", pch = 21, cex = 30,
       bg = rainbow(n, start=.85, end=.1, gamma = gamma),
       main = paste("Red tones;  gamma=",format(gamma)))
par(op)
}
\keyword{color}
\keyword{dplot}
\eof
\name{identical}
\alias{identical}
\title{ Test Objects for Exact Equality }
\description{
  The safe and reliable way to test two objects for being
  \emph{exactly} equal.  It returns \code{TRUE} in this case,
  \code{FALSE} in every other case.
}
\usage{
identical(x, y)
}
\arguments{
  \item{x, y}{any \R objects.}
}
\details{
  A call to \code{identical} is the way to test exact equality in
  \code{if} and \code{while} statements, as well as in logical
  expressions that use \code{&&} or \code{||}.  In all these
  applications you need to be assured of getting a single logical
  value.

  Users often use the comparison operators, such as \code{==} or
  \code{!=}, in these situations.  It looks natural, but it is not what
  these operators are designed to do in R.  They return an object like
  the arguments.  If you expected \code{x} and \code{y} to be of length
  1, but it happened that one of them wasn't, you will \emph{not} get a
  single \code{FALSE}.  Similarly, if one of the arguments is \code{NA},
  the result is also \code{NA}.  In either case, the expression
  \code{if(x == y)....} won't work as expected.

  The function \code{all.equal} is also sometimes used to test equality
  this way, but it was intended for something different.  First, it
  tries to allow for \dQuote{reasonable} differences in numeric results.
  Second, it returns a descriptive character vector instead of
  \code{FALSE} when the objects do not match.  Therefore, it is not the
  right function to use for reliable testing either.  (If you \emph{do} want
  to allow for numeric fuzziness in comparing objects, you can combine
  \code{all.equal} and \code{identical}, as shown in the examples
  below.)

  The computations in \code{identical} are also reliable and usually
  fast.  There should never be an error.  The only known way to kill
  \code{identical} is by having an invalid pointer at the C level,
  generating a memory fault.  It will usually find inequality quickly.
  Checking equality for two large, complicated objects can take longer
  if the objects are identical or nearly so, but represent completely
  independent copies.  For most applications, however, the computational cost
  should be negligible.

  As from \R 1.6.0, \code{identical} sees \code{NaN} as different from
  \code{as.double(NA)}, but all \code{NaN}s are equal (and all \code{NA}
  of the same type are equal).
}
\value{
  A single logical value, \code{TRUE} or \code{FALSE}, never \code{NA}
  and never anything other than a single value.
}
\author{John Chambers}

\references{
  Chambers, J. M. (1998)
  \emph{Programming with Data. A Guide to the S Language}.
  Springer.
}
\seealso{
  \code{\link{all.equal}} for descriptions of how two objects differ;
  \link{Comparison} for operators that generate elementwise comparisons.
}
\examples{
identical(1, NULL) ## FALSE -- don't try this with ==
identical(1, 1.)   ## TRUE in R (both are stored as doubles)
identical(1, as.integer(1)) ## FALSE, stored as different types

x <- 1.0; y <- 0.99999999999
## how to test for object equality allowing for numeric fuzz
identical(all.equal(x, y), TRUE)
## If all.equal thinks the objects are different, it returns a
## character string, and this expression evaluates to FALSE

# even for unusual R objects :
identical(.GlobalEnv, environment())
}
\keyword{ programming }
\keyword{ logic }
\keyword{ iteration }
\eof
\name{identify}
\alias{identify}
\alias{identify.default}
\title{Identify Points in a Scatter Plot}
\usage{
identify(x, \dots)

\method{identify}{default}(x, y = NULL, labels = seq(along = x), pos = FALSE,
         n = length(x), plot = TRUE, offset = 0.5, \dots)
}
\arguments{
  \item{x,y}{coordinates of points in a scatter plot.  Alternatively, any
    object which defines coordinates (a plotting structure, time
    series etc.) can be given as \code{x} and \code{y} left undefined.}
  \item{labels}{an optional vector, the same length as \code{x} and
    \code{y}, giving labels for the points.}
  \item{pos}{if \code{pos} is \code{TRUE}, a component is added to the
    return value which indicates where text was plotted relative to each
    identified point (1=below, 2=left, 3=above and 4=right).}
  \item{n}{the maximum number of points to be identified.}
  \item{plot}{if \code{plot} is \code{TRUE}, the labels are printed at
    the points and if \code{FALSE} they are omitted.}
  \item{offset}{the distance (in character widths) which separates the
    label from identified points.}
  \item{\dots}{further arguments to \code{par(.)}.}
}
\description{
  \code{identify} reads the position of the graphics pointer when the
  (first) mouse button is pressed.  It then searches the coordinates
  given in \code{x} and \code{y} for the point closest to the pointer.
  If this point is close to the pointer, its index will be returned as
  part of the value of the call.
}
\details{
  If in addition, \code{plot} is \code{TRUE}, the point is labelled with
  the corresponding element of \code{text}.

  The labels are placed either below, to the left, above or to the right
  of the identified point, depending on where the cursor was.

#ifdef unix
  The identification process is terminated by pressing any mouse button
  other than the first.
#endif
#ifdef windows
  The identification process is terminated by clicking the second button
  and selecting \sQuote{Stop} from the menu, or from the \sQuote{Stop}
  menu on the graphics window.
#endif
 
  On most devices which support \code{locator}, successful selection of
  a point is indicated by a bell sound unless
  \code{\link{options}(locatorBell=FALSE}} has been set.

  If the window is resized or hidden and then exposed before the identification
  process has terminated, any labels drawn by \code{identify}
  will disappear.  These will reappear once the identification process has 
  terminated and the window is resized or hidden and exposed again.
  This is because the labels drawn by \code{identify} are not
  recorded in the device's display list until the identification process has
  terminated.
}
\value{
  If \code{pos} is \code{FALSE}, an integer
  vector containing the indexes of the identified points.

  If \code{pos} is \code{TRUE}, a list containing a component
  \code{ind}, indicating which points were identified and a component
  \code{pos}, indicating where the labels were placed relative to the
  identified points.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{locator}}
}
\keyword{iplot}
\eof
\name{ifelse}
\title{Conditional Element Selection}
\usage{
ifelse(test, yes, no)
}
\alias{ifelse}
\description{
\code{ifelse} returns a value with the same shape as
\code{test} which is filled with elements selected
from either \code{yes} or \code{no}
depending on whether the element of \code{test}
is \code{TRUE} or \code{FALSE}.
If \code{yes} or \code{no} are too short, their elements are recycled.
}
\arguments{
  \item{test}{a logical vector}
  \item{yes}{return values for true elements of \code{test}.}
  \item{no}{return values for false elements of \code{test}.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
\code{\link{if}}.
}
\examples{
x <- c(6:-4)
sqrt(x)#- gives warning
sqrt(ifelse(x >= 0, x, NA))# no warning

## Note: the following also gives the warning !
ifelse(x >= 0, sqrt(x), NA)
}
\keyword{logic}
\keyword{programming}
\eof
\name{image}
\alias{image}
\alias{image.default}
\title{Display a Color Image}
\usage{
image(x, \dots)

\method{image}{default}(x, y, z, zlim, xlim, ylim, col = heat.colors(12),
      add = FALSE, xaxs = "i", yaxs = "i", xlab, ylab,
      breaks, oldstyle = FALSE, \dots)
}
\arguments{
  \item{x,y}{locations of grid lines at which the values in \code{z} are
    measured.  These must be in (strictly) ascending order.
    By default, equally
    spaced values from 0 to 1 are used.  If \code{x} is a \code{list},
    its components \code{x$x} and \code{x$y} are used for \code{x}
    and \code{y}, respectively. If the list has component \code{z} this
    is used for \code{z}.}
  \item{z}{a matrix containing the values to be plotted (\code{NA}s are
    allowed).  Note that \code{x} can be used instead of \code{z} for
    convenience.}
  \item{zlim}{the minimum and maximum \code{z} values for which colors
    should be plotted.  Each of the given colors will be used to color an
    equispaced interval of this range. The \emph{midpoints} of the
    intervals cover the range, so that values just outside the range
    will be plotted.}
  \item{xlim, ylim}{ranges for the plotted \code{x} and \code{y} values,
    defaulting to the range of the finite values of \code{x} and \code{y}.}
  \item{col}{a list of colors such as that generated by
    \code{\link{rainbow}}, \code{\link{heat.colors}},
    \code{\link{topo.colors}}, \code{\link{terrain.colors}} or similar
    functions.}
  \item{add}{logical; if \code{TRUE}, add to current plot (and disregard
    the following arguments).  This is rarely useful because
    \code{image} \dQuote{paints} over existing graphics.}
  \item{xaxs, yaxs}{style of x and y axis.  The default \code{"i"} is
    appropriate for images.  See \code{\link{par}}.}
  \item{xlab, ylab}{each a character string giving the labels for the x and
    y axis.  Default to the \sQuote{call names} of \code{x} or \code{y}, or to
    \code{""} if these where unspecified.}
  \item{breaks}{a set of breakpoints for the colours: must give one more
    breakpoint than colour.}
  \item{oldstyle}{logical. If true the midpoints of the colour intervals
    are equally spaced, and \code{zlim[1]} and \code{zlim[2]} were taken
    to be midpoints. (This was the default prior to \R 1.1.0.)
    The current default is to have colour intervals of equal lengths
    between the limits.}
  \item{\dots}{graphical parameters for \code{\link{plot}} may also be
    passed as arguments to this function.}
}
\description{
  Creates a grid of colored or gray-scale rectangles with colors
  corresponding to the values in \code{z}.  This can be used to display
  three-dimensional or spatial data aka \dQuote{images}.
  This is a generic function.

  The functions \code{\link{heat.colors}}, \code{\link{terrain.colors}}
  and \code{\link{topo.colors}} create heat-spectrum (red to white) and
  topographical color schemes suitable for displaying ordered data, with
  \code{n} giving the number of colors desired.
}
\details{
  The length of \code{x} should be equal to the \code{nrow(x)+1} or
  \code{nrow(x)}. In the first case \code{x} specifies the boundaries
  between the cells: in the second case \code{x} specifies the
  midpoints of the cells. Similar reasoning applies to \code{y}. It
  probably only makes sense to specify the midpoints of an
  equally-spaced grid. If you specify just one row or column and a
  length-one \code{x} or \code{y}, the whole user area in the
  corresponding direction is filled.

  If \code{breaks} is specified then \code{zlim} is unused and the
  algorithm used follows \code{\link{cut}}, so intervals are closed on
  the right and open on the left except for the lowest interval.
}
\note{
  Based on a function by Thomas Lumley
  \email{tlumley@u.washington.edu}.
}
\seealso{
  \code{\link{filled.contour}} or \code{\link[mva]{heatmap}} which can
  look nicer (but are less modular),
  \code{\link{contour}};

  \code{\link{heat.colors}}, \code{\link{topo.colors}},
  \code{\link{terrain.colors}}, \code{\link{rainbow}},
  \code{\link{hsv}}, \code{\link{par}}.
}
\examples{
x <- y <- seq(-4*pi, 4*pi, len=27)
r <- sqrt(outer(x^2, y^2, "+"))
image(z = z <- cos(r^2)*exp(-r/6), col=gray((0:32)/32))
image(z, axes = FALSE, main = "Math can be beautiful ...",
      xlab = expression(cos(r^2) * e^{-r/6}))
contour(z, add = TRUE, drawlabels = FALSE)

data(volcano)
x <- 10*(1:nrow(volcano))
y <- 10*(1:ncol(volcano))
image(x, y, volcano, col = terrain.colors(100), axes = FALSE)
contour(x, y, volcano, levels = seq(90, 200, by=5), add = TRUE, col = "peru")
axis(1, at = seq(100, 800, by = 100))
axis(2, at = seq(100, 600, by = 100))
box()
title(main = "Maunga Whau Volcano", font.main = 4)
}
\keyword{hplot}
\keyword{aplot}
\eof
\name{index.search}
\alias{index.search}
\title{Search Indices for Help Files}
\usage{
index.search(topic, path, file="AnIndex", type = "help")
}
\arguments{
  \item{topic}{The keyword to be searched for in the indices.}
  \item{path}{The path(s) to the packages to be searched.}
  \item{file}{The index file to be searched.  Normally
    \file{"AnIndex"}.}
  \item{type}{The type of file required.}
}
\description{
  Used to search the indices for help files, possibly under aliases.
}
\details{
  For each package in \code{path}, examine the file \code{file} in
  directory \file{type}, and look up the matching file stem for topic
  \code{topic}, if any.  
}
\value{
  A character vector of matching files, as if they are in directory
  \code{type} of the corresponding package. In the special cases of
  \code{type = "html"}, \code{"R-ex"} and \code{"latex"} the file
  extensions \code{".html"}, \code{".R"} and \code{".tex"} are added.
}
\seealso{
  \code{\link{help}},
  \code{\link{example}}
}
\keyword{utilities}
\eof
\name{infert}
\docType{data}
\alias{infert}
\title{Infertility after Spontaneous and Induced Abortion}
\description{
  This is a matched case-control study dating from before the
  availability of conditional logistic regression.
}
\usage{data(infert)}
\format{
  \tabular{rll}{
    1.  \tab Education  \tab 0 = 0-5  years \cr
        \tab            \tab 1 = 6-11 years \cr
        \tab            \tab 2 = 12+  years  \cr
    2.  \tab age        \tab age in years of case \cr
    3.  \tab parity     \tab count \cr
    4.  \tab number of prior \tab 0 = 0 \cr
        \tab induced abortions \tab 1 = 1 \cr
        \tab            \tab 2 = 2 or more \cr
    5.  \tab case status\tab 1 = case \cr
        \tab            \tab 0 = control \cr
    6.  \tab number of prior \tab 0 = 0 \cr
        \tab spontaneous abortions \tab 1 = 1 \cr
        \tab            \tab 2 = 2 or more \cr
    7.  \tab matched set number \tab 1-83 \cr
    8.  \tab stratum number \tab 1-63}
}
\source{
  Trichopoulos et al. (1976)
  \emph{Br. J. of Obst. and Gynaec.} \bold{83}, 645--650.
}
\note{
  One case with two prior spontaneous abortions and two prior induced
  abortions is omitted.
}
\examples{
data(infert)
model1 <- glm(case ~ spontaneous+induced, data=infert,family=binomial())
summary(model1)
## adjusted for other potential confounders:
summary(model2 <- glm(case ~ age+parity+education+spontaneous+induced,
                data=infert,family=binomial()))
## Really should be analysed by conditional logistic regression
## which is in the survival package
if(require(survival)){
  model3 <- clogit(case~spontaneous+induced+strata(stratum),data=infert)
  summary(model3)
  detach()# survival (conflicts)
}
}
\keyword{datasets}
\eof
\name{influence.measures}
\title{Regression Deletion Diagnostics}
\alias{influence.measures}
\alias{print.infl}
\alias{summary.infl}
\alias{hat}
\alias{hatvalues}
\alias{hatvalues.lm}
\alias{rstandard}
\alias{rstandard.lm}
\alias{rstandard.glm}
\alias{rstudent}
\alias{rstudent.lm}
\alias{rstudent.glm}
\alias{dfbeta}
\alias{dfbeta.lm}
\alias{dfbetas}
\alias{dfbetas.lm}
\alias{dffits}
\alias{covratio}
\alias{cooks.distance}
\alias{cooks.distance.lm}
\alias{cooks.distance.glm}
\usage{
influence.measures(model)

rstandard(model, \dots)
\method{rstandard}{lm}(model, infl = lm.influence(model, do.coef=FALSE),
          sd = sqrt(deviance(model)/df.residual(model)), \dots)
\method{rstandard}{glm}(model, infl = lm.influence(model, do.coef=FALSE), \dots)

rstudent(model, \dots)
\method{rstudent}{lm}(model, infl = lm.influence(model, do.coef=FALSE),
	 res = infl$wt.res, \dots)
\method{rstudent}{glm}(model, infl = influence(model, do.coef=FALSE), \dots)

dffits(model, infl = , res = )

dfbeta(model, \dots)
\method{dfbeta}{lm}(model, infl = lm.influence(model, do.coef=TRUE), \dots)

dfbetas(model, \dots)
\method{dfbetas}{lm}(model, infl = lm.influence(model, do.coef=TRUE), \dots)

covratio(model, infl = lm.influence(model, do.coef=FALSE),
         res = weighted.residuals(model))

cooks.distance(model, \dots)
\method{cooks.distance}{lm}(model, infl = lm.influence(model, do.coef=FALSE),
               res = weighted.residuals(model),
               sd = sqrt(deviance(model)/df.residual(model)),
               hat = infl$hat, \dots)
\method{cooks.distance}{glm}(model, infl = influence(model, do.coef=FALSE),
               res = infl$pear.res, dispersion = summary(model)$dispersion,
               hat = infl$hat, \dots)

hatvalues(model, \dots)
\method{hatvalues}{lm}(model, infl = lm.influence(model, do.coef=FALSE), \dots)

hat(x, intercept = TRUE)
}
\arguments{
  \item{model}{an \R object, typically returned by \code{\link{lm}} or
    \code{\link{glm}}.}
  \item{infl}{influence structure as returned by
    \code{\link{lm.influence}} or \code{\link{influence}} (the latter
    only for the \code{glm} method of \code{rstudent} and
    \code{cooks.distance}).}
  \item{res}{(possibly weighted) residuals, with proper default.}
  \item{sd}{standard deviation to use, see default.}
  \item{dispersion}{dispersion (for \code{\link{glm}} objects) to use,
    see default.}
  \item{hat}{hat values \eqn{H_{ii}}{H[i,i]}, see default.}

  \item{x}{the \eqn{X} or design matrix.}
  \item{intercept}{should an intercept column be pre-prended to \code{x}?}
  \item{\dots}{further arguments passed to or from other methods.}
}
\description{
  This suite of functions can be used to compute some of the regression
  (leave-one-out deletion) diagnostics for linear and generalized linear
  models discussed in Belsley, Kuh and Welsch (1980), Cook and Weisberg (1982),
  etc.
}
\details{
  The primary high-level function is \code{influence.measures} which produces a
  class \code{"infl"} object tabular display showing the DFBETAS for
  each model variable, DFFITS, covariance ratios, Cook's distances and
  the diagonal elements of the hat matrix.  Cases which are influential
  with respect to any of these measures are marked with an asterisk.

  The functions \code{dfbetas}, \code{dffits},
  \code{covratio} and \code{cooks.distance} provide direct access to the
  corresponding diagnostic quantities.  Functions \code{rstandard} and
  \code{rstudent} give the standardized and Studentized residuals
  respectively. (These re-normalize the residuals to have unit variance,
  using an overall and leave-one-out measure of the error variance
  respectively.)

  Values for generalized linear models are approximations, as described
  in Williams (1987) (except that Cook's distances are scaled as
  \eqn{F} rather than as chi-square values).

  The optional \code{infl}, \code{res} and \code{sd} arguments are there
  to encourage the use of these direct access functions, in situations
  where, e.g., the underlying basic influence measures (from
  \code{\link{lm.influence}} or the generic \code{\link{influence}}) are
  already available.

  Note that cases with \code{weights == 0} are \emph{dropped} from all
  these functions, but that if a linear model has been fitted with
  \code{na.action = na.exclude}, suitable values are filled in for the
  cases excluded during fitting.

  The function \code{hat()} exists mainly for S (version 2)
  compatibility; we recommend using \code{hatvalues()} instead.
}
\note{
  For \code{hatvalues}, \code{dfbeta}, and \code{dfbetas}, the method
  for linear models also works for generalized linear models.
}
\author{
  Several R core team members and John Fox, originally in his \file{car}
  package.
}
\references{
  Belsley, D. A., Kuh, E. and Welsch, R. E. (1980)
  \emph{Regression Diagnostics}.
  New York: Wiley.

  Cook, R. D. and Weisberg, S. (1982)
  \emph{Residuals and Influence in Regression}.
  London: Chapman and Hall.

  Williams, D. A. (1987)
  Generalized linear model diagnostics using the deviance and single
  case deletions. \emph{Applied Statistics} \bold{36}, 181--191.

  Fox, J. (1997)
  \emph{Applied Regression, Linear Models, and Related Methods}. Sage.

  Fox, J. (2002)
  \emph{An R and S-Plus Companion to Applied Regression}.
  Sage Publ.; \url{http://www.socsci.mcmaster.ca/jfox/Books/Companion/}.
}
\seealso{\code{\link{influence}} (containing \code{\link{lm.influence}}).
}
\examples{
## Analysis of the life-cycle savings data
## given in Belsley, Kuh and Welsch.
data(LifeCycleSavings)
lm.SR <- lm(sr ~ pop15 + pop75 + dpi + ddpi, data = LifeCycleSavings)

inflm.SR <- influence.measures(lm.SR)
which(apply(inflm.SR$is.inf, 1, any)) # which observations 'are' influential
summary(inflm.SR) # only these
inflm.SR          # all
plot(rstudent(lm.SR) ~ hatvalues(lm.SR)) # recommended by some

## The 'infl' argument is not needed, but avoids recomputation:
rs <- rstandard(lm.SR)
iflSR <- influence(lm.SR)
identical(rs, rstandard(lm.SR, infl = iflSR))
## to "see" the larger values:
1000 * round(dfbetas(lm.SR, infl = iflSR), 3)

## Huber's data [Atkinson 1985]
xh <- c(-4:0, 10)
yh <- c(2.48, .73, -.04, -1.44, -1.32, 0)
summary(lmH <- lm(yh ~ xh))
(im <- influence.measures(lmH))
plot(xh,yh, main = "Huber's data: L.S. line and influential obs.")
abline(lmH); points(xh[im$is.inf], yh[im$is.inf], pch=20, col=2)
}
\keyword{regression}
\eof
\name{integer}
\alias{integer}
\alias{as.integer}
\alias{as.integer.default}
\alias{is.integer}
\title{Integer Vectors}
\description{
  Creates or tests for objects of type \code{"integer"}.
}
\usage{
integer(length = 0)
as.integer(x, \dots)
is.integer(x)
}
\arguments{
  \item{length}{desired length.}
  \item{x}{object to be coerced or tested.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\value{
  \code{integer} creates a integer vector of the specified length.
  Each element of the vector is equal to \code{0}.
  Integer vectors exist so that data can be passed to C or Fortran code
  which expects them.

  \code{as.integer} attempts to coerce its argument to be of integer
  type. The answer will be \code{NA} unless the coercion succeeds.
  Real values larger in modulus than the largest integer are coerced to
  \code{NA} (unlike S which gives the most extreme integer of the same sign).
  Non-integral numeric values are truncated towards zero (i.e.,
  \code{as.integer(x)} equals \code{\link{trunc}(x)} there), and
  imaginary parts of complex numbers are discarded (with a warning).
  Like \code{\link{as.vector}} it strips attributes including names.

  \code{is.integer} returns \code{TRUE} or \code{FALSE} depending on
  whether its argument is of integer type or not.
  \code{is.integer} is generic: you can write methods to handle
  of specific classes of objects, see \link{InternalMethods}.
  Note that factors are true for \code{is.integer} but false for
  \code{\link{is.numeric}}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{round}} (and \code{ceiling} and \code{floor} on that help
  page) to convert to integral values.
}
\examples{
  ## as.integer() truncates:
  x <- pi * c(-1:1,10)
  as.integer(x)
}
\keyword{classes}
\eof
\name{integrate}
\alias{integrate}
\alias{print.integrate}
\title{Integration of One-Dimensional Functions}
\description{
  Adaptive quadrature of functions of one variable over a finite or
  infinite interval.
}
\usage{
integrate(f, lower, upper, subdivisions=100,
          rel.tol = .Machine$double.eps^0.25, abs.tol = rel.tol,
          stop.on.error = TRUE, keep.xy = FALSE, aux = NULL, \dots)
}
\arguments{
  \item{f}{an \R function taking a numeric first argument and returning
    a numeric vector of the same length.  Returning a non-finite element will
    generate an error.}
  \item{lower, upper}{the limits of integration.  Can be infinite.}
  \item{subdivisions}{the maximum number of subintervals.}
  \item{rel.tol}{relative accuracy requested.}
  \item{abs.tol}{absolute accuracy requested.}
  \item{stop.on.error}{logical. If true (the default) an error stops the
    function.  If false some errors will give a result with a warning in
    the \code{message} component.}
  \item{keep.xy}{unused.  For compatibility with S.}
  \item{aux}{unused.  For compatibility with S.}
  \item{\dots}{additional arguments to be passed to \code{f}.  Remember
    to use argument names \emph{not} matching those of \code{integrate(.)}!}
}
\details{
  If one or both limits are infinite, the
  infinite range is mapped onto a finite interval.

  For a finite interval, globally adaptive interval subdivision is used
  in connection with extrapolation by the Epsilon algorithm.

  \code{rel.tol} cannot be less than \code{max(50*.Machine$double.eps,
    0.5e-28)} if \code{abs.tol <= 0}.
}
\note{
  Like all numerical integration routines, these evaluate the function
  on a finite set of points.  If the function is approximately constant
  (in particular, zero) over nearly all its range it is possible that
  the result and error estimate may be seriously wrong.

  When integrating over infinite intervals do so explicitly, rather than
  just using a large number as the endpoint.  This increases the chance
  of a correct answer -- any function whose integral over an infinite
  interval is finite must be near zero for most of that interval.
}
\value{
  A list of class \code{"integrate"} with components
  \item{value}{the final estimate of the integral.}
  \item{abs.error}{estimate of the modulus of the absolute error.}
  \item{subdivisions}{the number of subintervals produced in the
    subdivision process.}
  \item{message}{\code{"OK"} or a character string giving the error message.}
  \item{call}{the matched call.}
}
\references{
  Based on QUADPACK routines \code{dqags} and \code{dqagi} by
  R. Piessens and E. deDoncker-Kapenga, available from Netlib.

  See\cr
  R. Piessens, E. deDoncker-Kapenga, C. Uberhuber, D. Kahaner (1983)
  \emph{Quadpack: a Subroutine Package for Automatic Integration};
  Springer Verlag.
}
\seealso{
  The function \code{\link[adapt]{adapt}} in the \pkg{adapt} package on
  CRAN, for multivariate integration.
}
\examples{
integrate(dnorm, -1.96, 1.96)
integrate(dnorm, -Inf, Inf)

## a slowly-convergent integral
integrand <- function(x) {1/((x+1)*sqrt(x))}
integrate(integrand, lower = 0, upper = Inf)

## don't do this if you really want the integral from 0 to Inf
integrate(integrand, lower = 0, upper = 10)
integrate(integrand, lower = 0, upper = 100000)
integrate(integrand, lower = 0, upper = 1000000, stop.on.error = FALSE)

try(integrate(function(x) 2, 0, 1))  ## no vectorizable function
integrate(function(x) rep(2, length(x)), 0, 1)  ## correct

## integrate can fail if misused
integrate(dnorm,0,2)
integrate(dnorm,0,20)
integrate(dnorm,0,200)
integrate(dnorm,0,2000)
integrate(dnorm,0,20000) ## fails on many systems
integrate(dnorm,0,Inf)   ## works
}
\keyword{math}
\keyword{utilities}
\eof
\name{interaction}
\title{Compute Factor Interactions}
\usage{
interaction(\dots, drop = FALSE)
}
\alias{interaction}
\arguments{
  \item{\dots}{The factors for which interaction is to be computed, or a
    single list giving those factors.}
  \item{drop}{If \code{drop} is \code{TRUE}, empty factor levels
    are dropped from the result. The default is to retain all
    factor levels.}
}
\description{
  \code{interaction} computes a factor which represents the interaction
  of the given factors.  The result of \code{interaction} is always unordered.
}
\value{
  A factor which represents the interaction of the given factors.
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S}.
  Wadsworth \& Brooks/Cole.
}
\seealso{\code{\link{factor}}.}%% even more ":" for factors!

\examples{
a <- gl(2, 2, 8)
b <- gl(2, 4, 8)
interaction(a, b)
}
\keyword{category}
\eof
\name{interaction.plot}
\alias{interaction.plot}
\title{Two-way Interaction Plot}
\description{
  Plots the mean (or other summary) of the response for two-way
  combinations of factors, thereby illustrating possible interactions.
}
\usage{
interaction.plot(x.factor, trace.factor, response, fun = mean,
                 type = c("l", "p"), legend = TRUE,
                 trace.label=deparse(substitute(trace.factor)), fixed=FALSE,
                 xlab = deparse(substitute(x.factor)), ylab = ylabel,
                 ylim = range(cells, na.rm=TRUE),
                 lty = nc:1, col = 1, pch = c(1:9, 0, letters),
                 xpd = NULL, leg.bg = par("bg"), leg.bty = "n",
                 xtick = FALSE, xaxt = par("xaxt"), axes = TRUE, \dots)
}
\arguments{
  \item{x.factor}{a factor whose levels will form the x axis.}
  \item{trace.factor}{another factor whose levels will form the traces.}
  \item{response}{a numeric variable giving the response}
  \item{fun}{the function to compute the summary. Should return a single
    real value.}
  \item{type}{the type of plot: lines or points.}
  \item{legend}{logical. Should a legend be included?}
  \item{trace.label}{overall label for the legend.}
  \item{fixed}{logical.  Should the legend be in the order of the levels
    of \code{trace.factor} or in the order of the traces at their right-hand ends?}
  \item{xlab,ylab}{the x and y label of the plot each with a sensible default.}
  \item{ylim}{numeric of length 2 giving the y limits for the plot.}
  \item{lty}{line type for the lines drawn, with sensible default.}
  \item{col}{the color to be used for plotting.}
  \item{pch}{a vector of plotting symbols or characters, with sensible
    default.}
  \item{xpd}{determines clipping behaviour for the \code{\link{legend}}
    used, see \code{\link{par}(xpd)}.  Per default, the legend is
    \emph{not} clipped at the figure border.}
  \item{leg.bg, leg.bty}{arguments passed to \code{\link{legend}()}.}
  \item{xtick}{logical. Should tick marks be used on the x axis?}
  \item{xaxt, axes, \dots}{graphics parameters to be passed to the plotting routines.}
}
\details{
  By default the levels of \code{x.factor} are plotted on the x axis in
  their given order, with extra space left at the right for the legend
  (if specified). If \code{x.factor} is an ordered factor and the levels
  are numeric, these numeric values are used for the x axis.

  The response and hence its summary can contain missing values. If so,
  the missing values and the line segments joining them are omitted from
  the plot (and this can be somewhat disconcerting).

  The graphics parameters \code{xlab}, \code{ylab}, \code{ylim},
  \code{lty}, \code{col} and \code{pch} are given suitable defaults
  (and \code{xlim} and \code{xaxs} are set and cannot be overriden).
  The defaults are to cycle through the line types, use the foreground
  colour, and to use the symbols 1:9, 0, and the capital letters to plot
  the traces.
}
\note{
  Some of the argument names and the precise behaviour are chosen for
  S-compatibility.
}
\references{
  Chambers, J. M., Freeny, A and Heiberger, R. M. (1992)
  \emph{Analysis of variance; designed experiments.}
  Chapter 5 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}

\examples{
data(ToothGrowth)
attach(ToothGrowth)
interaction.plot(dose, supp, len, fixed=TRUE)
dose <- ordered(dose)
interaction.plot(dose, supp, len, fixed=TRUE, col = 2:3, leg.bty = "o")
detach()

data(OrchardSprays)
with(OrchardSprays, {
  interaction.plot(treatment, rowpos, decrease)
  interaction.plot(rowpos, treatment, decrease, cex.axis=0.8)
  ## order the rows by their mean effect
  rowpos <- factor(rowpos, levels=sort.list(tapply(decrease, rowpos, mean)))
  interaction.plot(rowpos, treatment, decrease, col = 2:9, lty = 1)
})

data(esoph)
with(esoph, {
  interaction.plot(agegp, alcgp, ncases/ncontrols)
  interaction.plot(agegp, tobgp, ncases/ncontrols, trace.label="tobacco",
		   fixed=TRUE, xaxt = "n")
})
}
\keyword{hplot}
\eof
\name{interactive}
\alias{interactive}
\title{Is R Running Interactively?}
\description{ 
  Return \code{TRUE} when \R is being used interactively and
  \code{FALSE} otherwise.
}
\usage{
interactive()
}
\seealso{
  \code{\link{source}},
  \code{\link{.First}}
}
\examples{
 .First <- function() if(interactive()) x11()
}
\keyword{environment}
\keyword{programming}
\eof
\name{invisible}
\alias{invisible}
\title{Change the Print Mode to Invisible}
\description{
  Return a (temporarily) invisible copy of an object.
}
\usage{invisible(x)}
\arguments{
  \item{x}{an arbitrary \R object.}
}
\details{
  This function can be useful when it is desired to have functions
  return values which can be assigned, but which do not print when they
  are not assigned.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{return}},
  \code{\link{function}}.
}
\examples{
# These functions both return their argument
f1 <- function(x) x
f2 <- function(x) invisible(x)
f1(1)# prints
f2(1)# does not
}
\keyword{programming}
\eof
\name{iris}
\docType{data}
\alias{iris}
\alias{iris3}
\title{Edgar Anderson's Iris Data}
\description{
  This famous (Fisher's or Anderson's) iris data set gives the
  measurements in centimeters of the variables sepal length and width
  and petal length and width, respectively, for 50 flowers from each
  of 3 species of iris.  The species are \emph{Iris setosa},
  \emph{versicolor}, and \emph{virginica}.
}
\usage{
data(iris)
data(iris3)
}
\format{
  \code{iris} is a data frame with 150 cases (rows) and 5 variables
  (columns) named \code{Sepal.Length}, \code{Sepal.Width},
  \code{Petal.Length}, \code{Petal.Width}, and \code{Species}.

  \code{iris3} gives the same data arranged as a 3-dimensional array
  of size 50 by 4 by 3, as represented by S-PLUS.  The first dimension
  gives the case number within the species subsample, the second the
  measurements with names \code{Sepal L.}, \code{Sepal W.},
  \code{Petal L.}, and \code{Petal W.}, and the third the species.
}
\source{
  Fisher, R. A. (1936)
  The use of multiple measurements in taxonomic problems.
  \emph{Annals of Eugenics},
  \bold{7}, Part II, 179--188.

  The data were collected by
  Anderson, Edgar (1935).
  The irises of the Gaspe Peninsula,
  \emph{Bulletin of the American Iris Society},
  \bold{59}, 2--5.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole. (has \code{iris3} as \code{iris}.)
}
\seealso{\code{\link{matplot}} some examples of which use \code{iris}.}
\examples{
data(iris3)
dni3 <- dimnames(iris3)
ii <- data.frame(matrix(aperm(iris3, c(1,3,2)), ncol=4,
                   dimnames=list(NULL, sub(" L.",".Length",
                                           sub(" W.",".Width", dni3[[2]])))),
                 Species = gl(3,50,lab=sub("S","s",sub("V","v",dni3[[3]]))))
data(iris)
all.equal(ii, iris) # TRUE
}
\keyword{datasets}
\eof
\name{is.empty.model}
\alias{is.empty.model}
\title{Check if a Model is Empty}
\description{
\R model notation allows models with no intercept and no predictors. These require special handling internally.  \code{is.empty.model()} checks whether an object describes an empty model.
}
\usage{
is.empty.model(x)
}
\arguments{
 \item{x}{A \code{terms} object or an object with a \code{terms} method.}
}

\value{
  \code{TRUE} if the model is empty
}

\seealso{ \code{\link{lm}},\code{\link{glm}}}

\examples{
y <- rnorm(20)
is.empty.model(y ~ 0)
is.empty.model(y ~ -1)
is.empty.model(lm(y ~ 0))
}
\keyword{models}
\eof
\name{is.finite}
\title{Finite, Infinite and NaN Numbers}
\usage{
is.finite(x)
is.infinite(x)
Inf
NaN
is.nan(x)
}
\alias{is.finite}
\alias{is.infinite}
\alias{Inf}
\alias{NaN}
\alias{is.nan}
\description{
  \code{is.finite} and \code{is.infinite} return a vector of the same
  length as \code{x}, indicating which elements are finite (not infinite
  and not missing).

  \code{Inf} and \code{-Inf} are positive and negative \dQuote{infinity}
  whereas \code{NaN} means \dQuote{Not a Number}.
}
\arguments{
  \item{x}{(numerical) object to be tested.}
}
\details{
  \code{is.finite} returns a vector of the same length as \code{x}
  the jth element of which is \code{TRUE} if \code{x[j]} is
  finite (i.e., it is not one of the values \code{NA}, \code{NaN},
  \code{Inf} or \code{-Inf}).  All elements of character and
  generic (list) vectors are false, so \code{is.finite} is only useful for
  logical, integer, numeric and complex vectors.  Complex numbers are
  finite if both the real and imaginary parts are.

  \code{is.infinite} returns a vector of the same length as \code{x}
  the jth element of which is \code{TRUE} if \code{x[j]} is
  infinite (i.e., equal to one of \code{Inf} or \code{-Inf}).

  \code{is.nan} tests if a numeric value is \code{NaN}.  Do not test
  equality to \code{NaN}, or even use \code{\link{identical}},
  since systems typically have many different NaN values.
  In most ports of \R one of these is used for the numeric missing
  value \code{NA}.  It is generic: you can write methods to handle
  of specific classes of objects, see \link{InternalMethods}.
}
\note{
  In \R, basically all mathematical functions (including basic
  \code{\link{Arithmetic}}), are supposed to work properly with
  \code{+/- Inf} and \code{NaN} as input or output.

  The basic rule should be that calls and relations with \code{Inf}s
  really are statements with a proper mathematical \emph{limit}.
}
\seealso{
  \code{\link{NA}}, \sQuote{\emph{Not Available}} which is not a number
  as well, however usually used for missing values and applies to many
  modes, not just numeric.
}
\references{
%%- better ones ?!??
    ANSI/IEEE 754 Floating-Point Standard.

    Currently (6/2002), Bill Metzenthen's \email{billm@suburbia.net} tutorial
    and examples at \cr \url{http://www.suburbia.net/~billm/}
}
\examples{
pi / 0 ## = Inf a non-zero number divided by zero creates infinity
0 / 0  ## =  NaN

1/0 + 1/0# Inf
1/0 - 1/0# NaN

stopifnot(
    1/0 == Inf,
    1/Inf == 0
)
sin(Inf)
cos(Inf)
tan(Inf)
}
\keyword{programming}
\keyword{math}
\eof
\name{is.function}
\alias{is.function}
\title{Is an Object of Type Function?}
\usage{is.function(x)}
\description{Checks whether its argument is a function.}
\arguments{
  \item{x}{an \R object.}
}
\details{
  \code{is.function} is generic: you can write methods to handle
  of specific classes of objects, see \link{InternalMethods}.
}
\value{\code{TRUE} if \code{x} is a function, and \code{FALSE}
  otherwise.}
}
\keyword{programming}
\eof
\name{is.language}
\alias{is.language}
\title{Is an Object a Language Object?}
\usage{
is.language(x)
}
\description{
  \code{is.language} returns \code{TRUE} if \code{x} is either a
  variable \code{\link{name}}, a \code{\link{call}}, or an
  \code{\link{expression}}.
}
\arguments{
  \item{x}{object to be tested.}
}
\details{
  \code{is.language} is generic: you can write methods to handle
  of specific classes of objects, see \link{InternalMethods}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
ll <- list(a = expression(x^2 - 2*x + 1), b = as.name("Jim"),
           c = as.expression(exp(1)), d = call("sin", pi))
sapply(ll, typeof)
sapply(ll, mode)
stopifnot(sapply(ll, is.language))
}
\keyword{programming}
\eof
\name{is.object}
\alias{is.object}
\title{Is an Object ``internally classed''?}
\usage{
is.object(x)
}
\description{
    A function rather for internal use.  It returns \code{TRUE} if the
    object \code{x} has the \R internal \code{OBJECT} attribute set, and
    \code{FALSE} otherwise.
}
\arguments{
  \item{x}{object to be tested.}
}
\details{
  \code{is.object} is generic: you can write methods to handle
  of specific classes of objects, see \link{InternalMethods}.
}
\seealso{\code{\link[base]{class}}, and \code{\link{methods}}.}

\examples{
is.object(1) # FALSE
is.object(as.factor(1:3)) # TRUE
}
\keyword{methods}
\keyword{classes}
\eof
\name{is.recursive}
\alias{is.atomic}
\alias{is.recursive}
\title{Is an Object Atomic or Recursive?}
\usage{
is.atomic(x)
is.recursive(x)
}
\description{
  \code{is.atomic} returns \code{TRUE} if \code{x} does not have a list
  structure and \code{FALSE} otherwise.

  \code{is.recursive} returns \code{TRUE} if \code{x} has a recursive
  (list-like) structure and \code{FALSE} otherwise.
}
\arguments{
  \item{x}{object to be tested.}
}
\details{
  These are generic: you can write methods to handle of specific classes
  of objects, see \link{InternalMethods}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{is.list}},
  \code{\link{is.language}}, etc,
  and the \code{demo("is.things")}.
}
\examples{
is.a.r <- function(x) c(is.atomic(x), is.recursive(x))

is.a.r(c(a=1,b=3))      # TRUE FALSE
is.a.r(list())          # FALSE TRUE ??
is.a.r(list(2))         # FALSE TRUE
is.a.r(lm)              # FALSE TRUE
is.a.r(y ~ x)           # FALSE TRUE
is.a.r(expression(x+1)) # FALSE TRUE (not in 0.62.3!)
}
\keyword{programming}
\keyword{classes}
\eof
\name{is.single}
\title{Is an Object of Single Precision Type?}
\usage{is.single(x)}
\alias{is.single}
\description{
\code{is.single} reports an error. There are no single precision
values in R.
}
\arguments{
  \item{x}{object to be tested.}
}
\details{
  \code{is.single} is generic: you can write methods to handle
  of specific classes of objects, see \link{InternalMethods}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\keyword{classes}
\eof
\name{is.R}
\title{Are we using R, rather than S?}
\usage{
is.R()
}
\alias{is.R}
\description{
  Test if running under \R.
}

\details{
  The function has been written such as to correctly run in all versions
  of \R, S and S-PLUS.
  In order for code to be runnable in both \R and S dialects, either
  your the code must define \code{is.R} or use it as

  \code{if (exists("is.R") && is.function(is.R) && is.R()) \{}\cr
  \code{    }\emph{\#\# R-specific code}\cr
  \code{\} else \{}\cr
  \code{    }\emph{\#\# S-version of code}\cr
  \code{\}}
}
\value{
  \code{is.R} returns \code{TRUE} if we are using \R and \code{FALSE}
  otherwise.
}
\seealso{\code{\link{R.version}}, \code{\link{system}}.}
\examples{
x <- runif(20); small <- x < 0.4
## 'which()' only exists in R:
if(is.R()) which(small) else seq(along=small)[small]
}
\keyword{environment}
\keyword{utilities}
\eof
\name{islands}
\docType{data}
\alias{islands}
\title{Areas of the World's Major Landmasses}
\description{
  The areas in thousands of square miles of the landmasses which exceed
  10,000 square miles.
}
\usage{data(islands)}
\format{A named vector of length 48.}
\source{The World Almanac and Book of Facts, 1975, page 406.}
\references{
  McNeil, D. R. (1977)
  \emph{Interactive Data Analysis}.
  Wiley.
}
\examples{
data(islands)
dotchart(log(islands, 10),
   main = "islands data: log10(area) (log10(sq. miles))")
dotchart(log(islands[order(islands)], 10),
   main = "islands data: log10(area) (log10(sq. miles))")
}
\keyword{datasets}
\eof
\name{jitter}
\alias{jitter}
\title{Add `Jitter' (Noise) to Numbers}
\usage{
jitter(x, factor=1, amount = NULL)
}
\arguments{
  \item{x}{numeric to which \emph{jitter} should be added.}
  \item{factor}{numeric }
  \item{amount}{numeric; if positive, used as \emph{amount} (see below),
    otherwise, if \code{= 0} the default is \code{factor * z/50}.

    Default (\code{NULL}): \code{factor * d/5} where \code{d} is about
    the smallest difference between \code{x} values.}
}
\description{
  Add a small amount of noise to a numeric vector.
}
\value{
  \code{jitter(x,\dots)} returns a numeric of the same length as
  \code{x}, but with an \code{amount} of noise added in order to break
  ties. 
}
\details{
  The result, say \code{r}, is \code{r <- x + runif(n, -a, a)}
  where \code{n <- length(x)} and \code{a} is the \code{amount}
  argument (if specified).

  Let \code{z <- max(x) - min(x)} (assuming the usual case).
  The amount \code{a} to be added is either provided as \emph{positive}
  argument \code{amount} or otherwise computed from \code{z}, as
  follows:

  If \code{amount == 0}, we set \code{a <- factor * z/50} (same as S).

  If \code{amount} is \code{NULL} (\emph{default}), we set
  \code{a <- factor * d/5} where \emph{d} is the smallest
  difference between adjacent unique (apart from fuzz) \code{x} values.
}
\references{
  Chambers, J. M., Cleveland, W. S., Kleiner, B. and Tukey, P.A. (1983)
  \emph{Graphical Methods for Data Analysis.} Wadsworth; figures 2.8,
  4.22, 5.4.

  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S.}
  Wadsworth \& Brooks/Cole.
}
\author{Werner Stahel and Martin Maechler, ETH Zurich}
\seealso{\code{\link{rug}} which you may want to combine with \code{jitter}.}
\examples{
round(jitter(c(rep(1,3),  rep(1.2, 4), rep(3,3))), 3)
## These two 'fail' with S-plus 3.x:
jitter(rep(0, 7))
jitter(rep(10000,5))
}
\keyword{dplot}
\keyword{utilities}
\eof
\name{kappa}
\title{Estimate the Condition Number}
\usage{
kappa(z, \dots)
\method{kappa}{lm}(z, \dots)
\method{kappa}{default}(z, exact = FALSE, \dots)
\method{kappa}{qr}(z, \dots) 

kappa.tri(z, exact = FALSE, \dots)
}
\alias{kappa}
\alias{kappa.default}
\alias{kappa.lm}
\alias{kappa.qr}
\alias{kappa.tri}
\arguments{
  \item{z}{A matrix or a the result of \code{\link{qr}} or a fit from a class
    inheriting from \code{"lm"}.}
  \item{exact}{logical. Should the result be exact?}
  \item{\dots}{further arguments passed to or from other methods.}
}
\description{
 An estimate of the condition number of a matrix or of the \eqn{R} matrix of a
 \eqn{QR} decomposition, perhaps of a linear fit.  The condition number is
 defined as the ratio of the largest to the smallest \emph{non-zero}
 singular value of the matrix.
}
\details{
 If \code{exact = FALSE} (the default) the condition number is estimated
 by a cheap approximation. Following S, this uses the LINPACK routine
 \file{dtrco.f}.  However, in \R (or S) the exact calculation is also
 likely to be quick enough.

 \code{kappa.tri} is an internal function called by \code{kappa.qr}.
}
\value{
  The condition number, \eqn{kappa}, or an approximation if
  \code{exact = FALSE}.  
}
\references{
  Chambers, J. M. (1992)
  \emph{Linear models.}
  Chapter 4 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\author{
  The design was inspired by (but differs considerably from)
  the S function of the same name described in Chambers (1992).
}
  
\seealso{
  \code{\link{svd}} for the singular value decomposition and
  \code{\link{qr}} for the \eqn{QR} one.
}
\examples{
kappa(x1 <- cbind(1,1:10))# 15.71
kappa(x1, exact = TRUE)        # 13.68
kappa(x2 <- cbind(x1,2:11))# high! [x2 is singular!]

hilbert <- function(n) { i <- 1:n; 1 / outer(i - 1, i, "+") }
sv9 <- svd(h9 <- hilbert(9))$ d
kappa(h9)# pretty high!
kappa(h9, exact = TRUE) == max(sv9) / min(sv9)
kappa(h9, exact = TRUE) / kappa(h9) # .677 (i.e., rel.error = 32\%)
}
\keyword{math}
\eof
\name{kronecker}

\title{Kronecker products on arrays}

\usage{
kronecker(X, Y, FUN = "*", make.dimnames = FALSE, \dots)
X \%x\% Y
}

\alias{kronecker}
\alias{\%x\%}

\arguments{
 \item{X}{A vector or array.}
 \item{Y}{A vector or array.}
 \item{FUN}{a function; it may be a quoted string.}
 \item{make.dimnames}{Provide dimnames that are the product of the
dimnames of \code{X} and \code{Y}.}
 \item{\dots}{optional arguments to be passed to \code{FUN}.}
}

\description{
Computes the generalised kronecker product of two arrays,
\code{X} and \code{Y}.  \code{kronecker(X, Y)} returns an array
\code{A} with dimensions \code{dim(X) * dim(Y)}.}

\details{If \code{X} and \code{Y} do not have the same number of
dimensions, the smaller array is padded with dimensions of size
one.  The returned array comprises submatrices constructed by
taking \code{X} one term at a time and expanding that term as
\code{FUN(x, Y, ...)}.

\code{\%x\%} is an alias for \code{kronecker} (where
\code{FUN} is hardwired to \code{"*"}).
}

\references{
  Shayle R. Searle (1982)
  \emph{Matrix Algebra Useful for Statistics.} John Wiley and Sons.
}

\author{Jonathan Rougier, \email{J.C.Rougier@durham.ac.uk}}

\seealso{\code{\link{outer}}, on which \code{kronecker} is built
and \code{\link{\%*\%}} for usual matrix multiplication.}

\examples{
# simple scalar multiplication
( M <- matrix(1:6, ncol=2) )
kronecker(4, M)
# Block diagonal matrix:
kronecker(diag(1, 3), M)

# ask for dimnames

fred <- matrix(1:12, 3, 4, dimnames=list(LETTERS[1:3], LETTERS[4:7]))
bill <- c("happy" = 100, "sad" = 1000)
kronecker(fred, bill, make.dimnames = TRUE)

bill <- outer(bill, c("cat"=3, "dog"=4))
kronecker(fred, bill, make.dimnames = TRUE)
}

\keyword{array}
\eof
\name{labels}
\title{Find Labels from Object}
\usage{
labels(object, \dots)
}
\alias{labels}
\alias{labels.default}
\alias{labels.terms}
\alias{labels.lm}
\arguments{
  \item{object}{Any \R object: the function is generic.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\description{
  Find a suitable set of labels from an object for use in printing or
  plotting, for example.  A generic function.
}
\value{
  A character vector or list of such vectors. For a vector the results
  is the names or \code{seq(along=x)}, for a data frame or array it is
  the dimnames (with \code{NULL} expanded to \code{seq(len=d[i])}), for
  a \code{terms} object it is the term labels and for an \code{lm}
  object it is the term labels for estimable terms.
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S.}
  Wadsworth \& Brooks/Cole.
}
\keyword{print}
\keyword{models}
\eof
\name{lapply}
\title{Apply a Function over a List or Vector}
\usage{
lapply(X, FUN, \dots)
sapply(X, FUN, \dots, simplify = TRUE, USE.NAMES = TRUE)

replicate(n, expr, simplify = TRUE) 
}
\alias{lapply}
\alias{sapply}
\alias{replicate}
\arguments{
  \item{X}{list or vector to be used.}
  \item{FUN}{the function to be applied.
    In the case of functions like \code{+},
    \code{\%*\%}, etc., the function name must be quoted.}
  \item{\dots}{optional arguments to \code{FUN}.}
  \item{simplify}{logical; should the result be simplified to a vector
    if possible?}
  \item{USE.NAMES}{logical; if \code{TRUE} and if \code{X} is character,
    use \code{X} as \code{\link{names}} for the result unless it had names
    already.}
  \item{n}{Number of replications.}
  \item{expr}{Expression to evaluate repeatedly.}
}
\description{
  \code{lapply} returns a list of the same length as \code{X}.  Each
  element of which is the result of applying \code{FUN} to the
  corresponding element of \code{X}.

  \code{sapply} is a \dQuote{user-friendly} version of \code{lapply}
  also accepting vectors as \code{X}, and returning a vector or matrix
  with \code{dimnames} if appropriate.

  \code{replicate} is a wrapper for the common use of \code{sapply} for
  repeated evaluation of an expression (which will usually involve
  random number generation.)
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{apply}}, \code{\link{tapply}}.
}
\examples{
x <- list(a = 1:10, beta = exp(-3:3), logic = c(TRUE,FALSE,FALSE,TRUE))
# compute the list mean for each list element
lapply(x,mean)
# median and quartiles for each list element
lapply(x, quantile, probs = 1:3/4)
sapply(x, quantile)
str(i39 <- sapply(3:9, seq))# list of vectors
sapply(i39, fivenum)
hist(replicate(100, mean(rexp(10))))
}
\keyword{iteration}
\keyword{list}
\eof
\name{layout}
\alias{layout}
\alias{layout.show}
\alias{lcm}
\title{Specifying Complex Plot Arrangements}
\author{Paul R. Murrell}
\description{
  \code{layout} divides the device up into as many rows and columns as
  there are in matrix \code{mat}, with the column-widths and the
  row-heights specified in the respective arguments.
}
\usage{
layout(mat,
       widths = rep(1, dim(mat)[2]),
       heights= rep(1, dim(mat)[1]),
       respect= FALSE)

layout.show(n = 1)
lcm(x)
}
\arguments{
  \item{mat}{a matrix object specifying the location of the next
    \eqn{N} figures
    on the output device.  Each value in the matrix must be \code{0} or a
    positive integer.     If \eqn{N} is the largest positive integer in
    the matrix, then the integers \eqn{\{1,\dots,N-1\}} must also appear
    at least once in the matrix.}
  \item{widths}{a vector of values for the widths of columns on the
    device.  Relative widths are specified with numeric values.    Absolute
    widths (in centimetres) are specified with the \code{lcm()} function (see
    examples).}
  \item{heights}{a vector of values for the heights of rows on the device.
    Relative and absolute heights can be specified, see \code{widths} above.}
  \item{respect}{either a logical value or a matrix object.  If the
    latter, then it must have the same dimensions as \code{mat} and
    each value in the matrix must be either \code{0} or \code{1}.}
  \item{n}{number of figures to plot.}
  \item{x}{a dimension to be intepreted as a number of centimetres.}
}
\details{
    Figure \eqn{i} is allocated a region composed from a subset
    of these rows and columns, based on the rows and columns
    in which \eqn{i} occurs in \code{mat}.

    The \code{respect} argument controls whether a unit column-width is
    the same physical measurement on the device as a unit row-height.

    \code{layout.show(n)} plots (part of) the current layout, namely the
    outlines of the next \code{n} figures.

    \code{lcm} is a trivial function, to be used as \emph{the} interface
    for specifying absolute dimensions for the \code{widths} and
    \code{heights} arguments of \code{layout()}.
}
\value{
  \code{layout} returns the number of figures, \eqn{N}, see above.
}
\references{
  Murrell, P. R. (1999) Layouts: A mechanism for arranging plots on a page. 
  \emph{Journal of Computational and Graphical Statistics},
  \bold{8}, 121-134. 
  Chapter 5 of Paul Murrell's Ph.D. thesis.
}
\seealso{
  \code{\link{par}} with arguments \code{mfrow}, \code{mfcol}, or
  \code{mfg}.
}
\examples{
def.par <- par(no.readonly = TRUE)# save default, for resetting...

## divide the device into two rows and two columns
## allocate figure 1 all of row 1
## allocate figure 2 the intersection of column 2 and row 2
layout(matrix(c(1,1,0,2), 2, 2, byrow = TRUE))
## show the regions that have been allocated to each plot
layout.show(2)

## divide device into two rows and two columns
## allocate figure 1 and figure 2 as above
## respect relations between widths and heights
nf <- layout(matrix(c(1,1,0,2), 2, 2, byrow=TRUE), respect=TRUE)
layout.show(nf)

## create single figure which is 5cm square
nf <- layout(matrix(1), widths=lcm(5), heights=lcm(5))
layout.show(nf)


##-- Create a scatterplot with marginal histograms -----

x <- pmin(3, pmax(-3, rnorm(50)))
y <- pmin(3, pmax(-3, rnorm(50)))
xhist <- hist(x, breaks=seq(-3,3,0.5), plot=FALSE)
yhist <- hist(y, breaks=seq(-3,3,0.5), plot=FALSE)
top <- max(c(xhist$counts, yhist$counts))
xrange <- c(-3,3)
yrange <- c(-3,3)
nf <- layout(matrix(c(2,0,1,3),2,2,byrow=TRUE), c(3,1), c(1,3), TRUE)
layout.show(nf)

par(mar=c(3,3,1,1))
plot(x, y, xlim=xrange, ylim=yrange, xlab="", ylab="")
par(mar=c(0,3,1,1))
barplot(xhist$counts, axes=FALSE, ylim=c(0, top), space=0)
par(mar=c(3,0,1,1))
barplot(yhist$counts, axes=FALSE, xlim=c(0, top), space=0, horiz=TRUE)

par(def.par)#- reset to default
}
\keyword{iplot}
\keyword{dplot}
\keyword{environment}
\eof
\name{legend}
\alias{legend}
\title{Add Legends to Plots}
\usage{
legend(x, y = NULL, legend, fill = NULL, col = "black", lty, lwd, pch,
       angle = NULL, density = NULL, bty = "o", bg = par("bg"),
       pt.bg = NA, cex = 1, xjust = 0, yjust = 1,
       x.intersp = 1, y.intersp = 1, adj = c(0, 0.5),
       text.width = NULL, merge = do.lines && has.pch, trace = FALSE,
       plot = TRUE, ncol = 1, horiz = FALSE)
}
\description{
  This function can be used to add legends to plots.  Note that a call
  to the function \code{\link{locator}} can be used in place of the \code{x}
  and \code{y} arguments.
}
\arguments{
  \item{x, y}{the x and y co-ordinates to be used to position the legend.
    They can be specified in any way which is accepted by
    \code{\link{xy.coords}}: See Details.}
  \item{legend}{a vector of text values or an \code{\link{expression}}
    of length \eqn{\ge 1}{>= 1}, or a \code{\link{call}} (as resulting
    from \code{\link{substitute}}) to appear in the legend.}
  \item{fill}{if specified, this argument will cause boxes filled
    with the specified colors (or shaded in the specified colors)
    to appear beside the legend text.}
  \item{col}{the color of points or lines appearing in the legend.}
  \item{lty,lwd}{the line types and widths for lines appearing in the
    legend.  One of these two \emph{must} be specified for line drawing.}
  \item{pch}{the plotting symbols appearing in the legend, either as
    vector of 1-character strings, or one (multi character)
    string. \emph{Must} be specified for symbol drawing.}
  \item{angle}{angle of shading lines.}
  \item{density}{the density of shading lines, if numeric and
    positive. If \code{NULL} or negative or \code{NA} color filling
    is assumed.}
  \item{bty}{the type of box to be drawn around the legend.  The allowed
    values are \code{"o"} (the default) and \code{"n"}.}
  \item{bg}{the background color for the legend box.  (Note that this is
    only used if \code{bty = "n"}.)}
  \item{pt.bg}{the background color for the \code{\link{points}}.}
  \item{cex}{character expansion factor \bold{relative} to current
    \code{par("cex")}.}
  \item{xjust}{how the legend is to be justified relative to the legend
    x location.  A value of 0 means left justified, 0.5 means centered
    and 1 means right justified.}
  \item{yjust}{the same as \code{xjust} for the legend y location.}
  \item{x.intersp}{character interspacing factor for horizontal (x) spacing.}
  \item{y.intersp}{the same for vertical (y) line distances.}
  \item{adj}{numeric of length 1 or 2; the string adjustment for legend
      text.  Useful for y-adjustment when \code{labels} are
      \link{plotmath} expressions.}
  \item{text.width}{the width of the legend text in x (\code{"user"})
    coordinates.
    Defaults to the proper value computed by \code{\link{strwidth}(legend)}.}
  \item{merge}{logical; if \code{TRUE}, \dQuote{merge} points and lines but
    not filled boxes.  Defaults to \code{TRUE} if there are points and lines.}
  \item{trace}{logical; if \code{TRUE}, shows how \code{legend} does all
    its magical computations.}
  \item{plot}{logical.  If \code{FALSE}, nothing is plotted but the
    sizes are returned.}
  \item{ncol}{the number of columns in which to set the legend items
    (default is 1, a vertical legend).}
  \item{horiz}{logical; if \code{TRUE}, set the legend horizontally rather than
     vertically (specifying \code{horiz} overrides the \code{ncol}
     specification).}
}
\details{
  Arguments \code{x, y, legend} are interpreted in a non-standard way to
  allow the coordinates to be specified \emph{via} one or two arguments.
  If \code{legend} is missing and \code{y} is not numeric, it is assumed
  that the second argument is intended to be \code{legend} and that the
  first argument specifies the coordinates.

  The coordinates can be specified in any way which is accepted by
  \code{\link{xy.coords}}.  If this gives the coordinates of one point,
  it is used as the top-left coordinate of the rectangle containing the
  legend.  If it gives the coordinates of two points, these specify
  opposite corners of the rectangle (either pair of corners, in any
  order).

  \dQuote{Attribute} arguments such as \code{col}, \code{pch}, \code{lty},
  etc, are recycled if necessary.  \code{merge} is not.

  Points are drawn \emph{after} lines in order that they can cover the
  line with their background color \code{pt.bg}, if applicable.

  See the examples for how to right-justify labels.
}
\value{
  A list with list components
  \item{rect}{a list with components
    \describe{
      \item{\code{w, h}}{positive numbers giving \bold{w}idth and
	\bold{h}eight of the legend's box.}
      \item{\code{left, top}}{x and y coordinates of upper left corner
	of the box.}
    }
  }
  \item{text}{a list with components
    \describe{
      \item{\code{x, y}}{numeric vectors of length \code{length(legend)},
	giving the x and y coordinates of the legend's text(s).}
    }
  }
  returned invisibly.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{plot}}, \code{\link{barplot}} which uses \code{legend()}, and
  \code{\link{text}} for more examples of math expressions.
}
\examples{
## Run the example in '?matplot' or the following:
leg.txt <- c("Setosa     Petals", "Setosa     Sepals",
             "Versicolor Petals", "Versicolor Sepals")
y.leg <- c(4.5, 3, 2.1, 1.4, .7)
cexv  <- c(1.2, 1, 4/5, 2/3, 1/2)
matplot(c(1,8), c(0,4.5), type = "n", xlab = "Length", ylab = "Width",
        main = "Petal and Sepal Dimensions in Iris Blossoms")
for (i in seq(cexv)) {
  text  (1, y.leg[i]-.1, paste("cex=",formatC(cexv[i])), cex=.8, adj = 0)
  legend(3, y.leg[i], leg.txt, pch = "sSvV", col = c(1, 3), cex = cexv[i])
}

## 'merge = TRUE' for merging lines & points:
x <- seq(-pi, pi, len = 65)
plot(x, sin(x), type = "l", ylim = c(-1.2, 1.8), col = 3, lty = 2)
points(x, cos(x), pch = 3, col = 4)
lines(x, tan(x), type = "b", lty = 1, pch = 4, col = 6)
title("legend(..., lty = c(2, -1, 1), pch = c(-1,3,4), merge = TRUE)",
      cex.main = 1.1)
legend(-1, 1.9, c("sin", "cos", "tan"), col = c(3,4,6),
       lty = c(2, -1, 1), pch = c(-1, 3, 4), merge = TRUE, bg='gray90')

## right-justifying a set of labels: thanks to Uwe Ligges
x <- 1:5; y1 <- 1/x; y2 <- 2/x
plot(rep(x, 2), c(y1, y2), type="n", xlab="x", ylab="y")
lines(x, y1); lines(x, y2, lty=2)
temp <- legend(5, 2, legend = c(" ", " "),
               text.width = strwidth("1,000,000"),
               lty = 1:2, xjust = 1, yjust = 1)
text(temp$rect$left + temp$rect$w, temp$text$y,
     c("1,000", "1,000,000"), pos=2)


##--- log scaled Examples ------------------------------
leg.txt <- c("a one", "a two")

par(mfrow = c(2,2))
for(ll in c("","x","y","xy")) {
  plot(2:10, log=ll, main=paste("log = '",ll,"'", sep=""))
  abline(1,1)
  lines(2:3,3:4, col=2) #
  points(2,2, col=3)    #
  rect(2,3,3,2, col=4)
  text(c(3,3),2:3, c("rect(2,3,3,2, col=4)",
                     "text(c(3,3),2:3,\"c(rect(...)\")"), adj = c(0,.3))
  legend(list(x=2,y=8), legend = leg.txt, col=2:3, pch=1:2,
         lty=1, merge=TRUE)#, trace=TRUE)
}
par(mfrow=c(1,1))

##-- Math expressions:  ------------------------------
x <- seq(-pi, pi, len = 65)
plot(x, sin(x), type="l", col = 2,xlab=expression(phi),ylab=expression(f(phi)))
abline(h=-1:1, v=pi/2*(-6:6), col="gray90")
lines(x, cos(x), col = 3, lty = 2)
ex.cs1 <- expression(plain(sin) * phi,  paste("cos", phi))# 2 ways
str(legend(-3, .9, ex.cs1, lty=1:2, plot=FALSE, adj = c(0, .6)))# adj y !
    legend(-3, .9, ex.cs1, lty=1:2, col=2:3,    adj = c(0, .6))

x <- rexp(100, rate = .5)
hist(x, main = "Mean and Median of a Skewed Distribution")
abline(v = mean(x),   col=2, lty=2, lwd=2)
abline(v = median(x), col=3, lty=3, lwd=2)
ex12 <- expression(bar(x) == sum(over(x[i], n), i==1, n),
                   hat(x) == median(x[i], i==1,n))
str(legend(4.1, 30, ex12, col = 2:3, lty=2:3, lwd=2))

## 'Filled' boxes -- for more, see example(plotfactor)
op <- par(bg="white") # to get an opaque box for the legend
data(PlantGrowth)
plot(cut(weight, 3) ~ group, data = PlantGrowth,
     col = NULL, density = 16*(1:3))
par(op)

## Using 'ncol' :
x <- 0:64/64
matplot(x, outer(x, 1:7, function(x, k) sin(k * pi * x)),
        type = "o", col = 1:7, ylim = c(-1, 1.5), pch = "*")
op <- par(bg="antiquewhite1")
legend(0, 1.5, paste("sin(",1:7,"pi * x)"), col=1:7, lty=1:7, pch = "*",
       ncol = 4, cex=.8)
legend(.8,1.2, paste("sin(",1:7,"pi * x)"), col=1:7, lty=1:7, pch = "*",cex=.8)
legend(0, -.1, paste("sin(",1:4,"pi * x)"), col=1:4, lty=1:4, ncol=2, cex=.8)
legend(0, -.4, paste("sin(",5:7,"pi * x)"), col=5:7,  pch=24, ncol=2, cex=1.5,
       pt.bg="pink")
par(op)

## point covering line :
y <- sin(3*pi*x)
plot(x, y, type="l", col="blue", main = "points with bg & legend(*, pt.bg)")
points(x, y, pch=21, bg="white")
legend(.4,1, "sin(c x)", pch=21, pt.bg="white", lty=1, col = "blue")
}
\keyword{aplot}
\eof
\name{length}
\alias{length}
\alias{length<-}
\title{Length of a Vector or List}
\description{
  Get or set the length of vectors (including lists).
}
\usage{
length(x)
length(x) <- value
}
\arguments{
  \item{x}{a vector or list.}
  \item{value}{an integer.}
}
\value{
  The length of \code{x} as an \code{\link{integer}} of length 1,
  if \code{x} is (or can be coerced to) a vector or list.  Otherwise,
  \code{length} returns \code{NA}.
}
\details{
  \code{length} is generic: you can write methods to handle of specific
  classes of objects, see \link{InternalMethods}.

  The replacement form can be used to reset the length of a vector.  If
  a vector is shortened, extra values are discarded and when a vector is
  lengthened, it is padded out to its new length with \code{\link{NA}}s.
}
\seealso{\code{nchar} for counting the number of characters in
  character vectors.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
length(diag(4))# = 16 (4 x 4)
length(options())# 12 or more
length(y ~ x1 + x2 + x3)# 3
length(expression(x, {y <- x^2; y+2}, x^y)) # 3
}
\keyword{attribute}

\eof
\name{levels}
\alias{levels}
\alias{levels<-}
\alias{levels<-.default}
\alias{levels<-.factor}
\title{Levels Attributes}
\usage{
levels(x)
levels(x) <- value
}
\description{
  \code{levels} provides access to the levels attribute of a variable.
  The first form returns the value of the levels of its argument
  and the second sets the attribute.

  The assignment form (\code{"levels<-"}) of \code{levels} is a generic
  function and new methods can be written for it.
  The most important method is that for \code{\link{factor}}s:
}
\arguments{
  \item{x}{an object, for example a factor.}
  \item{value}{A valid value for \code{levels(x)}.
    For the default method, \code{NULL} or a character vector.  For the
    \code{factor} method, a vector of character strings with length at
    least the number of levels of \code{x}, or a named list specifying how to
    rename the levels.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{nlevels}}.
}
\examples{
## assign individual levels
x <- gl(2, 4, 8)
levels(x)[1] <- "low"
levels(x)[2] <- "high"
x

## or as a group
y <- gl(2, 4, 8)
levels(y) <- c("low", "high")
y

## combine some levels
z <- gl(3, 2, 12)
levels(z) <- c("A", "B", "A")
z

## same, using a named list
z <- gl(3, 2, 12)
levels(z) <- list(A=c(1,3), B=2)
z

## we can add levels this way:
f <- factor(c("a","b"))
levels(f) <- c("c", "a", "b")
f

f <- factor(c("a","b"))
levels(f) <- list(C="C", A="a", B="b")
f
}
\keyword{category}
\eof
\name{library}
\title{Loading and Listing of Packages}
\alias{library}
\alias{require}
\alias{R_LIBS}
\alias{.Autoloaded}
\alias{.First.lib}
\alias{.Last.lib}
\alias{.Library}
\alias{.find.package}
\alias{.packages}
\alias{.path.package}
\alias{.libPaths}
\alias{.noGenerics}
\alias{print.libraryIQR}
\alias{print.packageInfo}
\description{
  \code{library} and \code{require} load add-on packages.

  \code{.First.lib} is called when a package is loaded;
  \code{.Last.lib} is called when a package is detached.

  \code{.packages} returns information about package availability.

  \code{.path.package} returns information about where a package was
  loaded from.

  \code{.find.package} returns the directory paths of installed
  packages.
}
\usage{
library(package, help, pos = 2, lib.loc = NULL, character.only = FALSE,
        logical.return = FALSE, warn.conflicts = TRUE,
        keep.source = getOption("keep.source.pkgs"),
        verbose = getOption("verbose"), version)
require(package, quietly = FALSE, warn.conflicts = TRUE,
        keep.source = getOption("keep.source.pkgs"),
        character.only = FALSE, version, save = TRUE)

.First.lib(libname, pkgname)
.Last.lib(libpath)

.packages(all.available = FALSE, lib.loc = NULL)
.path.package(package = .packages(), quiet = FALSE)
.find.package(package, lib.loc = NULL, quiet = FALSE,
              verbose = getOption("verbose"))
.libPaths(new)

.Library
.Autoloaded
}
\arguments{
  \item{package, help}{the name of a package, given as a \link{name} or
    literal character string, or a character string, depending on
    whether \code{character.only} is \code{FALSE} (default) or
    \code{TRUE}).}
  \item{pos}{the position on the search list at which to attach the
    loaded package.  Note that \code{.First.lib} may attach other
    packages, and \code{pos} is computed \emph{after} \code{.First.lib}
    has been run.  Can also be the name of a position on the current
    search list as given by \code{\link{search}()}.}
  \item{lib.loc}{a character vector describing the location of \R
    library trees to search through, or \code{NULL}.  The default value
    of \code{NULL} corresponds to all libraries currently known.}
  \item{character.only}{a logical indicating whether \code{package} or
    \code{help} can be assumed to be character strings.}
  \item{version}{A character string denoting a version number of the
     package to be loaded.  If no version is given, a suitable default
     is chosen.}
  \item{logical.return}{logical.  If it is \code{TRUE},  \code{FALSE} or
    \code{TRUE} is returned to indicate success.}
  \item{warn.conflicts}{logical.  If \code{TRUE}, warnings are
    printed about \code{\link{conflicts}} from attaching the new
    package, unless that package contains an object \code{.conflicts.OK}.}
  \item{keep.source}{logical.  If \code{TRUE}, functions \dQuote{keep their
    source} including comments, see argument \code{keep.source} to
    \code{\link{options}}.}
  \item{verbose}{a logical.  If \code{TRUE}, additional diagnostics are
    printed.}
  \item{quietly}{a logical.  If \code{TRUE}, no message confirming
    package loading is printed.}
  \item{save}{logical or environment.  IF \code{TRUE}, a call to
  \code{require} from the source for a package will save the name of
  the required package in the variable \code{".required"}, allowing
  function \code{\link{detach}} to warn if a required package is
  detached. See section \sQuote{Packages that require other packages} below.}
  \item{libname}{a character string giving the library directory where
    the package was found.}
  \item{pkgname}{a character string giving the name of the package.}
  \item{libpath}{a character string giving the complete path to the
    package.}
  \item{all.available}{logical; if \code{TRUE} return a character vector
    of all available packages in \code{lib.loc}.}
  \item{quiet}{logical.
    For \code{.path.package}, should this not give warnings or an error
    if the package(s) are not loaded?
    For \code{.find.package}, should this not give warnings or an error
    if the package(s) are not found?}
  \item{new}{a character vector with the locations of \R library trees.}
}
\details{
  \code{library(package)} and \code{require(package)} both load the
  package with name \code{package}.  \code{require} is designed for use
  inside other functions; it returns \code{FALSE} and gives a warning
  (rather than an error as \code{library()} does) if the package does
  not exist.  Both functions check and update the list of currently
  loaded packages and do not reload code that is already loaded.

  For large packages, setting \code{keep.source = FALSE} may save quite
  a bit of memory.

  If \code{library} is called with no \code{package} or \code{help}
  argument, it lists all available packages in the libraries specified
  by \code{lib.loc}, and returns the corresponding information in an
  object of class \code{"libraryIQR"}.  The structure of this class may
  change in future versions.  In earlier versions of R, only the names
  of all available packages were returned; use \code{.packages(all =
    TRUE)} for obtaining these.  Note that
  \code{\link{installed.packages}()} returns even more information.

  \code{library(help = somename)} computes basic information about the
  package \code{somename}, and returns this in an object of class
  \code{"packageInfo"}.  The structure of this class may change in
  future versions.

  \code{.First.lib} is called when a package is loaded by
  \code{library}.  It is called with two arguments, the name of the
  library directory where the package was found (i.e., the corresponding
  element of \code{lib.loc}), and the name of the package (in that
  order).  It is a good place to put calls to \code{\link{library.dynam}}
  which are needed when loading a package into this function (don't call
  \code{library.dynam} directly, as this will not work if the package
  is not installed in a \dQuote{standard} location).  \code{.First.lib}
  is invoked after the search path interrogated by \code{search()}
  has been updated, so
  \code{as.environment(match("package:name", search()))} will return the
  environment in which the package is stored.  If calling
  \code{.First.lib} gives an error the loading of the package is
  abandoned, and the package will be unavailable.  Similarly, if the
  option \code{".First.lib"} has a list element with the package's name,
  this element is called in the same manner as \code{.First.lib} when
  the package is loaded.  This mechanism allows the user to set package
  \dQuote{load hooks} in addition to startup code as provided by the package
  maintainers.

  \code{.Last.lib} is called when a package is detached.  Beware
  that it might be called if \code{.First.lib} has failed, so it
  should be written defensively. (It is called within \code{\link{try}},
  so errors will not stop the package being detached.)

  \code{.packages()} returns the \dQuote{base names} of the currently attached
  packages \emph{invisibly} whereas
  \code{.packages(all.available = TRUE)} gives (visibly) \emph{all}
  packages available in the library location path \code{lib.loc}.

  \code{.path.package} returns the paths from which the named packages
  were loaded, or if none were named, for all currently loaded packages.
  Unless \code{quiet = TRUE} it will warn if some of the packages named
  are not loaded, and given an error if none are.  This function is not
  meant to be called by users, and its interface might change in future
  versions.

  \code{.find.package} returns the paths to the locations where the
  given packages can be found.  If \code{lib.loc} is \code{NULL}, then
  then attached packages are searched before the libraries.  If a
  package is found more than once, the first match is used.  Unless
  \code{quiet = TRUE} a warning will be given about the named packages
  which are not found, and an error if none are.  If \code{verbose} is
  true, warnings about packages found more than once are given.  This
  function is not meant to be called by users, and its interface might
  change in future versions.

  \code{.Autoloaded} contains the \dQuote{base names} of the packages for
  which autoloading has been promised.

  \code{.Library} is a character string giving the location of the
  default library, the \file{library} subdirectory of \env{R\_HOME}.
  \code{.libPaths} is used for getting or setting the library trees that
  \R knows about (and hence uses when looking for packages).  If called
  with argument \code{new}, the library search path is set to
  \code{unique(new, .Library)} and this is returned.  If given no
  argument, a character vector with the currently known library trees is
  returned.

#ifdef unix
  The library search path is initialized at startup from the environment
  variable \env{R\_LIBS} (which should be a colon-separated list of
  directories at which \R library trees are rooted) by calling
  \code{.libPaths} with the directories specified in \env{R\_LIBS}.
#endif
#ifdef windows
  The library search path is initialized at startup from the environment
  variable \env{R\_LIBS} (which should be a semicolon-separated list of
  directories at which \R library trees are rooted) by calling
  \code{.libPaths} with the directories specified in \env{R\_LIBS}.
#endif
}
\value{
  \code{library} returns the list of loaded (or available) packages
  (or \code{TRUE} if \code{logical.return} is \code{TRUE}).
  \code{require} returns a logical indicating whether the required
  package is available.
}
\section{Packages that require other packages}{The source code for a
  package that requires one or more other packages should have a call
  to \code{require}, preferably near the beginning of the source, and
  of course before any code that uses functions, classes or methods
  from the other package.  The default for argument \code{save} will
  save the names of all required packages in the environment of the
  new package.  The saved package names are used by
  \code{\link{detach}} when a package is detached to warn if other
  packages still require the detached package.  Also, if a package is
  installed with saved image (see \link{INSTALL}), the saved package
  names are used to require these packages when the new package is attached.}
\section{Formal methods}{
  \code{library} takes some further actions when package \pkg{methods}
  is attached (as it is by default).  Packages may define formal generic
  functions as well as re-defining functions in other packages (notably
  \pkg{base}) to be generic, and this information is cached whenever
  such a package is loaded after \pkg{methods} and re-defined functions
  are excluded from the list of conflicts.  The check requires looking
  for a pattern of objects; the pattern search may be avoided by
  defining an object \code{.noGenerics}
  (with any value) in the package.  Naturally, if the package
  \emph{does} have any such methods, this will prevent them from being used.
}
\note{
  \code{library} and \code{require} can only load an \emph{installed}
  package, and this is detected by having a \file{DESCRIPTION} file
  containing a \code{Built:} field.  Packages
  installed prior to 1.2.0 (released in December 2000) will need to be
  re-installed.

  Under Unix-alikes, the code checks that the package was installed
  under a similar operating system as given by
  \code{.Platform$canonical.name}, provided it contains compiled code.
  Packages which do not contain compiled code can be shared between
  Unix-alikes, but not to other OSes because of potential problems with
  line endings and OS-specific help files.

  \code{library} and \code{require} use the underlying file system
  services to locate the libraries, with the result that on
  case-sensitive file systems package names are case-sensitive
  (i.e., \code{library(foo)} is different from
  \code{library(Foo)}), but they are not distinguished on
  case-insensitive file systems such as MS Windows.  A warning
  is issued if the user specifies a name which isn't a perfect match
  to the package name, because future versions of \R will require
  exact matches.

}
\author{
  R core;
  Guido Masarotto for the \code{all.available=TRUE} part of
  \code{.packages}.
}
\seealso{
  \code{\link{attach}}, \code{\link{detach}}, \code{\link{search}},
  \code{\link{objects}}, \code{\link{autoload}},
  \code{\link{library.dynam}}, \code{\link{data}},
  \code{\link{install.packages}} and \code{\link{installed.packages}};
  \code{\link{INSTALL}}, \code{\link{REMOVE}}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
(.packages())               # maybe just "base"
.packages(all = TRUE)       # return all available as character vector
library()                   # list all available packages
library(lib = .Library)     # list all packages in the default library
library(help = eda)         # documentation on package 'eda'
library(eda)                # load package 'eda'
require(eda)                # the same
(.packages())               # "eda", too
detach("package:eda")

# if the package name is in a character vector, use
pkg <- "eda"
library(pkg, character.only = TRUE)
detach(pos = match(paste("package", pkg, sep=":"), search()))

require(pkg, character.only = TRUE)
detach(pos = match(paste("package", pkg, sep=":"), search()))

.path.package()
.Autoloaded                 # maybe "ctest"

.libPaths()                 # all library trees R knows about

require(nonexistent)        # FALSE
\dontrun{
## Suppose a package needs to call a shared library named 'fooEXT',
## where 'EXT' is the system-specific extension.  Then you should use
.First.lib <- function(lib, pkg) {
  library.dynam("foo", pkg, lib)
}

## if you want to mask as little as possible, use
library(mypkg, pos = "package:base")
}}
\keyword{data}
\eof
\name{library.dynam}
\alias{library.dynam}
\alias{library.dynam.unload}
\alias{.dynLibs}
\title{Loading Shared Libraries}
\description{
  Load the specified file of compiled code if it has not been loaded
  already, or unloads it.
}
\usage{
library.dynam(chname, package = .packages(), lib.loc = NULL,
              verbose = getOption("verbose"),
              file.ext = .Platform$dynlib.ext, \dots)
library.dynam.unload(chname, libpath,
              verbose = getOption("verbose"),
              file.ext = .Platform$dynlib.ext)
.dynLibs(new)
}
\arguments{
  \item{chname}{a character string naming a shared library to load.}
  \item{package}{a character vector with the names of packages to search
    through.}
  \item{lib.loc}{a character vector describing the location of \R
    library trees to search through, or \code{NULL}.  The default value
    of \code{NULL} corresponds to all libraries currently known.}
  \item{libpath}{the path to the loaded package whose shared library is
    to be unloaded.}
  \item{verbose}{a logical value indicating whether an announcement
    is printed on the console before loading the shared library.  The
    default value is taken from the verbose entry in the system
    options.}
  \item{file.ext}{the extension to append to the file name to specify
    the library to be loaded. This defaults to the appropriate value
    for the operating system.}
  \item{\dots}{additional arguments needed by some libraries that
    are passed to the call to \code{\link{dyn.load}} to control
    how the library is loaded.}
  \item{new}{a character vector of packages which have loaded shared
    libraries.}
}
\details{
  \code{library.dynam} is designed to be used inside a package rather
  than at the command line, and should really only be used inside
  \code{\link{.First.lib}} on \code{\link{.onLoad}}.  The
  system-specific extension for shared libraries
#ifdef unix
  (e.g., \file{.so} or \file{.sl} on Unix systems)
#endif
#ifdef windows
  (\file{.dll} on Windows)
#endif
  should not be added.

  \code{library.dynam.unload} is designed for use in \code{\link{.Last.lib}} or
  \code{\link{.onUnload}}.

  \code{.dynLibs} is used for getting or setting the packages that have
  loaded shared libraries (using \code{library.dynam}).  Versions of \R
  prior to 1.6.0 used an internal global variable \code{.Dyn.libs} for
  storing this information: this variable is now defunct.
}
\value{
  \code{library.dynam} returns a character vector with the names of
  packages which have used it in the current \R session to load shared
  libraries.  This vector is returned as \code{\link{invisible}}, unless
  the \code{chname} argument is missing.

  \code{library.dynam.unload} returns the updated character vector, invisibly.
}
\seealso{
  \code{\link{.First.lib}}, \code{\link{library}},
  \code{\link{dyn.load}}, \code{\link{.packages}},
  \code{\link{.libPaths}}

#ifdef unix
  \code{\link{SHLIB}} for how to create suitable shared libraries.
#endif
#ifdef windows
  \code{\link{SHLIB}} for how to create suitable DLLs.
#endif
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
library.dynam() # which packages have been "dynamically loaded"
}
\keyword{data}
\eof
\name{license}
\title{The R License Terms}
\alias{license}
\alias{licence}
\description{
  The license terms under which \R is distributed.
}
\usage{
license()
licence()
}
\details{
  \R is distributed under the terms of the GNU GENERAL PUBLIC LICENSE
  Version 2, June 1991.  A copy of this license is in
  \file{\$R\_HOME/COPYING}.

  A small number of files (the API header files and import library)
  are distributed under the LESSER GNU GENERAL PUBLIC LICENSE version
  2.1. A copy of this license is in \file{\$R\_HOME/COPYING.LIB}.
}
\keyword{misc}
\eof
\name{lines}
\alias{lines}
\alias{lines.default}
\title{Add Connected Line Segments to a Plot}
\description{
  A generic function taking coordinates given in various ways and
  joining the corresponding points with line segments.
}
\usage{
lines(x, \dots)

\method{lines}{default}(x, y = NULL, type = "l", col = par("col"),
      lty = par("lty"), \dots)
}
\arguments{
  \item{x, y}{coordinate vectors of points to join.}
  \item{type}{character indicating the type of plotting; actually any of
    the \code{type}s as in \code{\link{plot}}.}
  \item{col}{color to use. This can be vector of length greater than
    one, but only the first value will be used.}
  \item{lty}{line type to use.}
  \item{\dots}{Further graphical parameters (see \code{\link{par}}) may
    also be supplied as arguments, particularly, line type, \code{lty} and
    line width, \code{lwd}.}
}
\details{
  The coordinates can be passed to \code{lines} in a plotting structure
  (a list with \code{x} and \code{y} components), a time series,
  etc. See \code{\link{xy.coords}}.

  The coordinates can contain \code{NA} values. If a point contains
  \code{NA} it either its \code{x} or \code{y} value, it is omitted from
  the plot, and lines are not drawn to or from such points.  Thus
  missing values can be used to achieve breaks in lines.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{points}},
  \code{\link{plot}},
  and the underlying \dQuote{primitive} \code{\link{plot.xy}}.

  \code{\link{par}} for how to specify colors.
}
\examples{
data(cars)
# draw a smooth line through a scatter plot
plot(cars, main="Stopping Distance versus Speed")
lines(lowess(cars))
}
\keyword{aplot}
\eof
\name{list}
\title{Lists -- Generic and Dotted Pairs}
\usage{
list(\dots)
pairlist(\dots)

as.list(x, \dots)
%as.list.default(x, \dots)
as.pairlist(x)

is.list(x)
is.pairlist(x)

alist(\dots)
}
\alias{list}
\alias{pairlist}
\alias{alist}
\alias{as.list}
\alias{as.list.default}
\alias{as.list.data.frame}
\alias{as.pairlist}
\alias{is.list}
\alias{is.pairlist}
\description{
  Functions to construct, coerce and check for all kinds of \R lists.
}
\arguments{
  \item{\dots}{objects.}
  \item{x}{object to be coerced or tested.}
}
\details{
  Most lists in \R internally are \emph{Generic
    Vectors}, whereas traditional \emph{dotted pair} lists (as in LISP)
  are still available.

  The arguments to \code{list} or \code{pairlist} are of the form
  \code{value} or \code{tag=value}.
  The functions return a list composed of its arguments
  with each value either tagged or untagged,
  depending on how the argument was specified.

  \code{alist} is like \code{list}, except in the handling of tagged
  arguments with no value. These are handled as if they described
  function arguments with no default (cf. \code{\link{formals}}), whereas
  \code{list} simply ignores them.

  \code{as.list} attempts to coerce its argument to list type.
  For functions, this returns the concatenation of the list of formals
  arguments and the function body. For expressions, the list of
  constituent calls is returned.

  \code{is.list} returns \code{TRUE} iff its argument
  is a \code{list} \emph{or} a \code{pairlist} of \code{length}\eqn{> 0},
  whereas \code{is.pairlist} only returns \code{TRUE} in the latter case.

  \code{is.list} and \code{is.pairlist} are generic: you can write
  methods to handle of specific classes of objects, see \link{InternalMethods}.

  An empty pairlist, \code{pairlist()} is the same as \code{NULL}.  This
  is different from \code{list()}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
\code{\link{vector}(., mode="list")}, \code{\link{c}}, for concatenation;
\code{\link{formals}}.
}
\examples{
data(cars)
# create a plotting structure
pts <- list(x=cars[,1], y=cars[,2])
plot(pts)

# Argument lists
f <- function()x
# Note the specification of a "..." argument:
formals(f) <- al <- alist(x=, y=2, \dots=)
f
str(al)

str(pl <- as.pairlist(ps.options()))

## These are all TRUE:
is.list(pl) && is.pairlist(pl)
!is.null(list())
is.null(pairlist())
!is.list(NULL)
is.pairlist(pairlist())
is.null(as.pairlist(list()))
is.null(as.pairlist(NULL))
}
\keyword{list}
\keyword{manip}
\eof
\name{list.files}
\alias{list.files}
\alias{dir}
\title{List the Files in a Directory/Folder}
\usage{
list.files(path = ".", pattern = NULL, all.files = FALSE,
           full.names = FALSE, recursive = FALSE)
       dir(path = ".", pattern = NULL, all.files = FALSE,
           full.names = FALSE, recursive = FALSE)
}
\arguments{
  \item{path}{a character vector of full path names.}
  \item{pattern}{an optional regular expression.  Only file names
    which match the regular expression will be returned.}
  \item{all.files}{a logical value. If \code{FALSE}, only the
    names of visible files are returned.  If \code{TRUE},
    all file names will be returned.}
  \item{full.names}{a logical value.  If \code{TRUE}, the directory
    path is prepended to the file names.  If \code{FALSE}, only
    the file names are returned.}
  \item{recursive}{logical. Should the listing recurse into directories?}
}
\description{
  This function produces a list containing the names of files
  in the named directory. \code{dir} is an alias.
}
\value{
  A character vector containing the names of the files in the
  specified directories, or \code{""} if there were no files. If a
  path does not exist or is not a directory or is unreadable it
  is skipped, with a warning.

  The files are sorted in alphabetical order, on the full path
  if \code{full.names = TRUE}.
}
\author{Ross Ihaka, Brian Ripley}
\note{
  File naming conventions are very platform dependent.

  \code{recursive = TRUE} is not supported on all platforms, and may be
  ignored, with a warning.
}
\seealso{\code{\link{file.info}}, \code{\link{file.access}}
  and \code{\link{files}} for many more file handling functions.}
\examples{
list.files(R.home())
## Only files starting with a-l or r (*including* uppercase):
dir("../..", pattern = "^[a-lr]",full.names=TRUE)
}
\keyword{file}
\eof
\name{lm}
\alias{lm}
\alias{print.lm}
%\alias{print.lm.null}
\title{Fitting Linear Models}
\description{
  \code{lm} is used to fit linear models.
  It can be used to carry out regression,
  single stratum analysis of variance and
  analysis of covariance (although \code{\link{aov}} may provide a more
  convenient interface for these).
}
\usage{
lm(formula, data, subset, weights, na.action,
   method = "qr", model = TRUE, x = FALSE, y = FALSE, qr = TRUE,
   singular.ok = TRUE, contrasts = NULL, offset = NULL, \dots)
}
\arguments{
  \item{formula}{a symbolic description of the model to be fit.
    The details of model specification are given below.}

  \item{data}{an optional data frame containing the variables
    in the model.  By default the variables are taken from
    \code{environment(formula)}, typically the environment from which
    \code{lm} is called.}

  \item{subset}{an optional vector specifying a subset of observations
    to be used in the fitting process.}

  \item{weights}{an optional vector of weights to be used
    in the fitting process. If specified, weighted least squares is used
    with weights \code{weights} (that is, minimizing \code{sum(w*e^2)});
    otherwise ordinary least squares is used.}

  \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{method}{the method to be used; for fitting, currently only
    \code{method="qr"} is supported; \code{method="model.frame"} returns
    the model frame (the same as with \code{model = TRUE}, see below).}

  \item{model, x, y, qr}{logicals.  If \code{TRUE} the corresponding
    components of the fit (the model frame, the model matrix, the
    response, the QR decomposition) are returned.}

  \item{singular.ok}{logical. If \code{FALSE} (the default in S but
    not in \R) a singular fit is an error.}

  \item{contrasts}{an optional list. See the \code{contrasts.arg}
    of \code{model.matrix.default}.}

  \item{offset}{this can be used to specify an \emph{a priori}
    known component to be included in the linear predictor
    during fitting.  An \code{\link{offset}} term can be included in the
    formula instead or as well, and if both are specified their sum is used.}

  \item{\dots}{additional arguments to be passed to the low level
    regression fitting functions (see below).}
}
\details{
  Models for \code{lm} are specified symbolically.  A typical model has
  the form \code{response ~ terms} where \code{response} is the (numeric)
  response vector and \code{terms} is a series of terms which specifies a
  linear predictor for \code{response}.  A terms specification of the form
  \code{first + second} indicates all the terms in \code{first} together
  with all the terms in \code{second} with duplicates removed.  A
  specification of the form \code{first:second} indicates the set of
  terms obtained by taking the interactions of all terms in \code{first}
  with all terms in \code{second}.  The specification \code{first*second}
  indicates the \emph{cross} of \code{first} and \code{second}.  This is
  the same as \code{first + second + first:second}.  If \code{response} 
  is a matrix a linear model is fitted to each column of the matrix.
  See \code{\link{model.matrix}} for some further details.

  \code{lm} calls the lower level functions \code{\link{lm.fit}}, etc,
  see below, for the actual numerical computations.  For programming
  only, you may consider doing likewise.
}
\value{
  \code{lm} returns an object of \code{\link[base]{class}} \code{"lm"} or for
  multiple responses of class \code{c("mlm", "lm")}.

  The functions \code{summary} and \code{\link{anova}} are used to
  obtain and print a summary and analysis of variance table of the
  results.  The generic accessor functions \code{coefficients},
  \code{effects}, \code{fitted.values} and \code{residuals} extract
  various useful features of the value returned by \code{lm}.

  An object of class \code{"lm"} is a list containing at least the
  following components:

  \item{coefficients}{a named vector of coefficients}
  \item{residuals}{the residuals, that is response minus fitted values.}
  \item{fitted.values}{the fitted mean values.}
  \item{rank}{the numeric rank of the fitted linear model.}
  \item{weights}{(only for weighted fits) the specified weights.}
  \item{df.residual}{the residual degrees of freedom.}
  \item{call}{the matched call.}
  \item{terms}{the \code{\link{terms}} object used.}
  \item{contrasts}{(only where relevant) the contrasts used.}
  \item{xlevels}{(only where relevant) a record of the levels of the
    factors used in fitting.}
  \item{y}{if requested, the response used.}
  \item{x}{if requested, the model matrix used.}
  \item{model}{if requested (the default), the model frame used.}

  In addition, non-null fits will have components \code{assign},
  \code{effects} and (unless not requested) \code{qr} relating to the linear
  fit, for use by extractor functions such as \code{summary} and
  \code{\link{effects}}.
}
\seealso{
  \code{\link{summary.lm}} for summaries and \code{\link{anova.lm}} for
  the ANOVA table; \code{\link{aov}} for a different interface.

  The generic functions \code{\link{coefficients}}, \code{\link{effects}},
  \code{\link{residuals}}, \code{\link{fitted.values}}.

  \code{\link{predict.lm}} (via \code{\link{predict}}) for prediction,
  including confidence and prediction intervals.

  \code{\link{lm.influence}} for regression diagnostics, and
  \code{\link{glm}} for \bold{generalized} linear models.

  The underlying low level functions,
  \code{\link{lm.fit}} for plain, and \code{\link{lm.wfit}} for weighted
  regression fitting.
}
\references{
  Chambers, J. M. (1992)
  \emph{Linear models.}
  Chapter 4 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.

  Wilkinson, G. N. and Rogers, C. E. (1973)
  Symbolic descriptions of factorial models for analysis of variance.
  \emph{Applied Statistics}, \bold{22}, 392--9.
}
\author{
  The design was inspired by the S function of the same name described
  in Chambers (1992).  The implementation of model formula by Ross Ihaka
  was based on Wilkinson \& Rogers (1973).
}

\note{
  Offsets specified by \code{offset} will not be included in predictions
  by \code{\link{predict.lm}}, whereas those specified by an offset term
  in the formula will be.
}
\examples{
## Annette Dobson (1990) "An Introduction to Generalized Linear Models".
## Page 9: Plant Weight Data.
ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)
trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)
group <- gl(2,10,20, labels=c("Ctl","Trt"))
weight <- c(ctl, trt)
anova(lm.D9 <- lm(weight ~ group))
summary(lm.D90 <- lm(weight ~ group - 1))# omitting intercept
summary(resid(lm.D9) - resid(lm.D90)) #- residuals almost identical

opar <- par(mfrow = c(2,2), oma = c(0, 0, 1.1, 0))
plot(lm.D9, las = 1)      # Residuals, Fitted, ...
par(opar)

## model frame :
stopifnot(identical(lm(weight ~ group, method = "model.frame"),
                    model.frame(lm.D9)))
}
\keyword{regression}
\eof
\name{lm.influence}
\title{Regression Diagnostics}
\usage{
influence(model, \dots)
\method{influence}{lm}(model, do.coef = TRUE, \dots)
\method{influence}{glm}(model, do.coef = TRUE, \dots)

lm.influence(model, do.coef = TRUE)
}
\alias{lm.influence}
\alias{influence}
\alias{influence.lm}
\alias{influence.glm}
\arguments{
  \item{model}{an object as returned by \code{\link{lm}}.}
  \item{do.coef}{logical indicating if the changed \code{coefficients}
    (see below) are desired.  These need \eqn{O(n^2 p)} computing time.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\description{
  This function provides the basic quantities which are
  used in forming a wide variety of diagnostics for
  checking the quality of regression fits.
}
\details{
  The \code{\link{influence.measures}()} and other functions listed in
  \bold{See Also} provide a more user oriented way of computing a
  variety of regression diagnostics.  These all build on
  \code{lm.influence}.

  An attempt is made to ensure that computed hat values that are
  probably one are treated as one, and the corresponding rows in
  \code{sigma} and \code{coefficients} are \code{NaN}.  (Dropping such a
  case would normally result in a variable being dropped, so it is not
  possible to give simple drop-one diagnostics.)
}
\value{
  A list containing the following components of the same length or
  number of rows \eqn{n}, which is the number of non-zero weights.
  Cases omitted in the fit are omitted unless a \code{\link{na.action}}
  method was used (such as \code{\link{na.exclude}}) which restores them.
  
  \item{hat}{a vector containing the diagonal of the \dQuote{hat} matrix.}
  \item{coefficients}{(unless \code{do.coef} is false) a matrix whose
    i-th row contains the change in the estimated coefficients which
    results when the i-th case is dropped from the regression.  Note
    that aliased coefficients are not included in the matrix.}
  \item{sigma}{a vector whose i-th element contains the estimate
    of the residual standard deviation obtained when the i-th
    case is dropped from the regression.}
  \item{wt.res}{a vector of \emph{weighted} (or for class \code{glm}
    rather \emph{deviance}) residuals.}
}
\note{
  The \code{coefficients} returned by the \R version
  of \code{lm.influence} differ from those computed by S.
  Rather than returning the coefficients which result
  from dropping each case, we return the changes in the coefficients.
  This is more directly useful in many diagnostic measures.\cr
  Since these need \eqn{O(n^2 p)} computing time, they can be omitted by
  \code{do.coef = FALSE}.

  Note that cases with \code{weights == 0} are \emph{dropped} (contrary
  to the situation in S).

  If a model has been fitted with \code{na.action=na.exclude} (see
  \code{\link{na.exclude}}), cases excluded in the fit \emph{are}
  considered here.
}
\references{
  See the list in the documentation for \code{\link{influence.measures}}.

  Chambers, J. M. (1992)
  \emph{Linear models.}
  Chapter 4 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\seealso{
\code{\link{summary.lm}} for \code{\link{summary}} and related methods;\cr
\code{\link{influence.measures}},\cr
\code{\link{hat}} for the hat matrix diagonals,\cr
\code{\link{dfbetas}},
\code{\link{dffits}},
\code{\link{covratio}},
\code{\link{cooks.distance}},
\code{\link{lm}}.
}
\examples{
## Analysis of the life-cycle savings data
## given in Belsley, Kuh and Welsch.
data(LifeCycleSavings)
summary(lm.SR <- lm(sr ~ pop15 + pop75 + dpi + ddpi,
                    data = LifeCycleSavings),
        corr = TRUE)
str(lmI <- lm.influence(lm.SR))

## For more "user level" examples, use example(influence.measures)
}
\keyword{regression}
\eof
\name{lm.summaries}
\alias{family.lm}
\alias{formula.lm}
\alias{residuals.lm}
\alias{weights}
\alias{weights.default}
\title{Accessing Linear Model Fits}
\usage{
\method{family}{lm}(object, \dots)

\method{formula}{lm}(x, \dots)

\method{residuals}{lm}(object,
          type = c("working", "response", "deviance","pearson", "partial"),
          \dots)

weights(object, \dots)
}
\arguments{
  \item{object, x}{an object inheriting from class \code{lm}, usually
    the result of a call to \code{\link{lm}} or \code{\link{aov}}.}
  \item{\dots}{further arguments passed to or from other methods.}
  \item{type}{the type of residuals which should be returned.}
}
\description{
  All these functions are \code{\link{methods}} for class \code{"lm"}  objects.
}
\details{
  The generic accessor functions \code{coef}, \code{effects},
  \code{fitted} and \code{residuals} can be used to extract
  various useful features of the value returned by \code{lm}.

  The working and response residuals are \dQuote{observed - fitted}.  The
  deviance and pearson residuals are weighted residuals, scaled by the
  square root of the weights used in fitting.  The partial residuals
  are a matrix with each column formed by omitting a term from the
  model.  In all these, zero weight cases are never omitted (as opposed
  to the standardized \code{\link{rstudent}} residuals).

}
\seealso{
  The model fitting function \code{\link{lm}}, \code{\link{anova.lm}}.

  \code{\link{coef}}, \code{\link{deviance}},
  \code{\link{df.residual}},
  \code{\link{effects}}, \code{\link{fitted}},
  \code{\link{glm}} for \bold{generalized} linear models,
  \code{\link{influence}} (etc on that page) for regression diagnostics,
  \code{\link{weighted.residuals}},
  \code{\link{residuals}}, \code{\link{residuals.glm}},
  \code{\link{summary.lm}}.
}
\references{
  Chambers, J. M. (1992)
  \emph{Linear models.}
  Chapter 4 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\examples{
\dontshow{example("lm", echo = FALSE)}
##-- Continuing the  lm(.) example:
coef(lm.D90)# the bare coefficients

## The 2 basic regression diagnostic plots [plot.lm(.) is preferred]
plot(resid(lm.D90), fitted(lm.D90))# Tukey-Anscombe's
abline(h=0, lty=2, col = 'gray')

qqnorm(residuals(lm.D90))
}
\keyword{regression}
\keyword{models}
\eof
\name{lm.fit}
\title{Fitter Functions for Linear Models}
\usage{
lm.fit (x, y,    offset = NULL, method = "qr", tol = 1e-7,
       singular.ok = TRUE, \dots)

lm.wfit(x, y, w, offset = NULL, method = "qr", tol = 1e-7,
        singular.ok = TRUE, \dots)
}
\alias{lm.fit}
\alias{lm.wfit}
\description{
  These are the basic computing engines called by \code{\link{lm}} used
  to fit linear models.  These should usually \emph{not} be used
  directly unless by experienced users.
}
\arguments{
  \item{x}{design matrix of dimension \code{n * p}.}
  \item{y}{vector of observations of length \code{n}.}
  \item{w}{vector of weights (length \code{n}) to be used in the fitting
    process for the \code{wfit} functions.  Weighted least squares is
    used with weights \code{w}, i.e., \code{sum(w * e^2)} is minimized.}
  \item{offset}{numeric of length \code{n}).  This can be used to
    specify an \emph{a priori} known component to be included in the
    linear predictor during fitting.}

  \item{method}{currently, only \code{method="qr"} is supported.}

  \item{tol}{tolerance for the \code{\link{qr}} decomposition.  Default
    is 1e-7.}

  \item{singular.ok}{logical. If \code{FALSE}, a singular model is an
    error.}
  
  \item{\dots}{currently disregarded.}
}
\details{
  The functions \code{lm.\{w\}fit.null} are called by \code{lm.fit} or
  \code{lm.wfit} respectively, when \code{x} has zero columns.
}
\value{
%% S(-PLUS) returns an object of class "lm"
%% such that print.lm, summary,... work; but that'd need more changes for R.
  a list with components
  \item{coefficients}{\code{p} vector}
  \item{residuals}{\code{n} vector}
  \item{fitted.values}{\code{n} vector}
  \item{effects}{(not null fits)\code{n} vector of orthogonal single-df
    effects.  The first \code{rank} of them correspond to non-aliased
    coeffcients, and are named accordingly.}
  \item{weights}{\code{n} vector --- \emph{only} for the \code{*wfit*}
    functions.}
  \item{rank}{integer, giving the rank}
  \item{df.residual}{degrees of freedom of residuals}
  \item{qr}{(not null fits) the QR decomposition, see \code{\link{qr}}.}
}
\seealso{
  \code{\link{lm}} which you should use for linear least squares regression,
  unless you know better.
}
\examples{
%% FIXME: Do something more sensible (non-random data) !!
set.seed(129)
n <- 7 ; p <- 2
X <- matrix(rnorm(n * p), n,p) # no intercept!
y <- rnorm(n)
w <- rnorm(n)^2

str(lmw <- lm.wfit(x=X, y=y, w=w))

str(lm. <- lm.fit (x=X, y=y))

%% do an example which sets 'tol' and gives a difference!
}
\keyword{regression}
\keyword{array}
\eof
\name{load}
\alias{load}
\alias{loadURL}
\title{Reload Saved Datasets}
\description{
  Reload the datasets written to a file with the function \code{save}.
}
\usage{
load(file, envir = parent.frame())
loadURL(url, envir = parent.frame(), quiet = TRUE, \dots)
}
\arguments{
  \item{file}{a connection or a character string giving the name of the
    file to load.}
  \item{envir}{the environment where the data should be loaded.}
  \item{url}{a character string naming a URL.}
  \item{quiet, \dots}{additional arguments to \code{\link{download.file}}.}
}
\details{
  \code{load} can load \R objects saved in the current or any earlier
  format.  It can read a compressed file (see \code{\link{save}})
  directly from a file or from a suitable connection.

  \code{loadURL} is a convenience wrapper which downloads a file, loads
  it and deletes the downloaded copy.
}
\value{
  A character vector of the names of objects created, invisibly.
}
\seealso{
  \code{\link{save}}, \code{\link{download.file}}.
}
\examples{
## save all data
save(list = ls(), file= "all.Rdata")

## restore the saved values to the current environment
load("all.Rdata")

## restore the saved values to the user's workspace
load("all.Rdata", .GlobalEnv)

\dontrun{## This example may not still be available
## print the value to see what objects were created.
print(loadURL("http://hesweb1.med.virginia.edu/biostat/s/data/sav/kprats.sav"))}
}
\keyword{file}
\eof
\name{localeconv}
\alias{localeconv}
\alias{Sys.localeconv}
\title{Find Details of the Numerical Representations in the Current Locale}
\description{
  Get details of the numerical representations in the current locale.
}
\usage{
Sys.localeconv()
}
\value{
  A character vector with 18 named components. See your ISO C
  documentation for details of the meaning.

  It is possible to compile \R without support for locales, in which
  case the value will be \code{NULL}.
}
\seealso{
  \code{\link{Sys.setlocale}} for ways to set locales: by default \R uses the
  C clocal for \code{"LC_NUMERIC"} and \code{"LC_MONETARY"}.
}
\examples{
Sys.localeconv()
## The results in the default C locale are
##    decimal_point     thousands_sep          grouping   int_curr_symbol 
##              "."                ""                ""                "" 
##  currency_symbol mon_decimal_point mon_thousands_sep      mon_grouping 
##               ""                ""                ""                "" 
##    positive_sign     negative_sign   int_frac_digits       frac_digits 
##               ""                ""             "127"             "127" 
##    p_cs_precedes    p_sep_by_space     n_cs_precedes    n_sep_by_space 
##            "127"             "127"             "127"             "127" 
##      p_sign_posn       n_sign_posn 
##            "127"             "127"

## Now try your default locale (which might be "C").
\dontrun{old <- Sys.getlocale()
Sys.setlocale(locale = "")
Sys.localeconv()
Sys.setlocale(locale = old)}

\dontrun{read.table("foo", dec=Sys.localeconv()["decimal_point"])}
}
\keyword{utilities}
\eof
\name{locales}
\alias{locales}
\alias{Sys.getlocale}
\alias{Sys.setlocale}
\title{Query or Set Aspects of the Locale}
\description{
  Get details of or set aspects of the locale for the \R process.
}
\usage{
Sys.getlocale(category = "LC_ALL")
Sys.setlocale(category = "LC_ALL", locale = "")
}
\arguments{
  \item{category}{character string. Must be one of \code{"LC_ALL"},
    \code{"LC_COLLATE"}, \code{"LC_CTYPE"}, \code{"LC_MONETARY"},
    \code{"LC_NUMERIC"} or \code{"LC_TIME"}.}
  \item{locale}{character string. A valid locale name on the system in
    use. Normally \code{""} (the default) will pick up the default
    locale for the system.}
}
\details{
  The locale describes aspects of the internationalization of a program.
  Initially most aspects of the locale of \R are set to \code{"C"} (which
  is the default for the C language and reflects North-American usage).
  \R does set \code{"LC_CTYPE"} and \code{"LC_COLLATE"}, which allow the
  use of a different character set (typically ISO Latin 1) and alphabetic
  comparisons in that character set (including the use of
  \code{\link{sort}}) and \code{"LC_TIME"} may affect
  the behaviour of \code{\link{as.POSIXlt}} and \code{\link{strptime}}
  and functions which use them (but not \code{\link{date}}).

  \R can be built with no support for locales, but it is normally
  available on Unix and is available on Windows.

  Some systems will have other locale categories, but the six described
  here are those specified by POSIX.
}
\value{
  A character string of length one describing the locale in use (after
  setting for \code{Sys.setlocale}), or an empty character string if the
  locale is invalid (with a warning) or \code{NULL} if locale
  information is unavailable.

  For \code{category = "LC_ALL"} the details of the string are
  system-specific: it might be a single locale or a set of locales
  separated by \code{"/"} (Solaris) or \code{";"} (Windows).  For
  portability, it is best to query categories individually.  It is
  guaranteed that the result of \code{foo <- Sys.getlocale()} can be
  used in \code{Sys.setlocale("LC_ALL", locale = foo)} on the same
  machine.
}
\section{Warning}{
  Setting \code{"LC_NUMERIC"} can produce output that \R cannot then
  read by \code{scan} or \code{read.table} with their default arguments,
  which are not locale-specific.
}
\seealso{
  \code{\link{strptime}} for uses of \code{category = "LC_TIME"}.
  \code{\link{Sys.localeconv}} for details of numerical representations.
}
\examples{
Sys.getlocale()
Sys.getlocale("LC_TIME")
\dontrun{
Sys.setlocale("LC_TIME", "de")     # Solaris: details are OS-dependent
Sys.setlocale("LC_TIME", "German") # Windows}

Sys.setlocale("LC_COLLATE", "C")  # turn off locale-specific sorting
}
\keyword{utilities}
\eof
\name{locator}
\alias{locator}
\title{Graphical Input}
\description{
  Reads the position of the graphics cursor when the (first) mouse
  button is pressed.
}
\usage{
locator(n = 512, type = "n", \dots)
}
\arguments{
  \item{n}{the maximum number of points to locate.}
  \item{type}{One of \code{"n"}, \code{"p"}, \code{"l"} or
    \code{"o"}. If \code{"p"} or \code{"o"} the points are
    plotted; if \code{"l"}  or \code{"o"} they are joined by lines.}
  \item{\dots}{additional graphics parameters used if \code{type != "n"}
    for plotting the locations.}
}
\value{
  A list containing \code{x} and \code{y} components which are the
  coordinates of the identified points.
}
\details{
  Unless the process is terminated prematurely by the user (see below)
  at most \code{n} positions are determined.

#ifdef unix
  The identification process can be terminated by pressing any mouse
  button other than the first.
#endif
#ifdef windows
  The identification process can be terminated by clicking the second
  button and selecting \sQuote{Stop} from the menu, or from the
  \sQuote{Stop} menu on the graphics window.
#endif

  The current graphics parameters apply just as if \code{plot.default}
  has been called with the same value of \code{type}. The plotting of
  the points and lines is subject to clipping, but locations outside the
  current clipping rectangle will be returned.

  On most devices which support \code{locator}, successful selection of
  a point is indicated by a bell sound unless
  \code{\link{options}(locatorBell=FALSE)} has been set.

  If the window is resized or hidden and then exposed before the input 
  process has terminated, any lines or points drawn by \code{locator}
  will disappear.  These will reappear once the input process has 
  terminated and the window is resized or hidden and exposed again.
  This is because the points and lines drawn by \code{locator} are not
  recorded in the device's display list until the input process has
  terminated.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{identify}}
}
\keyword{iplot}
\eof
\name{logLik}
\title{Extract Log-Likelihood}
\usage{
logLik(object, \dots)

\method{as.data.frame}{logLik}(x, row.names = NULL, optional = FALSE)
%notyet print(logLik(*), ...)
%notyet   str(logLik(*), ...)
}
\alias{logLik}
\alias{print.logLik}
\alias{str.logLik}
\alias{as.data.frame.logLik}
\arguments{
 \item{object}{any object from which a log-likelihood value, or a
   contribution to a log-likelihood value, can be extracted.}
 \item{\dots}{some methods for this generic function require additional
   arguments.}
 \item{x}{an object of class \code{logLik}.}
 \item{row.names, optional}{arguments to the \code{\link{as.data.frame}}
   method; see its documentation.}
}
\description{
  This function is generic; method functions can be written to handle
  specific classes of objects.  Classes which already have methods for
  this function include: \code{glm}, \code{lm},
  \code{nls} in package \pkg{nls}
  and \code{gls}, \code{lme} and others in package \pkg{nlme}.
%   \code{corStruct}, \code{lmList}, \code{lmeStruct}, \code{reStruct}, and
%   \code{varFunc}.
}
\value{
  Returns an object, say \code{r}, of class \code{logLik} which is a
  number with attributes, \code{attr(r, "df")} (\bold{d}egrees of
  \bold{f}reedom) giving the number of parameters in the model.
  There's a simple \code{print} method for \code{logLik} objects.

  The details depend on the method function used; see the appropriate
  documentation.
}
\seealso{\code{\link{logLik.lm}}, \code{\link{logLik.glm}},
  \code{\link[nlme]{logLik.gls}}, \code{\link[nlme]{logLik.lme}}, etc.}
\author{Jose Pinheiro and Douglas Bates}
\examples{
## see the method function documentation
x <- 1:5
lmx <- lm(x ~ 1)
logLik(lmx) # using print.logLik() method
str(logLik(lmx))
}
\keyword{models}
\eof
\name{logLik.glm}
\alias{logLik.glm}
\title{Extract Log-Likelihood from an glm Object}
\usage{
\method{logLik}{glm}(object, \dots)
}
\arguments{
  \item{object}{an object inheriting from class \code{"glm"}.}
  \item{\dots}{further arguments to be passed to or from methods.}
}
\description{
  Returns the log-likelihood value of the generalized linear
  model represented by \code{object} evaluated at the estimated
  coefficients.
}
\value{
  the log-likelihood of the linear model represented by
  \code{object} evaluated at the estimated coefficients.
}
\details{
  As a \code{\link{family}} does not have to specify how to calculate
  the log-likelihood, this is based on the family's function to compute
  the AIC.  For \code{\link{gaussian}}, \code{\link{Gamma}} and
  \code{\link{inverse.gaussian}}
  families it assumed that the dispersion of the GLM is estimated and
  has been included in the AIC, and for all other families it is assumed
  that the dispersion is known.

  Not that this procedure is not completely accurate for the gamma and
  inverse gaussian families, as the estimate of dispersion used is not
  the MLE.
}
\seealso{\code{\link{glm}}, \code{\link{logLik.lm}}}
\keyword{models}
\eof
\name{logLik.lm}
\alias{logLik.lm}
\title{Extract Log-Likelihood from an lm Object}
\usage{
\method{logLik}{lm}(object, REML = FALSE, \dots)
}
\arguments{
  \item{object}{an object inheriting from class \code{"lm"}.}
  \item{REML}{an optional logical value.  If \code{TRUE} the restricted
    log-likelihood is returned, else, if \code{FALSE}, the
    log-likelihood is returned.  Defaults to \code{FALSE}.}
  \item{\dots}{further arguments to be passed to or from methods.}
}
\description{
  If \code{REML = FALSE}, returns the log-likelihood value of the linear
  model represented by \code{object} evaluated at the estimated
  coefficients; else, the restricted log-likelihood evaluated at the
  estimated coefficients is returned.
}
\value{
  an object of class \code{logLik},
  the (restricted) log-likelihood of the linear model represented by
  \code{object} evaluated at the estimated coefficients.  Note that
  error variance \eqn{\sigma^2} is estimated in \code{lm()} and hence
  counted as well.
}
\references{
  Harville, D.A. (1974).
  Bayesian inference for variance components using only error contrasts.
  \emph{Biometrika}, \bold{61}, 383--385.
}
\author{Jose Pinheiro and Douglas Bates}
\seealso{\code{\link{lm}}}
\examples{
data(attitude)
(fm1 <- lm(rating ~ ., data = attitude))
logLik(fm1)
logLik(fm1, REML = TRUE)


res <- try(data(Orthodont, package="nlme"))
if(!inherits(res, "try-error")) {
  fm1 <- lm(distance ~ Sex * age, Orthodont)
  print(logLik(fm1))
  print(logLik(fm1, REML = TRUE))
}}
\keyword{models}
\eof
\name{logical}
\alias{logical}
\alias{as.logical}
\alias{as.logical.default}
\alias{is.logical}
\alias{TRUE}
\alias{FALSE}
\alias{T}
\alias{F}
\title{Logical Vectors}
\description{
  Create or test for objects of type \code{"logical"}, and the basic
  logical \dQuote{constants}.
}
\usage{
TRUE
FALSE
T; F

logical(length = 0)
as.logical(x, \dots)
is.logical(x)
}
\details{
  \code{TRUE} and \code{FALSE} are part of the \R language, where
  \code{T} and \code{F} are global variables set to these.
  All four are \code{logical(1)} vectors.

  \code{is.logical} is generic: you can write methods to handle
  of specific classes of objects, see \link{InternalMethods}.
}
\arguments{
  \item{length}{desired length.}
  \item{x}{object to be coerced or tested.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\value{
  \code{logical} creates a logical vector of the specified length.
  Each element of the vector is equal to \code{FALSE}.

  \code{as.logical} attempts to coerce its argument to be of logical
  type.  For \code{\link{factor}}s, this uses the \code{\link{levels}}
  (labels) and not the \code{\link{codes}}.  Like
  \code{\link{as.vector}} it strips attributes including names.

  \code{is.logical} returns \code{TRUE} or \code{FALSE} depending on
  whether its argument is of logical type or not.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\keyword{classes}
\keyword{logic}
\eof
\name{loglin}
\alias{loglin}
\title{Fitting Log-Linear Models}
\usage{
loglin(table, margin, start = rep(1, length(table)), fit = FALSE,
       eps = 0.1, iter = 20, param = FALSE, print = TRUE)
}
\description{
  \code{loglin} is used to fit log-linear models to multidimensional
  contingency tables by Iterative Proportional Fitting.  
}
\arguments{
  \item{table}{a contingency table to be fit, typically the output from
    \code{table}.}
  \item{margin}{a list of vectors with the marginal totals to be fit.

    (Hierarchical) log-linear models can be specified in term of these
    marginal totals which give the \dQuote{maximal} factor subsets contained
    in the model.  For example, in a three-factor model,
    \code{list(c(1, 2), c(1, 3))} specifies a model which contains
    parameters for the grand mean, each factor, and the 1-2 and 1-3
    interactions, respectively (but no 2-3 or 1-2-3 interaction), i.e.,
    a model where factors 2 and 3 are independent conditional on factor
    1 (sometimes represented as \sQuote{[12][13]}).
     
    The names of factors (i.e., \code{names(dimnames(table))}) may be
    used rather than numeric indices.
  }
  \item{start}{a starting estimate for the fitted table.  This optional
    argument is important for incomplete tables with structural zeros
    in \code{table} which should be preserved in the fit.  In this
    case, the corresponding entries in \code{start} should be zero and
    the others can be taken as one.}
  \item{fit}{a logical indicating whether the fitted values should be
    returned.}
  \item{eps}{maximum deviation allowed between observed and fitted
    margins.}
  \item{iter}{maximum number of iterations.}
  \item{param}{a logical indicating whether the parameter values should
    be returned.}
  \item{print}{a logical.  If \code{TRUE}, the number of iterations and
    the final deviation are printed.}
}
\value{
  A list with the following components.
  \item{lrt}{the Likelihood Ratio Test statistic.}
  \item{pearson}{the Pearson test statistic (X-squared).}
  \item{df}{the degrees of freedom for the fitted model.  There is no
    adjustment for structural zeros.}
  \item{margin}{list of the margins that were fit.  Basically the same
    as the input \code{margin}, but with numbers replaced by names
    where possible.} 
  \item{fit}{An array like \code{table} containing the fitted values.
    Only returned if \code{fit} is \code{TRUE}.}
  \item{param}{A list containing the estimated parameters of the
    model.  The \dQuote{standard} constraints of zero marginal sums
    (e.g., zero row and column sums for a two factor parameter) are
    employed.  Only returned if \code{param} is \code{TRUE}.}
}
\details{
  The Iterative Proportional Fitting algorithm as presented in
  Haberman (1972) is used for fitting the model.  At most \code{iter}
  iterations are performed, convergence is taken to occur when the
  maximum deviation between observed and fitted margins is less than
  \code{eps}.  All internal computations are done in double precision;
  there is no limit on the number of factors (the dimension of the
  table) in the model.

  Assuming that there are no structural zeros, both the Likelihood
  Ratio Test and Pearson test statistics have an asymptotic chi-squared
  distribution with \code{df} degrees of freedom.
    
  Package \pkg{MASS} contains \code{loglm}, a front-end to \code{loglin}
  which allows the log-linear model to be specified and fitted in a
  formula-based manner similar to that of other fitting functions such
  as \code{lm} or \code{glm}.
}

\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Haberman, S. J. (1972)
  Log-linear fit for contingency tables---Algorithm AS51.
  \emph{Applied Statistics}, \bold{21}, 218--225.

  Agresti, A.  (1990)
  \emph{Categorical data analysis.}
  New York: Wiley.
}
\author{Kurt Hornik}
\seealso{\code{\link{table}}}
\examples{
data(HairEyeColor)
## Model of joint independence of sex from hair and eye color.
fm <- loglin(HairEyeColor, list(c(1, 2), c(1, 3), c(2, 3)))
fm
1 - pchisq(fm$lrt, fm$df)
## Model with no three-factor interactions fits well.
}
\keyword{category}
\keyword{models}
\eof
\name{longley}
\docType{data}
\alias{longley}
\title{Longley's Economic Regression Data}
\description{
  A macroeconomic data set which provides a well-known example for a
  highly collinear regression.
}
\usage{data(longley)}
\format{
  A data frame with 7 economical variables, observed yearly from 1947 to
  1962 (\eqn{n=16}).
  \describe{
    \item{GNP.deflator:}{GNP implicit price deflator (\eqn{1954=100})}
    \item{GNP:}{Gross National Product.}
    \item{Unemployed:}{number of unemployed.}
    \item{Armed.Forces:}{number of people in the armed forces.}
    \item{Population:}{\sQuote{noninstitutionalized} population
      \eqn{\ge} 14 years of age.}
    \item{Year:}{the year (time).}
    \item{Employed:}{number of people employed.}
  }

  The regression \code{lm(Employed ~ .)} is known to be highly
  collinear.
}
\source{
  J. W. Longley (1967)
  An appraisal of least-squares programs from the point of view of the
  user.
  \emph{Journal of the American Statistical Association}, \bold{62},
  819--841.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
## give the data set in the form it is used in S-PLUS:
data(longley)
longley.x <- data.matrix(longley[, 1:6])
longley.y <- longley[, "Employed"]
pairs(longley, main = "longley data")
summary(fm1 <- lm(Employed ~ ., data = longley))
opar <- par(mfrow = c(2, 2), oma = c(0, 0, 1.1, 0),
            mar = c(4.1, 4.1, 2.1, 1.1))
plot(fm1)
par(opar)
}
\keyword{datasets}
\eof
\name{lower.tri}
\alias{lower.tri}
\alias{upper.tri}
\title{Lower and Upper Triangular Part of a Matrix}
\description{
  Returns a matrix of logicals the same size of a given matrix with
  entries \code{TRUE} in the lower or upper triangle.
}
\usage{
lower.tri(x, diag = FALSE)
upper.tri(x, diag = FALSE)
}
\arguments{
  \item{x}{a matrix.}
  \item{diag}{logical. Should the diagonal be included?}
}
\seealso{
  \code{\link{diag}},
  \code{\link{matrix}}.
}
\examples{
(m2 <- matrix(1:20, 4, 5))
lower.tri(m2)
m2[lower.tri(m2)] <- NA
m2
}
\keyword{array}
\eof
\name{lowess}
\title{Scatter Plot Smoothing}
\usage{
lowess(x, y = NULL, f = 2/3, iter=3, delta = 0.01 * diff(range(xy$x[o])))
}
\alias{lowess}
\arguments{
  \item{x, y}{vectors giving the coordinates of the points in the scatter plot.
    Alternatively a single plotting structure can be specified.}
  \item{f}{the smoother span. This gives the proportion of points in
    the plot which influence the smooth at each value.
    Larger values give more smoothness.}
  \item{iter}{the number of robustifying iterations which should be
    performed.
    Using smaller values of \code{iter} will make \code{lowess} run faster.}
  \item{delta}{values of \code{x} which lie within \code{delta}
    of each other are replaced by a single value in the output from
    \code{lowess}.  Defaults to 1/100th of the range of \code{x}.}
}
\description{
  This function performs the computations for the
  \emph{LOWESS} smoother (see the reference below).
  \code{lowess} returns a list containing components
  \code{x} and \code{y} which give the coordinates of the smooth.
  The smooth should be added to a plot of the original
  points with the function \code{lines}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Cleveland, W. S. (1979)
  Robust locally weighted regression and smoothing scatterplots.
  \emph{J. Amer. Statist. Assoc.} \bold{74}, 829--836.

  Cleveland, W. S. (1981)
  LOWESS: A program for smoothing scatterplots by robust locally weighted
  regression. \emph{The American Statistician}, \bold{35}, 54.
}
\seealso{\code{\link[modreg]{loess}} (in package \pkg{modreg}), a newer
  formula based version of \code{lowess} (with different defaults!).
}
\examples{
data(cars)
plot(cars, main = "lowess(cars)")
lines(lowess(cars), col = 2)
lines(lowess(cars, f=.2), col = 3)
legend(5, 120, c(paste("f = ", c("2/3", ".2"))), lty = 1, col = 2:3)
}
\keyword{smooth}
\eof
\name{ls}
\alias{ls}
\alias{objects}
\title{List Objects}
\usage{
ls(name, pos = -1, envir = as.environment(pos),
   all.names = FALSE, pattern)
objects(name, pos= -1, envir = as.environment(pos),
        all.names = FALSE, pattern)
}
\arguments{
  \item{name}{which environment to use in listing the available objects.
    Defaults to the \emph{current}
    environment.  Although called \code{name} for back compatibility, in
    fact this argument can specify the environment in any form; see the
    details section.}
  \item{pos}{An alternative  argument to \code{name} for specifying the
    environment as a position in the search list.  Mostly there for
    back compatibility.}
  \item{envir}{an alternative  argument to \code{name} for specifying the
    environment evaluation environment. Mostly there for back compatibility.}
  \item{all.names}{a logical value.  If \code{TRUE}, all
    object names are returned.  If \code{FALSE}, names which begin with a
    \samp{.} are omitted.}
  \item{pattern}{an optional regular expression, see \code{\link{grep}}.
    Only names matching \code{pattern} are returned.}}
\details{
  The \code{name} argument can specify the  environment from which
  object names are taken in one of several forms:
  as an integer (the position in the \code{\link{search}} list); as
  the character string name of an element in the search list; or as an
  explicit \code{\link{environment}} (including using
  \code{\link{sys.frame}} to access the currently active function calls).
  By default, the environment of the call to \code{ls} or \code{objects}
  is used. The \code{pos} and \code{envir} arguments are an alternative
  way to specify an environment, but are primarily there for back
  compatibility.
}  
 \description{
   \code{ls} and \code{objects} return a vector of character strings
   giving the names of the objects in the specified environment.
   When invoked with no argument at the top level prompt,
   \code{ls} shows what data sets and functions a user has defined.
   When invoked with no argument inside a function,
   \code{ls} returns the names of the functions local variables.
   This is useful in conjunction with \code{browser}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{apropos}} (or \code{\link{find}}) for finding objects in the
  whole search path;
  \code{\link{grep}} for more details on \dQuote{regular expressions};
  \code{\link[base]{class}},
  \code{\link{methods}}, etc., for
  object-oriented programming.
}
\examples{
.Ob <- 1
ls(pat="O")
ls(pat="O", all = TRUE)    # also shows ".[foo]"

# shows an empty list because inside myfunc no variables are defined
myfunc <- function() {ls()}
myfunc()

# define a local variable inside myfunc
myfunc <- function() {y <- 1; ls()}
myfunc()                # shows "y"
}
\keyword{environment}
\eof
\name{ls.diag}
\title{Compute Diagnostics for `lsfit' Regression Results}
\usage{
ls.diag(ls.out)
}
\alias{ls.diag}
\arguments{
  \item{ls.out}{Typically the result of \code{\link{lsfit}()}}
}
\description{
  Computes basic statistics, including standard errors, t- and p-values
  for the regression coefficients.
}
\value{
  A \code{list} with the following numeric components.
  \item{std.dev}{The standard deviation of the errors, an estimate of
    \eqn{\sigma}{sigma}.}
  \item{hat}{diagonal entries \eqn{h_{ii}} of the hat matrix \eqn{H}}
  \item{std.res}{standardized residuals}
  \item{stud.res}{studentized residuals}
  \item{cooks}{Cook's distances}
  \item{dfits}{DFITS statistics}
  \item{correlation}{correlation matrix}
  \item{std.err}{standard errors of the regression coefficients}
  \item{cov.scaled}{Scaled covariance matrix of the coefficients}
  \item{cov.unscaled}{Unscaled covariance matrix of the coefficients}
}
\references{
  Belsley, D. A., Kuh, E. and Welsch, R. E. (1980)
  \emph{Regression Diagnostics.}
  New York: Wiley.
}
\seealso{
  \code{\link{hat}} for the hat matrix diagonals,
  \code{\link{ls.print}},
  \code{\link{lm.influence}}, \code{\link{summary.lm}},
  \code{\link{anova}}.
}
\examples{
\dontshow{example("lm", echo = FALSE)}
##-- Using the same data as the lm(.) example:
lsD9 <- lsfit(x = as.numeric(gl(2, 10, 20)), y = weight)
dlsD9 <- ls.diag(lsD9)
str(dlsD9, give.attr=FALSE)
abs(1 - sum(dlsD9$hat) / 2) < 10*.Machine$double.eps # sum(h.ii) = p
plot(dlsD9$hat, dlsD9$stud.res, xlim=c(0,0.11))
abline(h = 0, lty = 2, col = "lightgray")
}
\keyword{regression}
\eof
\name{ls.print}
\title{Print `lsfit' Regression Results}
\usage{
ls.print(ls.out, digits = 4, print.it = TRUE)
}
\alias{ls.print}
\arguments{
  \item{ls.out}{Typically the result of \code{\link{lsfit}()}}
  \item{digits}{The number of significant digits used for printing}
  \item{print.it}{a logical indicating whether the result should also be
    printed}
}
\description{
  Computes basic statistics, including standard errors, t- and p-values
  for the regression coefficients and prints them if \code{print.it} is
  \code{TRUE}.
}
\value{
  A list with the components
  \item{summary}{The ANOVA table of the regression}
  \item{coef.table}{matrix with regression coefficients, standard
    errors, t- and p-values}
}
\note{
  Usually, you'd rather use \code{summary(lm(\ldots))} and
  \code{anova(lm(\ldots))} for obtaining similar output.
}
\seealso{
  \code{\link{ls.diag}}, \code{\link{lsfit}}, also for examples;
  \code{\link{lm}}, \code{\link{lm.influence}} which usually are
  preferable.
}
\keyword{regression}
\eof
\name{lsfit}
\title{Find the Least Squares Fit}
\usage{
lsfit(x, y, wt=NULL, intercept=TRUE, tolerance=1e-07, yname=NULL)
}
\alias{lsfit}
\arguments{
\item{x}{a matrix whose rows correspond to cases and whose columns
  correspond to variables.}
\item{y}{the responses, possibly a matrix if you want to fit multiple
  left hand sides.}
\item{wt}{an optional vector of weights for performing weighted least squares.}
\item{intercept}{whether or not an intercept term should be used.}
\item{tolerance}{the tolerance to be used in the matrix decomposition.}
\item{yname}{names to be used for the response variables.}
}
\description{
The least squares estimate of \bold{\eqn{\beta}{b}} in the model
\deqn{\bold{Y} = \bold{X \beta} + \bold{\epsilon}}{y = X b + e}
is found.
}
\details{
If weights are specified then a weighted least squares is performed
with the weight given to the \emph{j}th case specified by the \emph{j}th
entry in \code{wt}.

If any observation has a missing value in any field, that observation
is removed before the analysis is carried out.
This can be quite inefficient if there is a lot of missing data.

The implementation is via a modification of the LINPACK subroutines
which allow for multiple left-hand sides.
}
\value{
A list with the following named components:
\item{coef}{the least squares estimates of the coefficients in
  the model (\bold{\eqn{\beta}{b}} as stated above).}
\item{residuals}{residuals from the fit.}
\item{intercept}{indicates whether an intercept was fitted.}
\item{qr}{the QR decomposition of the design matrix.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
\code{\link{lm}} which usually is preferable;
\code{\link{ls.print}}, \code{\link{ls.diag}}.
}
\examples{
\dontshow{example("lm", echo = FALSE)}
##-- Using the same data as the lm(.) example:
lsD9 <- lsfit(x = unclass(gl(2,10)), y = weight)
ls.print(lsD9)
}
\keyword{regression}
\eof
\name{mad}
\title{Median Absolute Deviation}
\usage{
mad(x, center = median(x), constant = 1.4826, na.rm = FALSE,
    low = FALSE, high = FALSE)
}
\alias{mad}
\arguments{
  \item{x}{a numeric vector.}
  \item{center}{Optionally, the centre: defauls to the median.}
  \item{constant}{scale factor.}
  \item{na.rm}{if \code{TRUE} then \code{NA} values are stripped
    from \code{x} before computation takes place.}
  \item{low}{if \code{TRUE}, compute the \dQuote{lo-median}, i.e., for even
    sample size, do not average the two middle values, but take the
    smaller one.}
  \item{high}{if \code{TRUE}, compute the \dQuote{hi-median}, i.e., take the
    larger of the two middle values for even sample size.}
}
\description{
  Compute the median absolute deviation, i.e., the (lo-/hi-) median of
  the absolute deviations from the median, and (by default) adjust by a
  factor for asymptotically normal consistency.
}
\details{
  The actual value calculated is \code{constant * cMedian(abs(x - center))}
  with the default value of \code{center} being \code{median(x)}, and
  \code{cMedian} being the usual, the \dQuote{low} or \dQuote{high} median, see
  the arguments description for \code{low} and \code{high} above.

  The default \code{constant = 1.4826} (approximately
  \eqn{1/\Phi^{-1}(\frac 3 4)}{1/ Phi^(-1)(3/4)} = \code{1/qnorm(3/4)})
  ensures consistency, i.e.,
  \deqn{E[mad(X_1,\dots,X_n)] = \sigma}
  for \eqn{X_i} distributed as \eqn{N(\mu,\sigma^2)} and large \eqn{n}.

  If \code{na.rm} is \code{TRUE} then \code{NA}
  values are stripped from \code{x} before computation takes place.
  If this is not done then an \code{NA} value in
  \code{x} will cause \code{mad} to return \code{NA}.
}
\seealso{
  \code{\link{IQR}} which is simpler but less robust,
  \code{\link{median}}, \code{\link{var}}.
}
\examples{
mad(c(1:9))
print(mad(c(1:9),     constant=1)) ==
      mad(c(1:8,100), constant=1)       # = 2 ; TRUE
x <- c(1,2,3, 5,7,8)
sort(abs(x - median(x)))
c(mad(x, co=1), mad(x, co=1, lo = TRUE), mad(x, co=1, hi = TRUE))
}
\keyword{univar}
\keyword{robust}

\eof
\name{mahalanobis}
\title{Mahalanobis Distance}
\usage{
mahalanobis(x, center, cov, inverted=FALSE, tol.inv = 1e-7)
}
\alias{mahalanobis}
\arguments{
  \item{x}{vector or matrix of data with, say, \eqn{p} columns.}
  \item{center}{mean vector of the distribution or second data vector of
    length \eqn{p}.}
  \item{cov}{covariance matrix (\eqn{p \times p}{p x p}) of the distribution.}
  \item{inverted}{logical.  If \code{TRUE}, \code{cov} is supposed to
    contain the \emph{inverse} of the covariance matrix.}
  \item{tol.inv}{tolerance to be used for computing the inverse (if
    \code{inverted} is false), see \code{\link{solve}}.}
}
\description{
  Returns the Mahalanobis distance of all rows in \code{x} and the
  vector \eqn{\mu=}\code{center} with respect to
  \eqn{\Sigma=}\code{cov}.
  This is (for vector \code{x}) defined as
  \deqn{
    D^2 = (x - \mu)' \Sigma^{-1} (x - \mu)
  }
}
\author{Friedrich Leisch}
\seealso{\code{\link{cov}}, \code{\link{var}}}
\examples{
ma <- cbind(1:6, 1:3)
(S <-  var(ma))
mahalanobis(c(0,0), 1:2, S)

x <- matrix(rnorm(100*3), ncol = 3)
stopifnot(mahalanobis(x, 0, diag(ncol(x))) == rowSums(x*x))
	##- Here, D^2 = usual Euclidean distances
Sx <- cov(x)
D2 <- mahalanobis(x, rowMeans(x), Sx)
plot(density(D2, bw=.5), main="Mahalanobis distances, n=100, p=3"); rug(D2)
qqplot(qchisq(ppoints(100), df=3), D2,
       main = expression("Q-Q plot of Mahalanobis" * ~D^2 *
                         " vs. quantiles of" * ~ chi[3]^2))
abline(0, 1, col = 'gray')
}
\keyword{multivariate}
\eof
\name{make.link}
\alias{make.link}
\title{Create a Link for GLM families}
\usage{
make.link(link)
}
\arguments{
    \item{link}{character or numeric; one of \code{"logit"},
        \code{"probit"}, \code{"cloglog"}, \code{"identity"},
        \code{"log"},  \code{"sqrt"},  \code{"1/mu^2"},
        \code{"inverse"}, or number, say \eqn{\lambda}{lambda} resulting
        in power link \eqn{=\mu ^ \lambda}{mu ^ lambda}.}
}
%%-- implementation in ../R/family.R
\description{
    This function is used with the \code{\link{family}} functions in
    \code{\link{glm}()}.
    Given a link, it returns a link function, an inverse link
    function, the derivative \eqn{d\mu / d\eta}{dmu/deta} and a function
    for domain checking.
}
\value{
    A list with components
    \item{linkfun}{Link function \code{function(mu)}}
    \item{linkinv}{Inverse link function \code{function(eta)}}
    \item{mu.eta}{Derivative \code{function(eta)} \eqn{d\mu / d\eta}{dmu/deta}}
    \item{valideta}{\code{function(eta)}\{ \code{TRUE} if all of
        \code{eta} is in the domain of \code{linkinv} \}.}
}
\seealso{\code{\link{glm}}, \code{\link{family}}.}
\examples{
str(make.link("logit"))

l2 <- make.link(2)
l2$linkfun(0:3)# 0 1 4 9
l2$mu.eta(eta= 1:2)#= 1/(2*sqrt(eta))
}
\keyword{models}

\eof
\name{make.names}
\alias{make.names}
\title{Make Syntactically Valid Names}
\description{
  Make syntactically valid names out of character vectors.
}
\usage{
make.names(names, unique = FALSE)
}
\arguments{
 \item{names}{character vector to be coerced to syntactically valid
   names. This is coerced to character if necessary.}
 \item{unique}{logical; if \code{TRUE}, the resulting elements are
     unique.  This may be desired for, e.g., column names.}
}
\value{
  A character vector of same length as \code{names} with each changed to
  a syntactically valid name.
}
\details{
  A syntactically valid name consists of letters, numbers, and the dot
  character and starts with a letter or the dot.  Names such as
  \code{".2"} are not valid, and neither are the reserved words.

  The character \code{"X"} is prepended if necessary.
  All invalid characters are translated to \code{"."}.  A missing value
  is translated to \code{"NA"}.  Names which match \R keywords have a dot
  appended to them.  Duplicated values are altered by
  \code{\link{make.unique}}.
}
\seealso{
  \code{\link{make.unique}},
  \code{\link{names}},
  \code{\link{character}},
  \code{\link{data.frame}}.
}
\examples{
make.names(c("a and b", "a_and_b"), unique=TRUE)
# "a.and.b"  "a.and.b.1"

data(state)
state.name[make.names(state.name) != state.name] # those 10 with a space
}
\keyword{character}
\eof
\name{make.socket}
\alias{make.socket}
\alias{print.socket}
\title{Create a Socket Connection}
\usage{
make.socket(host = "localhost", port, fail = TRUE, server = FALSE)
}
\arguments{
  \item{host}{name of remote host}
  \item{port}{port to connect to/listen on}
  \item{fail}{failure to connect is an error?}
  \item{server}{a server socket?}
}
\description{
  With \code{server = FALSE} attempts to open a client socket to the
  specified port and host. With \code{server = TRUE} listens on the
  specified port for a connection and then returns a server socket. It is
  a good idea to use \code{\link{on.exit}} to ensure that a socket is
  closed, as you only get 64 of them.
}
\value{
  An object of class \code{"socket"}.
  \item{socket}{socket number. This is for internal use}
  \item{port}{port number of the connection}
  \item{host}{name of remote computer}
}
\author{Thomas Lumley}
\references{
  Adapted from Luke Tierney's code for \code{XLISP-Stat}, in turn
  based on code from Robbins and Robbins "Practical UNIX Programming"
}
\section{Warning}{
  I don't know if the connecting host name returned
  when \code{server = TRUE} can be trusted. I suspect not.
} 

\seealso{
  \code{\link{close.socket}}, \code{\link{read.socket}}
}

\examples{
daytime <- function(host = "localhost"){
    a <- make.socket(host, 13)
    on.exit(close.socket(a))
    read.socket(a)
}
## Offical time (UTC) from US Naval Observatory
\dontrun{daytime("tick.usno.navy.mil")}
}
\keyword{misc}
\eof
\name{make.tables}
\title{Create model.tables}
\alias{make.tables.aovproj}
\alias{make.tables.aovprojlist}
\usage{
make.tables.aovproj    (proj.cols, mf.cols, prjs, mf,
                        fun = "mean", prt = FALSE, \dots)

make.tables.aovprojlist(proj.cols, strata.cols, model.cols, projections,
                        model, eff, fun = "mean", prt = FALSE, \dots)  
}
\description{
 These are support functions for (the methods of)
 \code{\link{model.tables}} and probably not much of use otherwise.
}
%% \details{
%%              ___ SOURCE in ../R/model.tables.R ___
%% }
\seealso{\code{\link{model.tables}}}
\keyword{internal}
\eof
\name{make.unique}
\alias{make.unique}
\title{Make Character Strings Unique}
\description{
  Makes the elements of a character vector unique by
  appending sequence numbers to duplicates.
}
\usage{
make.unique(names, sep = ".")
}
\arguments{
  \item{names}{a character vector}
  \item{sep}{a character string used to separate a duplicate name from
    its sequence number.}
}
\value{
  A character vector of same length as \code{names} with duplicates changed.
}
\details{
  The algorithm used by \code{make.unique} has the property that
  \code{make.unique(c(A, B)) == make.unique(c(make.unique(A), B))}.

  In other words, you can append one string at a time to a vector,
  making it unique each time, and get the same result as applying
  \code{make.unique} to all of the strings at once.
    
  If character vector \code{A} is already unique, then
  \code{make.unique(c(A, B))} preserves \code{A}.
}
\author{Thomas P Minka}
\seealso{
  \code{\link{make.names}}
}
\examples{
make.unique(c("a", "a", "a"))
make.unique(c(make.unique(c("a", "a")), "a"))

make.unique(c("a", "a", "a.2", "a"))
make.unique(c(make.unique(c("a", "a")), "a.2", "a"))

rbind(data.frame(x=1), data.frame(x=2), data.frame(x=3))
rbind(rbind(data.frame(x=1), data.frame(x=2)), data.frame(x=3))
}
\keyword{character}
\eof
\name{makepredictcall}
\alias{makepredictcall}
\alias{makepredictcall.default}
\alias{SafePrediction}
\title{Utility Function for Safe Prediction}
\description{
  A utility to help \code{\link{model.frame.default}} create the right
  matrices when predicting from models with terms like \code{poly} or
  \code{ns}. 
}
\usage{
makepredictcall(var, call)
}
\arguments{
  \item{var}{A variable.}
  \item{call}{The term in the formula, as a call.}
}
\details{
  This is a generic function with methods for \code{poly}, \code{bs} and
  \code{ns}: the default method handles \code{scale}.  If
  \code{model.frame.default} encounters such a term when
  creating a model frame, it modifies the \code{predvars} attribute of
  the terms supplied to replace the term with one that will work for
  predicting new data.  For example \code{makepredictcall.ns} adds
  arguments for the knots and intercept.

  To make use of this, have your model-fitting function return the
  \code{terms} attribute of the model frame, or copy the \code{predvars}
  attribute of the \code{terms} attribute of the model frame to your
  \code{terms} object.

  To extend this, make sure the term creates variables with a class,
  and write a suitable method for that class.
}
\value{
  A replacement for \code{call} for the \code{predvars} attribute of
  the terms.
}
\seealso{
  \code{\link{model.frame}}, \code{\link{poly}}, \code{\link{scale}},
  \code{\link[splines]{bs}}, \code{\link[splines]{ns}}, \code{\link{cars}}
}
\examples{
## using poly: this did not work in R < 1.5.0
data(women)
fm <- lm(weight ~ poly(height, 2), data = women)
plot(women, xlab = "Height (in)", ylab = "Weight (lb)")
ht <- seq(57, 73, len = 200)
lines(ht, predict(fm, data.frame(height=ht)))

## see also example(cars)

## see bs and ns for spline examples.
}
\keyword{models}
\eof
\name{manglePackageName}
\alias{manglePackageName}
\title{Mangle the Package Name }
\description{
 This function takes the package name and the package version number and
 pastes them together with a separating underscore.
}
\usage{
manglePackageName(pkgName, pkgVersion)
}
\arguments{
  \item{pkgName}{The package name, as a character string. }
  \item{pkgVersion}{The package version, as a character string. }
}
\value{
  A character string with the two inputs pasted together.
}

\examples{
  manglePackageName("foo", "1.2.3")
}
\keyword{utilities }
\eof
\name{manova}
\alias{manova}
\title{Multivariate Analysis of Variance}
\description{
  A class for the multivariate analysis of variance.
}
\usage{
manova(\dots)
}
\arguments{
  \item{\dots}{Arguments to be passed to \code{\link{aov}}.}
}
\details{
  Class \code{"manova"} differs from class \code{"aov"} in selecting a
  different \code{summary} method.  Function \code{manova} calls
  \code{\link{aov}} and then add class \code{"manova"} to the result
  object for each stratum.
}
\value{
  See \code{\link{aov}} and the comments in Details here.
}
\note{
  \code{manova} does not support multistratum analysis of variance, so
  the formula should not include an \code{Error} term.
}
\references{
  Krzanowski, W. J. (1988) \emph{Principles of Multivariate Analysis. A
    User's Perspective.} Oxford.

  Hand, D. J. and Taylor, C. C.  (1987)
  \emph{Multivariate Analysis of Variance and Repeated Measures.}
  Chapman and Hall.
}

\seealso{
  \code{\link{aov}}, \code{\link{summary.manova}}, the latter containing
  examples.
}
\keyword{models}
\eof
\name{mapply}
\alias{mapply}
\title{Apply a function to multiple list or vector arguments }
\description{
  A multivariate version of \code{\link{sapply}}.
  \code{mapply} applies \code{FUN} to the first elements of each \dots
  argument, the second elements, the third elements, and so on.
  Arguments are recycled if necessary. 
}
\usage{
mapply(FUN, \dots, MoreArgs = NULL, SIMPLIFY = TRUE, USE.NAMES = TRUE)
}
\arguments{
  \item{FUN}{Function to apply }
  \item{\dots}{Arguments to vectorise over (list or vector) }
  \item{MoreArgs}{A list of other arguments to \code{FUN} }
  \item{SIMPLIFY}{Attempt to reduce the result to a vector or matrix? }
  \item{USE.NAMES}{If the first \dots argument is character and the
    result doesn't already have names, use it as the names}
}
\value{
  A list, vector, or matrix.
}

\seealso{\code{\link{sapply}}}, \code{\link{outer}} }
\examples{
 mapply(rep, 1:4, 4:1)

 mapply(rep, times=1:4, x=4:1)

 mapply(rep, times=1:4, MoreArgs=list(x=42))

}
\keyword{manip }
\keyword{utilities}
\eof
\name{margin.table}
\alias{margin.table}
\title{Compute table margin}
\description{
  For a contingency table in array form, compute the sum of table
  entries for a given index.
}
\usage{
margin.table(x, margin=NULL)
}
\arguments{
  \item{x}{an array}
  \item{margin}{index number (1 for rows, etc.) }
}
\details{
  This is really just \code{apply(x, margin, sum)} packaged up for
  newbies, except that if \code{margin} has length zero you get
  \code{sum(x)}.
}
\value{
  The relevant marginal table.  The class of \code{x} is copied to the
  output table, except in the summation case.
}
\author{Peter Dalgaard}
\examples{
m<-matrix(1:4,2)
margin.table(m,1)
margin.table(m,2)
}
\keyword{array}
\eof
\name{mat.or.vec}
\alias{mat.or.vec}
\title{Create a Matrix or a Vector}
\usage{
mat.or.vec(nr, nc)
}
\arguments{
  \item{nr, nc}{numbers of rows and columns.}
}
\description{
  \code{mat.or.vec} creates an \code{nr} by \code{nc} zero matrix if
  \code{nc} is greater than 1, and a zero vector of length \code{nr} if
  \code{nc} equals 1.
}
\examples{
mat.or.vec(3, 1)
mat.or.vec(3, 2)
}
\keyword{array}
\eof
\name{match}
\alias{match}
\alias{\%in\%}
\title{Value Matching}
\description{
  \code{match} returns a vector of the positions of (first) matches of
  its first argument in its second.

  \code{\%in\%} is a more intuitive interface as a binary operator,
  which returns a logical vector indicating if there is a match or not
  for its left operand.
}
\usage{
match(x, table, nomatch = NA, incomparables = FALSE)

x \%in\% table
}
\arguments{
  \item{x}{the values to be matched.}
  \item{table}{the values to be matched against.}
  \item{nomatch}{the value to be returned in the case when no match is
    found.  Note that it is coerced to \code{integer}.}
  \item{incomparables}{a vector of values that cannot be matched.  Any
    value in \code{x} matching a value in this vector is assigned the
    \code{nomatch} value.  Currently, \code{FALSE} is the only possible
    value, meaning that all values can be matched.}
}
\value{
  In both cases, a vector of the same length as \code{x}.

  \code{match}: An integer vector giving the position in \code{table} of
  the first match if there is a match, otherwise \code{nomatch}.

  If \code{x[i]} is found to equal \code{table[j]}
  then the value returned in the \code{i}-th position of the return value is
  \code{j}, for the smallest possible \code{j}.  If no match is found,
  the value is \code{nomatch}.

  \code{\%in\%}: A logical vector, indicating if a match was located for
  each element of \code{x}.
}
\details{
  \code{\%in\%} is currently defined as \cr
  \code{"\%in\%" <- function(x, table) match(x, table, nomatch = 0) > 0}

  Factors are converted to character vectors, and then \code{x} and
  \code{table} are coerced to a common type (the later of the two types
  in R's ordering, logical < integer < numeric < complex < character)
  before matching.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{pmatch}} and \code{\link{charmatch}} for (\emph{partial})
  string matching, \code{\link{match.arg}}, etc for function argument
  matching.

  \code{\link{is.element}} for an S-compatible equivalent of \code{\%in\%}.
}
\examples{
## The intersection of two sets :
intersect <- function(x, y) y[match(x, y, nomatch = 0)]
intersect(1:10,7:20)

1:10 \%in\% c(1,3,5,9)
sstr <- c("c","ab","B","bba","c","@","bla","a","Ba","\%")
sstr[sstr \%in\% c(letters,LETTERS)]

"\%w/o\%" <- function(x,y) x[!x \%in\% y] #--  x without y
(1:10) \%w/o\% c(3,7,12)
}
\keyword{manip}
\keyword{logic}
\eof
\name{match.arg}
\title{Argument Verification Using Partial Matching}
\usage{
match.arg(arg, choices)
}
\alias{match.arg}
\arguments{
  \item{arg}{a character string}
  \item{choices}{a character vector of candidate values}
}
\description{
  \code{match.arg} matches \code{arg} against a table of candidate
  values as specified by \code{choices}.
}
\details{
  In the one-argument form \code{match.arg(arg)}, the choices are
  obtained from a default setting for the formal argument \code{arg} of
  the function from which \code{match.arg} was called.

  Matching is done using \code{\link{pmatch}}, so \code{arg} may be
  abbreviated.
}
\value{
  The unabbreviated version of the unique partial match if there is one;
  otherwise, an error is signalled.
}
\seealso{
  \code{\link{pmatch}},
  \code{\link{match.fun}},
  \code{\link{match.call}}.
}
\examples{
## Extends the example for 'switch'
center <- function(x, type = c("mean", "median", "trimmed")) {
  type <- match.arg(type)
  switch(type,
         mean = mean(x),
         median = median(x),
         trimmed = mean(x, trim = .1))
}
x <- rcauchy(10)
center(x, "t")       # Works
center(x, "med")     # Works
\dontrun{center(x, "m")       # Error
}
}
\keyword{programming}
\eof
\name{match.call}
\title{Argument Matching}
\usage{
match.call(definition = NULL, call = sys.call(sys.parent()),
           expand.dots = TRUE)
}
\alias{match.call}
\arguments{
  \item{definition}{a function, by default the function from which
    \code{match.call} is called.}
  \item{call}{an unevaluated call to the function specified by
    \code{definition}, as generated by \code{\link{call}}.}
  \item{expand.dots}{logical. Should arguments matching \code{\dots}
    in the call be included or left as a \code{\dots} argument?}
}
\description{
  \code{match.call} returns a call in which all of the arguments are
  specified by their names.  The most common use is to get the call of
  the current function, with all arguments named.
}
\value{
  An object of class \code{call}.
}
\references{
  Chambers, J. M. (1998)
  \emph{Programming with Data. A Guide to the S Language}.
  Springer.
}
\seealso{
  \code{\link{call}}, \code{\link{pmatch}}, \code{\link{match.arg}},
  \code{\link{match.fun}}.
}
\examples{
match.call(get, call("get", "abc", i = FALSE, p = 3))
## -> get(x = "abc", pos = 3, inherits = FALSE)
fun <- function(x, lower = 0, upper = 1) {
  structure((x - lower) / (upper - lower), CALL = match.call())
}
fun(4 * atan(1), u = pi)
}
\keyword{programming}
\eof
\name{match.fun}
\alias{match.fun}
\title{Function Verification for ``Function Variables''}
\description{
  When called inside functions that take a function as argument, extract
  the desired function object while avoiding undesired matching to
  objects of other types.
}
\usage{
match.fun(FUN, descend = TRUE)
}
\arguments{
 \item{FUN}{item to match as function.}
 \item{descend}{logical; control whether to search past non-function
     objects.}
}
\value{
  A function matching \code{FUN} or an error is generated.
}
\details{
  \code{match.fun} is not intended to be used at the top level since it
  will perform matching in the \emph{parent} of the caller.

  If \code{FUN} is a function, it is returned.  If it is a symbol or a
  character vector of length one, it will be looked up using \code{get}
  in the environment of the parent of the caller.  If it is of any other
  mode, it is attempted first to get the argument to the caller as a
  symbol (using \code{substitute} twice), and if that fails, an error is
  declared.

  If \code{descend = TRUE}, \code{match.fun} will look past non-function
  objects with the given name; otherwise if \code{FUN} points to a
  non-function object then an error is generated.

  This is now used in base functions such as \code{\link{apply}},
  \code{\link{lapply}}, \code{\link{outer}}, and \code{\link{sweep}}.
}
\author{
  Peter Dalgaard and Robert Gentleman, based on an earlier version
  by Jonathan Rougier.
}
\section{Bugs}{
  The \code{descend} argument is a bit of misnomer and probably not
  actually needed by anything.  It may go away in the future.

  It is impossible to fully foolproof this.  If one \code{attach}es a
  list or data frame containing a character object with the same name
  of a system function, it will be used.
}
\seealso{
  \code{\link{match.arg}}, \code{\link{get}}
}
\examples{
# Same as get("*"):
match.fun("*")
# Overwrite outer with a vector
outer <- 1:5
\dontrun{
match.fun(outer, descend = FALSE) #-> Error:  not a function
}
match.fun(outer) # finds it anyway
is.function(match.fun("outer")) # as well
}
\keyword{programming}
\eof
\name{matmult}
\alias{\%*\%}
\alias{matmult}
\title{Matrix Multiplication}
\description{
  Multiplies two matrices, if they are conformable.
  If one argument is a vector, it will be coerced to a either a row or column
  matrix to make the two arguments conformable.
  If both are vectors it will return the inner product.
}
\usage{
a \%*\% b
}
\arguments{
  \item{a, b}{numeric or complex matrices or vectors.}
}
\value{
  The matrix product.  Use \code{\link{drop}} to get rid of dimensions
  which have only one level.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{matrix}},
  \code{\link{Arithmetic}},
  \code{\link{diag}}.
}
\examples{
x <- 1:4
(z <- x \%*\% x)    # scalar ("inner") product (1 x 1 matrix)
drop(z)             # as scalar

y <- diag(x)
z <- matrix(1:12, ncol = 3, nrow = 4)
y \%*\% z
y \%*\% x
x \%*\% z
}
\keyword{array}
\keyword{arith}
\eof
\name{matplot}
\alias{matplot}
\alias{matpoints}
\alias{matlines}
\title{Plot Columns of Matrices}
\usage{
matplot(x, y, type = "p", lty = 1:5, lwd = 1, pch = NULL, col = 1:6,
        cex = NULL, xlab = NULL, ylab = NULL, xlim = NULL, ylim = NULL,
        \dots, add = FALSE, verbose = getOption("verbose"))
matpoints(x, y, type = "p", lty = 1:5, lwd = 1, pch = NULL, col = 1:6, \dots)
matlines (x, y, type = "l", lty = 1:5, lwd = 1, pch = NULL, col = 1:6, \dots)
}
\arguments{
  \item{x,y}{vectors or matrices of data for plotting.  The number of
    rows should match.  If one of them are missing, the other is taken
    as \code{y} and an \code{x} vector of \code{1:n} is used.
    Missing values (\code{NA}s) are allowed.}
  \item{type}{character string (length 1 vector) or vector of 1-character
    strings indicating the type of plot for each
    column of \code{y}, see \code{\link{plot}} for all possible
    \code{type}s.  The first character of \code{type}
    defines the first plot, the second character the second, etc.
    Characters in \code{type} are cycled through; e.g., \code{"pl"}
    alternately plots points and lines.}
  \item{lty,lwd}{vector of line types and widths.
    The first element is for the first column, the second element for
    the second column, etc., even if lines are not plotted for all
    columns. Line types will be used cyclically until all plots are
    drawn.}
  \item{pch}{character string or vector of 1-characters or integers for
    plotting characters, see \code{\link{points}}.
    The first character is the plotting-character for the first plot,
    the second for the second, etc.  The default is the digits (1
    through 9, 0) then the letters.
%%__FIXME__ Which of the following is still true; what's the "right" UI ?
%  To mix special plotting symbols (those specified by integers) and
%  plotting characters, either use character escapes \code{pch="Xe002"}
%  or figure out the numeric equivalent of the ASCII character,
%  \code{pch=c(88,2)}.
  }
  \item{col}{vector of colors.  Colors are used cyclically.}
  \item{cex}{vector of character expansion sizes, used cyclically.}
  \item{xlab, ylab}{titles for x and y axes, as in \code{\link{plot}}.}
  \item{xlim, ylim}{ranges of x and y axes, as in \code{\link{plot}}.}
  \item{\dots}{Graphical parameters (see \code{\link{par}}) and any further
    arguments of \code{plot}, typically \code{\link{plot.default}}, may also be
    supplied as arguments to this function.  Hence, the high-level
    graphics control arguments described under \code{\link{par}} and the
    arguments to \code{\link{title}} may be supplied to this function.}
  \item{add}{logical.  If \code{TRUE}, plots are added to current one,
    using \code{\link{points}} and \code{\link{lines}}.}
  \item{verbose}{logical.  If \code{TRUE}, write one line of what is
    done.}
}
\section{Side Effects}{Function \code{matplot} generates a new plot;
  \code{matpoints} and \code{matlines} add to the current one.}
\description{
  Plot the columns of one matrix against the columns of another.
}
\details{
  Points involving missing values are not plotted.

  The first column of \code{x} is plotted against the first column of
  \code{y}, the second column of \code{x} against the second column of
  \code{y}, etc.  If one matrix has fewer columns, plotting will cycle
  back through the columns again.  (In particular, either \code{x} or
  \code{y} may be a vector, against which all columns of the other
  argument will be plotted.)

  The first element of \code{col, cex, lty, lwd} is used to plot the axes
  as well as the first line.

  Because plotting symbols are drawn with lines and because these
  functions may be changing the line style, you should probably specify
  \code{lty=1} when using plotting symbols.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{plot}}, \code{\link{points}}, \code{\link{lines}},
  \code{\link{matrix}}, \code{\link{par}}.
}
\examples{
matplot((-4:5)^2, main = "Quadratic") # almost identical to plot(*)
sines <- outer(1:20, 1:4, function(x, y) sin(x / 20 * pi * y))
matplot(sines, pch = 1:4, type = "o", col = rainbow(ncol(sines)))

x <- 0:50/50
matplot(x, outer(x, 1:8, function(x, k) sin(k*pi * x)),
        ylim = c(-2,2), type = "plobcsSh",
        main= "matplot(,type = \"plobcsSh\" )")
## pch & type =  vector of 1-chars :
matplot(x, outer(x, 1:4, function(x, k) sin(k*pi * x)),
        pch = letters[1:4], type = c("b","p","o"))

data(iris)                  # is data.frame with 'Species' factor
table(iris$Species)
iS <- iris$Species == "setosa"
iV <- iris$Species == "versicolor"
op <- par(bg = "bisque")
matplot(c(1, 8), c(0, 4.5), type= "n", xlab = "Length", ylab = "Width",
        main = "Petal and Sepal Dimensions in Iris Blossoms")
matpoints(iris[iS,c(1,3)], iris[iS,c(2,4)], pch = "sS", col = c(2,4))
matpoints(iris[iV,c(1,3)], iris[iV,c(2,4)], pch = "vV", col = c(2,4))
legend(1, 4, c("    Setosa Petals", "    Setosa Sepals",
               "Versicolor Petals", "Versicolor Sepals"),
       pch = "sSvV", col = rep(c(2,4), 2))

nam.var <- colnames(iris)[-5]
nam.spec <- as.character(iris[1+50*0:2, "Species"])
iris.S <- array(NA, dim = c(50,4,3), dimnames = list(NULL, nam.var, nam.spec))
for(i in 1:3) iris.S[,,i] <- data.matrix(iris[1:50+50*(i-1), -5])

matplot(iris.S[,"Petal.Length",], iris.S[,"Petal.Width",], pch="SCV",
        col = rainbow(3, start = .8, end = .1),
        sub = paste(c("S", "C", "V"), dimnames(iris.S)[[3]],
                    sep = "=", collapse= ",  "),
        main = "Fisher's Iris Data")
}
par(op)
\keyword{hplot}
\keyword{aplot}
\keyword{array}
\eof
\name{matrix}
\alias{matrix}
\alias{as.matrix}
\alias{as.matrix.default}
\alias{as.matrix.data.frame}
\alias{is.matrix}
\title{Matrices}
\description{
  \code{matrix} creates a matrix from the given set of values.

  \code{as.matrix} attempts to turn its argument into a matrix.

  \code{is.matrix} tests if its argument is a (strict) matrix.
  It is generic: you can write methods to handle
  of specific classes of objects, see \link{InternalMethods}.
}
\usage{
matrix(data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL)
as.matrix(x)
is.matrix(x)
}
\arguments{
  \item{data}{an optional data vector.}
  \item{nrow}{the desired number of rows}
  \item{ncol}{the desired number of columns}
  \item{byrow}{logical. If \code{FALSE}
    (the default) the matrix is filled by columns, otherwise the matrix is
    filled by rows.}
  \item{dimnames}{A \code{\link{dimnames}} attribute for the matrix: a
    \code{list} of length 2.}
  \item{x}{an \R object.}
}
\details{
  If either of \code{nrow} or \code{ncol} is not given, an attempt is
  made to infer it from the length of \code{data} and the other
  parameter.

  \code{is.matrix} returns \code{TRUE} if \code{x} is a matrix (i.e., it
  is \emph{not} a \code{\link{data.frame}} and has a \code{\link{dim}}
  attribute of length 2) and \code{FALSE} otherwise.

  \code{as.matrix} is a generic function. The method for data frames
  will convert any non-numeric column into a character vector using
  \code{\link{format}} and so return a character matrix. 
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{data.matrix}}, which attempts to convert to a numeric matrix.
}
\examples{
is.matrix(as.matrix(1:10))
data(warpbreaks)
!is.matrix(warpbreaks)# data.frame, NOT matrix!
str(warpbreaks)
str(as.matrix(warpbreaks))#using as.matrix.data.frame(.) method
}
\keyword{array}
\keyword{algebra}
\eof
\name{maxCol}
\alias{max.col}
\title{Find Maximum Position in Matrix}
\description{
  Find the maximum position for each row of a matrix, breaking ties at random.
}
\usage{
max.col(m)
}
\arguments{
  \item{m}{numerical matrix}
}
\value{index of a maximal value for each row, an integer vector of
  length \code{nrow(m)}.
}
\details{
  Ties are broken at random.  The determination of \dQuote{tie} assumes that
  the entries are probabilities: there is a relative tolerance of
  \eqn{10^{-5}}{1e-5}, relative to the largest entry in the row.
}
\references{
  Venables, W. N. and Ripley, B. D. (2002)
  \emph{Modern Applied Statistics with S.}
  New York: Springer (4th ed).
}
\seealso{\code{\link{which.max}} for vectors.}
\examples{
data(swiss)
table(mc <- max.col(swiss))# mostly "1" and "5", 5 x "2" and once "4"
swiss[unique(print(mr <- max.col(t(swiss)))) , ] # 3 33 45 45 33 6
}
\keyword{utilities}
\keyword{array}
\eof
\name{mean}
\title{Arithmetic Mean}
\usage{
mean(x, \dots)

\method{mean}{default}(x, trim = 0, na.rm = FALSE, \dots)
}
\alias{mean}
\alias{mean.default}
\alias{mean.data.frame}
\arguments{
  \item{x}{An \R object.  Currently there are methods for numeric data
    frames, numeric vectors and dates.  A complex vector is allowed for
    \code{trim = 0}, only.}
  \item{trim}{the fraction (0 to 0.5) of observations to be
    trimmed from each end of \code{x} before the mean is computed.}
  \item{na.rm}{a logical value indicating whether \code{NA}
    values should be stripped before the computation proceeds.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\description{
  Generic function for the (trimmed) arithmetic mean.
}
\value{
  For a data frame, a named vector with the appropriate method being
  applied column by column.
  
  If \code{trim} is zero (the default),
  the arithmetic mean of the values in \code{x} is computed.

  If \code{trim} is non-zero, a symmetrically trimmed mean is computed
  with a fraction of \code{trim} observations deleted from each end
  before the mean is computed.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{weighted.mean}}, \code{\link{mean.POSIXct}}
}
\examples{
x <- c(0:10, 50)
xm <- mean(x)
c(xm, mean(x, trim = 0.10))

data(USArrests)
mean(USArrests, trim = 0.2)
}
\keyword{univar}

\eof
\name{median}
\title{Median Value}
\usage{
median(x, na.rm=FALSE)
}
\alias{median}
\arguments{
  \item{x}{a numeric vector containing the values
    whose median is to be computed.}
  \item{na.rm}{a logical value indicating whether \code{NA}
    values should be stripped before the computation proceeds.}
  }
\description{
  Compute the sample median of the vector of values given as its argument.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{\code{\link{quantile}} for general quantiles.}
\examples{
median(1:4)# = 2.5 [even number]
median(c(1:3,100,1000))# = 3 [odd, robust]
}
\keyword{univar}
\keyword{robust}
\eof
\name{memory.profile}
\alias{memory.profile}
\title{Profile the Usage of Cons Cells}
\description{
    Lists the usage of the cons cells by \code{SEXPREC} type.
}
\usage{
memory.profile()
}
\details{
    The current types and their uses are listed in the include file
    \file{Rinternals.h}. There will be blanks in the list corresponding
    to types that are no longer in use (types 11 and 12 at the time of
    writing). Also \code{FUNSXP} is not included.
}
\value{
  A vector of counts, named by the types.
}

\seealso{\code{\link{gc}} for the overall usage of cons cells.}

\examples{
memory.profile()
}
\keyword{utilities}
\eof
\name{menu}
\alias{menu}
\title{Menu Interaction Function}
\description{
  \code{menu} presents the user with a menu of choices labelled from 1
  to the number of choices.  To exit without choosing an item one can
  select \samp{0}.
}
\usage{
menu(choices, graphics = FALSE, title = "")
}
\arguments{
  \item{choices}{a character vector of choices}
  \item{graphics}{a logical indicating whether a graphics menu should be
    used.  Currently unused.}
  \item{title}{a character string to be used as the title of the menu}
}
\value{
  The number corresponding to the selected item, or 0 if no choice was
  made.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
\dontrun{
switch(menu(c("List letters", "List LETTERS")) + 1,
       cat("Nothing done\n"), letters, LETTERS)
}
}
\keyword{utilities}
\keyword{programming}
\eof
\name{merge}
\alias{merge}
\alias{merge.default}
\alias{merge.data.frame}
\title{Merge Two Data Frames}
\description{
  Merge two data frames by common columns or row names, or do other
  versions of database \dQuote{join} operations.
}
\usage{
merge(x, y, \dots)

\method{merge}{default}(x, y, \dots)

\method{merge}{data.frame}(x, y, by = intersect(names(x), names(y)),
      by.x = by, by.y = by, all = FALSE, all.x = all, all.y = all,
      sort = TRUE, suffixes = c(".x",".y"), \dots)
}
\arguments{
  \item{x, y}{data frames, or objects to be coerced to one}
  \item{by, by.x, by.y}{specifications of the common columns. See Details.}
  \item{all}{logical; \code{all=L} is shorthand for \code{all.x=L} and
    \code{all.y=L}.}
  \item{all.x}{logical; if \code{TRUE}, then extra rows will be added to
    the output, one for each row in \code{x} that has no matching row in
    \code{y}.  These rows will have \code{NA}s in those columns that are
    usually filled with values from \code{y}.  The default is
    \code{FALSE}, so that only rows with data from both \code{x} and
    \code{y} are included in the output.}
  \item{all.y}{logical; analogous to \code{all.x} above.}
  \item{sort}{logical.  Should the results be sorted on the \code{by}
    columns?}
  \item{suffixes}{character(2) specifying the suffixes to be used for
    making non-\code{by} \code{names()} unique.}
  \item{\dots}{arguments to be passed to or from methods.}
}
\details{
  By default the data frames are merged on the columns with names they
  both have, but separate specifications of the columns can be given by
  \code{by.x} and \code{by.y}.  Columns can be specified by name, number
  or by a logical vector: the name \code{"row.names"} or the number
  \code{0} specifies the row names.  The rows in the two data frames
  that match on the specified columns are extracted, and joined
  together.  If there is more than one match, all possible matches
  contribute one row each.\cr
  If the \code{by.*} vector are of length 0, the result, \code{r}, is the
  \dQuote{Cartesian product} of \code{x} and \code{y}, i.e.,
  \code{dim(r) = c(nrow(x)*nrow, ncol(x) + ncol(y))}.

  If \code{all.x} is true, all the non matching cases of \code{x} are
  appended to the result as well, with \code{NA} filled in the
  corresponding columns of \code{y};  analogously for \code{all.y}.

  If the remaining columns in the data frames have any common names,
  these have \code{suffixes} (\code{".x"} and \code{".y"} by default)
  appended to make the names of the result unique.
}
\value{
  A data frame.  The rows are by default lexicographically sorted on the
  common columns, but are otherwise in the order in which they occurred
  in \code{y}.  The columns are the common columns followed by the
  remaining columns in \code{x} and then those in \code{y}.  If the
  matching involved row names, an extra column \code{Row.names} is added
  at the left, and in all cases the result has no special row names.
}
\seealso{
  \code{\link{data.frame}},
  \code{\link{by}},
  \code{\link{cbind}}
}

\examples{
authors <- data.frame(
    surname = c("Tukey", "Venables", "Tierney", "Ripley", "McNeil"),
    nationality = c("US", "Australia", "US", "UK", "Australia"),
    deceased = c("yes", rep("no", 4)))
books <- data.frame(
    name = c("Tukey", "Venables", "Tierney",
             "Ripley", "Ripley", "McNeil", "R Core"),
    title = c("Exploratory Data Analysis",
              "Modern Applied Statistics ...",
              "LISP-STAT",
              "Spatial Statistics", "Stochastic Simulation",
              "Interactive Data Analysis",
              "An Introduction to R"),
    other.author = c(NA, "Ripley", NA, NA, NA, NA,
                     "Venables & Smith"))

(m1 <- merge(authors, books, by.x = "surname", by.y = "name"))
(m2 <- merge(books, authors, by.x = "name", by.y = "surname"))
stopifnot(as.character(m1[,1]) == as.character(m2[,1]),
          all.equal(m1[, -1], m2[, -1][ names(m1)[-1] ]),
          dim(merge(m1, m2, by = integer(0))) == c(36, 10))

## "R core" is missing from authors and appears only here :
merge(authors, books, by.x = "surname", by.y = "name", all = TRUE)
}
\keyword{array}
\keyword{manip}
\eof
\name{methods}
\title{List Methods for S3 Generic Functions or Classes}
\alias{methods}
\alias{print.MethodsFunction}
\description{
  List all available methods for an S3 generic function, or all
  methods for a class.
}
\usage{
methods(generic.function, class)
}
\arguments{
  \item{generic.function}{a generic function, or a character string naming a
    generic function.}
  \item{class}{a symbol or character string naming a class: only used if
    \code{generic.function} is not supplied.}
}
\value{
  An object of class \code{"MethodsFunction"}, a
  character vector of function names with an \code{"info"} attribute.
  There is a \code{print} method which marks with an asterisk any
  methods which are not visible: such functions can be examined by
  \code{\link{getS3method}} or \code{\link{getAnywhere}}.

  The \code{"info"} attribute is a data frame, currently with a
  logical column, \code{visible} and a factor column \code{from}
  (indicating where the methods were found).
}
\details{
  Function \code{methods} can be used to find out about the methods for
  a particular generic function or class.  The functions listed are those
  which \emph{are named like methods} and may not actually be methods
  (known exceptions are discarded in the code).  Note that the listed
  methods may not be user-visible objects, but often help will be
  available for them.

  If \code{class} is used, we check that a matching generic can be found
  for each user-visible object named.
}
\note{
  This scheme is called \emph{S3} (S version 3).  For new projects,
  it is recommended to use the more flexible and robust \emph{S4} scheme
  provided in the \pkg{methods} package.  Functions can have both S3
  and S4 methods, and function \code{\link[methods]{showMethods}} will
  list the S4 methods (possibly none).

  The original \code{methods} function was written by Martin Maechler.
}
\seealso{
  \code{\link{S3Methods}}, \code{\link[base]{class}}, \code{\link{getS3method}}
}
\references{
  Chambers, J. M. (1992)
  \emph{Classes and methods: object-oriented programming in S.}
  Appendix A of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\examples{
methods(summary)
methods(class = "aov")
methods("[[")    ##- does not list the C-internal ones...
methods("$")     # currently none
methods("$<-")   # replacement function
methods("+")     # binary operator
methods("Math")  # group generic
\dontrun{methods(print)
}}
\keyword{methods}
\eof
\name{missing}
\alias{missing}
\title{Does a Formal Argument have a Value?}
\usage{
missing(x)
}
\description{
\code{missing} can be used to test whether a value was specified
as an argument to a function.
}
\arguments{
  \item{x}{a formal argument.}
}
\details{
  \code{missing(x)} is only reliable if \code{x} has not been altered
  since entering the function: in particular it will \emph{always}
  be false after \code{x <- match.arg(x)}. 
  
  The example shows how a plotting function
  can be written to work with either a pair of vectors
  giving x and y coordinates of points to be plotted
  or a single vector giving y values to be plotted
  against their indexes.

  Currently \code{missing} can only be used in the immediate body of
  the function that defines the argument, not in the body of a nested
  function or a \code{local} call.  This may change in the future.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Chambers, J. M. (1998)
  \emph{Programming with Data. A Guide to the S Language}.
  Springer.
}
\seealso{
  \code{\link{substitute}} for argument expression;
  \code{\link{NA}} for \dQuote{missing values} in data.
}
\examples{
myplot <- function(x,y) {
                if(missing(y)) {
                        y <- x
                        x <- 1:length(y)
                }
                plot(x,y)
        }
}
\keyword{programming}
\eof
\name{mode}
\alias{mode}
\alias{mode<-}
\alias{storage.mode}
\alias{storage.mode<-}
\title{The (Storage) Mode of an Object}
\description{
  Get or set the type or storage mode of an object.
}
\usage{
mode(x)
mode(x) <- value
storage.mode(x)
storage.mode(x) <- value
}
\arguments{
  \item{x}{any \R object.}
  \item{value}{a character string giving the desired (storage) mode of
    the object.}
}
\details{
  Both \code{mode} and \code{storage.mode} return a character string
  giving the (storage) mode of the object --- often the same --- both
  relying on the output of \code{\link{typeof}(x)}, see the example
  below.

  The two assignment versions are currently identical.  Both
  \code{mode(x) <- newmode} and \code{storage.mode(x) <- newmode} change
  the \code{mode} or \code{storage.mode} of object \code{x} to
  \code{newmode}.

  As storage mode \code{"single"} is only a pseudo-mode in \R, it will
  not be reported by \code{mode} or \code{storage.mode}: use
  \code{attr(object, "Csingle")} to examine this. However, the
  assignment versions can be used to set the mode to \code{"single"},
  which sets the real mode to \code{"double"} and the \code{"Csingle"}
  attribute to \code{TRUE}. Setting any other mode will remove this
  attribute.

  Note (in the examples below) that some \code{\link{call}}s have mode
  \code{"("} which is S compatible.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{typeof}} for the R-internal \dQuote{mode},
  \code{\link{attributes}}.
}
\examples{
sapply(options(),mode)

cex3 <- c("NULL","1","1:1","1i","list(1)","data.frame(x=1)", "pairlist(pi)",
  "c", "lm", "formals(lm)[[1]]",  "formals(lm)[[2]]",
  "y~x","expression((1))[[1]]", "(y~x)[[1]]", "expression(x <- pi)[[1]][[1]]")
lex3 <- sapply(cex3, function(x) eval(parse(text=x)))
mex3 <- t(sapply(lex3, function(x) c(typeof(x), storage.mode(x), mode(x))))
dimnames(mex3) <- list(cex3, c("typeof(.)","storage.mode(.)","mode(.)"))
mex3

## This also makes a local copy of 'pi':
storage.mode(pi) <- "complex"
storage.mode(pi)
rm(pi)
}
\keyword{attribute}
\eof
\name{model.extract}
\title{Extract Components from a Model Frame}
\usage{
model.extract(frame, component)
model.offset(x)
model.response(data, type = "any")
model.weights(x)
}
\alias{model.extract}
\alias{model.offset}
\alias{model.response}
\alias{model.weights}
\arguments{
 \item{frame, x, data}{A model frame.}
 \item{component}{literal character string or name. The name of a
   component to extract, such as \code{"weights"}, \code{"subset"}.}
 \item{type}{One of \code{"any"}, \code{"numeric"}, \code{"double"}.
   Using the either of latter two coerces the result to have
   storage mode \code{"double"}.}
}
\description{Returns the response, offset, subset, weights or other
  special components of a model frame passed as optional arguments to
  \code{\link{model.frame}}.
}
\details{
  \code{model.extract} is provided for compatibility with S, which does
  not have the more specific functions.

  \code{model.offset} and
  \code{model.response} are equivalent to \code{model.frame(, "offset")}
  and \code{model.frame(, "response")} respectively.

  \code{model.weights} is slightly different from
  \code{model.frame(, "weights")} in not naming the vector it returns.
}
\value{The specified component of the model frame, usually a vector.}

\seealso{\code{\link{model.frame}}, \code{\link{offset}}}

\examples{
data(esoph)
a <- model.frame(cbind(ncases,ncontrols) ~ agegp+tobgp+alcgp, data=esoph)
model.extract(a, "response")
stopifnot(model.extract(a, "response") == model.response(a))

a <- model.frame(ncases/(ncases+ncontrols) ~ agegp+tobgp+alcgp,
                 data = esoph, weights = ncases+ncontrols)
model.response(a)
model.extract(a, "weights")

a <- model.frame(cbind(ncases,ncontrols) ~ agegp,
                 something = tobgp, data = esoph)
names(a)
stopifnot(model.extract(a, "something") == esoph$tobgp)
}
\keyword{manip}
\keyword{programming}
\keyword{models}
\eof
\name{model.frame}
\alias{model.frame}
\alias{model.frame.default}
\alias{model.frame.lm}
\alias{model.frame.glm}
\alias{model.frame.aovlist}
\title{Extracting the ``Environment'' of a Model Formula}
\usage{
model.frame(formula, \dots)

\method{model.frame}{default}(formula, data = NULL,
           subset = NULL, na.action = na.fail,
           drop.unused.levels = FALSE, xlev = NULL, \dots)

\method{model.frame}{aovlist}(formula, data = NULL, \dots)

\method{model.frame}{glm}(formula, data, na.action, \dots)

\method{model.frame}{lm}(formula, data, na.action, \dots)
}
\arguments{
  \item{formula}{a model formula}

  \item{data}{\code{data.frame}, list, \code{environment} or object
    coercible to \code{data.frame} containing the variables in
    \code{formula}.}

  \item{subset}{a specification of the rows to be used: defaults to all
    rows. This can be any valid indexing vector (see
    \code{\link{[.data.frame}} for the rows of \code{data} or if that is not
    supplied, a data frame made up of the variables used in \code{formula}.}

  \item{na.action}{how \code{NA}s are treated. The default is first,
    any \code{na.action} attribute of \code{data}, second
    a \code{na.action} setting of \code{\link{options}}, and third
    \code{\link{na.fail}} if that is unset.  The \dQuote{factory-fresh}
    default is \code{\link{na.omit}}.}

  \item{drop.unused.levels}{should factors have unused levels dropped?
    Defaults to \code{FALSE}.}

  \item{xlev}{a named list of character vectors giving the full set of levels
    to be assumed for each factor.}

  \item{\dots}{further arguments such as \code{subset}, \code{offset} and
    \code{weights}. \code{NULL} arguments are treated as missing.}
}
\description{
  \code{model.frame} (a generic function) and its methods return a
  \code{\link{data.frame}} with the variables needed to use
  \code{formula} and any \code{\dots} arguments.
}
\details{
  Variables in the formula, \code{subset} and in \code{\dots} are looked
  for first in \code{data} and then in the environment of
  \code{formula}: see the help for \code{\link{formula}()} for further
  details.

  First all the variables needed are collected into a data frame.
  Then \code{subset}
  expression is evaluated, and it is is used as a row index to the data
  frame. Then the \code{na.action} function is applied to the data frame
  (and may well add attributes).  The levels of any factors in the data
  frame are adjusted according to the \code{drop.unused.levels} and
  \code{xlev} arguments.
}
\value{
  A \code{\link{data.frame}} containing the variables used in
  \code{formula} plus those specified \code{\dots}.
}
\seealso{\code{\link{model.matrix}} for the \dQuote{design matrix},
  \code{\link{formula}} for formulas  and
  \code{\link{expand.model.frame}} for model.frame manipulation.
}
\references{
  Chambers, J. M. (1992)
  \emph{Data for models.}
  Chapter 3 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\examples{
data(cars)
data.class(model.frame(dist ~ speed, data = cars))
}
\keyword{models}
\eof
\name{model.matrix}
\alias{model.matrix}
\alias{model.matrix.default}
\alias{model.matrix.lm}
%\alias{model.matrix.lm.null}
%\alias{model.matrix.glm.null}
\title{Construct Design Matrices}
\usage{
model.matrix(object, \dots)

\method{model.matrix}{default}(object, data = environment(object),
             contrasts.arg = NULL, xlev = NULL, \dots)
}
\arguments{
  \item{object}{an object of an appropriate class. For the default
    method, a model formula or terms object.}
  \item{data}{a data frame created with \code{\link{model.frame}}.}
  \item{contrasts.arg}{A list, whose entries are contrasts suitable for
    input to the \code{\link{contrasts}} replacement function and
    whose names are the names of columns of \code{data} containing
    \code{\link{factor}}s.}
  \item{xlev}{to be used as argument of \code{\link{model.frame}} if
    \code{data} has no \code{"terms"} attribute.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\description{
  \code{model.matrix} creates a design matrix.
}
\details{
  \code{model.matrix} creates a design matrix from the description given
  in \code{terms(formula)}, using the data in \code{data} which must
  contain columns with the same names as would be created by a call to
  \code{model.frame(formula)} or, more precisely, by evaluating
  \code{attr(terms(formula), "variables")}.  There may be other columns
  and the order is not important.  If \code{contrasts} is specified it
  overrides the default factor coding for that variable.

  In interactions, the variable whose levels vary fastest is the first
  one to appear in the formula (and not in the term), so in \code{~ a +
    b + b:a} the interaction will have \code{a} varying fastest.

  By convention, if the response variable also appears on the
  right-hand side of the formula it is dropped (with a warning),
  although interactions involving the term are retained.
}
\value{
  The design matrix for a regression model with the specified formula
  and data.
}
\references{
  Chambers, J. M. (1992)
  \emph{Data for models.}
  Chapter 3 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{model.frame}}, \code{\link{model.extract}},
  \code{\link{terms}}
}
\examples{
data(trees)
ff <- log(Volume) ~ log(Height) + log(Girth)
str(m <- model.frame(ff, trees))
mat <- model.matrix(ff, m)

dd <- data.frame(a = gl(3,4), b = gl(4,1,12))# balanced 2-way
options("contrasts")
model.matrix(~ a + b, dd)
model.matrix(~ a + b, dd, contrasts = list(a="contr.sum"))
model.matrix(~ a + b, dd, contrasts = list(a="contr.sum", b="contr.poly"))
m.orth <- model.matrix(~a+b, dd, contrasts = list(a="contr.helmert"))
crossprod(m.orth)# m.orth is  ALMOST  orthogonal
}
\keyword{models}
\eof
\name{model.tables}
\alias{model.tables}
\alias{model.tables.aov}
\alias{model.tables.aovlist}
\alias{print.tables.aov}
\title{Compute Tables of Results from an Aov Model Fit}
\description{
  Computes summary tables for model fits, especially complex \code{aov}
  fits.
}
\usage{
model.tables(x, \dots)

\method{model.tables}{aov}(x, type = "effects", se = FALSE, cterms, \dots)

\method{model.tables}{aovlist}(x, type = "effects", se = FALSE, \dots)
}
\arguments{
  \item{x}{a model object, usually produced by \code{aov}}
  \item{type}{type of table: currently only \code{"effects"} and
    \code{"means"} are implemented.}
  \item{se}{should standard errors be computed?}
  \item{cterms}{A character vector giving the names of the terms for
    which tables should be computed. The default is all tables.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\details{
  For \code{type = "effects"} give tables of the coefficients for each
  term, optionally with standard errors.

  For \code{type = "means"} give tables of the mean response for each
  combinations of levels of the factors in a term.
}
\value{
  An object of class \code{"tables.aov"}, as list which may contain components
  \item{tables}{A list of tables for each requested term.}
  \item{n}{The replication information for each term.}
  \item{se}{Standard error information.}
}
\section{Warning}{
  The implementation is incomplete, and only the simpler cases have been
  tested thoroughly.

  Weighted \code{aov} fits are not supported.
}

\seealso{
  \code{\link{aov}}, \code{\link{proj}},
  \code{\link{replications}}, \code{\link{TukeyHSD}},
  \code{\link{se.contrast}}
}

\examples{
## From Venables and Ripley (2002) p.165.
N <- c(0,1,0,1,1,1,0,0,0,1,1,0,1,1,0,0,1,0,1,0,1,1,0,0)
P <- c(1,1,0,0,0,1,0,1,1,1,0,0,0,1,0,1,1,0,0,1,0,1,1,0)
K <- c(1,0,0,1,0,1,1,0,0,1,0,1,0,1,1,0,0,0,1,1,1,0,1,0)
yield <- c(49.5,62.8,46.8,57.0,59.8,58.5,55.5,56.0,62.8,55.8,69.5,
55.0, 62.0,48.8,45.5,44.2,52.0,51.5,49.8,48.8,57.2,59.0,53.2,56.0)

npk <- data.frame(block=gl(6,4), N=factor(N), P=factor(P),
                  K=factor(K), yield=yield)
npk.aov <- aov(yield ~ block + N*P*K, npk)
model.tables(npk.aov, "means", se=TRUE)

## as a test, not particularly sensible statistically
options(contrasts=c("contr.helmert", "contr.treatment"))
npk.aovE <- aov(yield ~  N*P*K + Error(block), npk)
model.tables(npk.aovE,  se=TRUE)
model.tables(npk.aovE, "means")
}
\keyword{models}
\eof
\name{morley}
\docType{data}
\alias{morley}
\title{Michaelson-Morley Speed of Light Data}
\description{
  The classical data of Michaelson and Morley on the speed of light.
  The data consists of five experiments, each consisting of 20
  consecutive \sQuote{runs}.  The response is the speed of light
  measurement, suitably coded.
}
\usage{data(morley)}
\format{
  A data frame contains the following components:
  \describe{
    \item{\code{Expt}}{The experiment number, from 1 to 5.}
    \item{\code{Run}}{The run number within each experiment.}
    \item{\code{Speed}}{Speed-of-light measurement.}
  }
}
\details{
  The data is here viewed as a randomized block experiment with
  \sQuote{experiment} and \sQuote{run} as the factors.  \sQuote{run} may
  also be considered a quantitative variate to account for linear (or
  polynomial) changes in the measurement over the course of a single
  experiment.
}
\source{
  A. J. Weekes (1986)
  \emph{A Genstat Primer}.
  London: Edward Arnold.
}
\examples{
data(morley)
morley$Expt <- factor(morley$Expt)
morley$Run <- factor(morley$Run)
attach(morley)
plot(Expt, Speed, main = "Speed of Light Data", xlab = "Experiment No.")
fm <- aov(Speed ~ Run + Expt, data = morley)
summary(fm)
fm0 <- update(fm, . ~ . - Run)
anova(fm0, fm)
detach(morley)
}
\keyword{datasets}
\eof
\name{mosaicplot}
\alias{mosaicplot}
\alias{mosaicplot.default}
\alias{mosaicplot.formula}
\title{Mosaic Plots}
\description{Plots a mosaic on the current graphics device.}
\usage{
mosaicplot(x, \dots)

\method{mosaicplot}{default}(x, main = deparse(substitute(x)), 
                   sub = NULL, xlab = NULL, ylab = NULL,
                   sort = NULL, off = NULL, dir = NULL,
                   color = FALSE, shade = FALSE, margin = NULL,
                   cex.axis = 0.66, las = par("las"),
                   type = c("pearson", "deviance", "FT"), \dots)

\method{mosaicplot}{formula}(formula, data = NULL, \dots,
          main = deparse(substitute(data)), subset)
}
\arguments{
  \item{x}{a contingency table in array form, with optional category
    labels specified in the \code{dimnames(x)} attribute.  The table is
    best created by the \code{table()} command.}
  \item{main}{character string for the mosaic title.}
  \item{sub}{character string for the mosaic sub-title (at bottom).}
  \item{xlab,ylab}{x- and y-axis labels used for the plot; by default,
    the first and second element of \code{names(dimnames(X))} (i.e., the
    name of the first and second variable in \code{X}).}
  \item{sort}{vector ordering of the variables, containing a permutation
    of the integers \code{1:length(dim(x))} (the default).}
  \item{off}{vector of offsets to determine percentage spacing at each
    level of the mosaic (appropriate values are between 0 and 20,
    and the default is 10 at each level).  There should be one
    offset for each dimension of the contingency table.}
  \item{dir}{vector of split directions (\code{"v"} for vertical and
    \code{"h"} for horizontal) for each level of the mosaic, one
    direction for each dimension of the contingency table.  The
    default consists of alternating directions, beginning with a
    vertical split.}
  \item{color}{logical or (recycling) vector of colors for color
    shading, used only when \code{shade} is \code{FALSE}.  The default
    \code{color=FALSE} gives empty boxes with no shading.}
  \item{shade}{a logical indicating whether to produce extended mosaic
    plots, or a numeric vector of at most 5 distinct positive numbers
    giving the absolute values of the cut points for the residuals.  By
    default, \code{shade} is \code{FALSE}, and simple mosaics are
    created.  Using \code{shade = TRUE} cuts absolute values at 2 and
    4.}
  \item{margin}{a list of vectors with the marginal totals to be fit in
    the log-linear model.  By default, an independence model is fitted.
    See \code{\link{loglin}} for further information.}
  \item{cex.axis}{The magnification to be used for axis annotation,
    as a multiple of \code{par("cex")}.}
  \item{las}{numeric; the style of axis labels, see \code{\link{par}}.}
  \item{type}{a character string indicating the type of residual to be
    represented.  Must be one of \code{"pearson"} (giving components of
    Pearson's \eqn{\chi^2}{chi-squared}), \code{"deviance"} (giving
    components of the likelihood ratio \eqn{\chi^2}{chi-squared}), or
    \code{"FT"} for the Freeman-Tukey residuals.  The value of this
    argument can be abbreviated.}
  \item{formula}{a formula, such as \code{y ~ x}.}
  \item{data}{a data frame (or list), or a contingency table from which
    the variables in \code{formula} should be taken.}
  \item{\dots}{further arguments to be passed to or from methods.}
  \item{subset}{an optional vector specifying a subset of observations
    in the data frame to be used for plotting.}
}
\details{
  This is a generic function.  It currently has a default method
  (\code{\link{mosaicplot.default}}) and a formula interface
  (\code{\link{mosaicplot.formula}}).

  Extended mosaic displays show the standardized residuals of a
  loglinear model of the counts from by the color and outline of the
  mosaic's tiles.  (Standardized residuals are often referred to a
  standard normal distribution.)  Negative residuals are drawn in shaded
  of red and with broken outlines; positive ones are drawn in blue with
  solid outlines.

  For the formula method, if \code{data} is an object inheriting from
  classes \code{"table"} or \code{"ftable"}, or an array with more than
  2 dimensions, it is taken as a contingency table, and hence all
  entries should be nonnegative.  In this case, the left-hand side of
  \code{formula} should be empty, and the variables on the right-hand
  side should be taken from the names of the dimnames attribute of the
  contingency table.  A marginal table of these variables is computed,
  and a mosaic of this table is produced.

  Otherwise, \code{data} should be a data frame or matrix, list or
  environment containing the variables to be cross-tabulated.  In this
  case, after possibly selecting a subset of the data as specified by
  the \code{subset} argument, a contingency table is computed from the
  variables given in \code{formula}, and a mosaic is produced from
  this.

  See Emerson (1998) for more information and a case study with
  television viewer data from Nielsen Media Research.
}
\author{
  S-PLUS original by John Emerson \email{emerson@stat.yale.edu}.
  Originally modified and enhanced for \R by KH.
}
\references{
  Hartigan, J.A., and Kleiner, B. (1984)
  A mosaic of television ratings. \emph{The American Statistician},
  \bold{38}, 32--35.

  Emerson, J. W. (1998)
  Mosaic displays in S-PLUS: a general implementation and a case study.
  \emph{Statistical Computing and Graphics Newsletter (ASA)},
  \bold{9}, 1, 17--23.

  Friendly, M. (1994)
  Mosaic displays for multi-way contingency tables.
  \emph{Journal of the American Statistical Association}, \bold{89},
  190--200.

  The home page of Michael Friendly
  (\url{http://www.math.yorku.ca/SCS/friendly.html}) provides
  information on various aspects of graphical methods for analyzing
  categorical data, including mosaic plots.
}
\seealso{
  \code{\link{assocplot}},
  \code{\link{loglin}}.
}
\examples{
data(Titanic)
mosaicplot(Titanic, main = "Survival on the Titanic", color = TRUE)
## Formula interface for tabulated data:
mosaicplot(~ Sex + Age + Survived, data = Titanic, color = TRUE)

data(HairEyeColor)
mosaicplot(HairEyeColor, shade = TRUE)
## Independence model of hair and eye color and sex.  Indicates that
## there are significantly more blue eyed blonde females than expected
## in the case of independence (and too few brown eyed blonde females).

mosaicplot(HairEyeColor, shade = TRUE, margin = list(c(1,2), 3))
## Model of joint independence of sex from hair and eye color.  Males
## are underrepresented among people with brown hair and eyes, and are
## overrepresented among people with brown hair and blue eyes, but not
## "significantly".

## Formula interface for raw data: visualize crosstabulation of numbers
## of gears and carburettors in Motor Trend car data.
data(mtcars)
mosaicplot(~ gear + carb, data = mtcars, color = TRUE, las = 1)
mosaicplot(~ gear + carb, data = mtcars, color = 2:3, las = 1)# color recycling
}
\keyword{hplot}
\eof
\name{mtcars}
\docType{data}
\alias{mtcars}
\title{Motor Trend Car Road Tests}
\description{
  The data was extracted from the 1974 \emph{Motor Trend} US magazine,
  and comprises fuel consumption and 10 aspects of
  automobile design and performance for 32 automobiles (1973--74
  models).
}
\usage{data(mtcars)}
\format{
  A data frame with 32 observations on 11 variables.
  \tabular{rll}{
    [, 1] \tab mpg  \tab Miles/(US) gallon \cr
    [, 2] \tab cyl  \tab Number of cylinders \cr
    [, 3] \tab disp \tab Displacement (cu.in.) \cr
    [, 4] \tab hp   \tab Gross horsepower \cr
    [, 5] \tab drat \tab Rear axle ratio \cr
    [, 6] \tab wt   \tab Weight (lb/1000) \cr
    [, 7] \tab qsec \tab 1/4 mile time \cr
    [, 8] \tab vs   \tab V/S \cr
    [, 9] \tab am   \tab Transmission (0 = automatic, 1 = manual) \cr
    [,10] \tab gear \tab Number of forward gears \cr
    [,11] \tab carb \tab Number of carburettors
  }
}
\source{
  Henderson and Velleman (1981),
  Building multiple regression models interactively.
  \emph{Biometrics}, \bold{37}, 391--411.
}
\examples{
data(mtcars)
pairs(mtcars, main = "mtcars data")
coplot(mpg ~ disp | as.factor(cyl), data = mtcars,
       panel = panel.smooth, rows = 1)
}
\keyword{datasets}
\eof
\name{mtext}
\title{Write Text into the Margins of a Plot}
\usage{
mtext(text, side = 3, line = 0, outer = FALSE, at = NA,
      adj = NA, cex = NA, col = NA, font = NA, vfont = NULL, \dots)
}
\alias{mtext}
\arguments{
  \item{text}{one or more character strings or expressions.}
  \item{side}{on which side of the plot (1=bottom, 2=left, 3=top, 4=right).}
  \item{line}{on which MARgin line, starting at 0 counting outwards.}
  \item{outer}{use outer margins if available.}
  \item{at}{give location in user-coordinates.  If \code{length(at)==0}
    (the default), the location will be determined by \code{adj}.
  }
  \item{adj}{adjustment for each string. For strings parallel
    to the axes, \code{adj=0} means left or bottom alignment, and
    \code{adj=1} means right or top aligment.
    If \code{adj} is not a finite value (the default), the value
    \code{par("las")} determines the adjustment. For strings plotted
    parallel to the axis the default is to centre the string.}
  \item{\dots}{Further graphical parameters (see \code{\link{text}} and
    \code{\link{par}}) ; currently supported are:}
  \item{cex}{character expansion factor (default = 1).}
  \item{col}{color to use.}
  \item{font}{font for text.}
  \item{vfont}{vector font for text.}
}
% mtext is defined via do_mtext(.) in  src/main/plot.c ---
\description{
  Text is written in one of the four margins of the current figure region
  or one of the outer margins of the device region.
}
\details{
  The \dQuote{user coordinates} in the outer margins always range from zero to
  one, and are not affected by the user coordinates in the figure
  region(s) --- \R is differing here from other implementations of S.

  The arguments \code{side}, \code{line}, \code{at}, \code{at},
  \code{adj}, the further graphical parameters and even \code{outer} can
  be vectors, and recycling will take place to plot as many strings as
  the longest of the vector arguments.  Note that a vector \code{adj}
  has a different meaning from \code{\link{text}}.

  \code{adj = 0.5} will centre the string, but for \code{outer=TRUE} on
  the device region rather than the plot region.

  Parameter \code{las} will determine the orientation of the string(s).
  For strings plotted perpendicular to the axis the default justifcation
  is to place the end of the string nearest the axis on the specified line.

  Note that if the text is to be plotted perpendicular to the axis,
  \code{adj} determines the justification of the string \emph{and} the
  position along the axis unless \code{at} is specified.
}
\section{Side Effects}{The given text is written onto the current plot.}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{title}}, \code{\link{text}}, \code{\link{plot}},
  \code{\link{par}};
  \code{\link{plotmath}} for details on mathematical annotation.
}
\examples{
plot(1:10, (-4:5)^2, main="Parabola Points", xlab="xlab")
mtext("10 of them")
for(s in 1:4)
    mtext(paste("mtext(..., line= -1, {side, col, font} = ",s,
          ", cex = ", (1+s)/2, ")"), line = -1,
          side=s, col=s, font=s, cex= (1+s)/2)
mtext("mtext(..., line= -2)", line = -2)
mtext("mtext(..., line= -2, adj = 0)", line = -2, adj =0)
##--- log axis :
plot(1:10, exp(1:10), log='y', main="log='y'", xlab="xlab")
for(s in 1:4) mtext(paste("mtext(...,side=",s,")"), side=s)
}
\keyword{aplot}


\eof
\name{n2mfrow}
\alias{n2mfrow}
\title{Compute Default mfrow From Number of Plots}
\description{
  Easy setup for plotting multiple figures (in a rectangular layout) on
  one page.  This computes a sensible default for
  \code{\link{par}(mfrow)}.
}
\usage{
n2mfrow(nr.plots)
}
\arguments{
  \item{nr.plots}{integer; the number of plot figures you'll want to draw.}
}
\value{
  A length two integer vector \code{nr, nc} giving the number of rows
  and columns, fulfilling \code{nr >= nc >= 1} and \code{nr * nc >= nr.plots}.
}
\author{Martin Maechler}
\seealso{\code{\link{par}}, \code{\link{layout}}.}
\examples{
n2mfrow(8) # 3 x 3

n <- 5 ; x <- seq(-2,2, len=51)
## suppose now that 'n' is not known {inside function}
op <- par(mfrow = n2mfrow(n))
for (j in 1:n)
   plot(x, x^j, main = substitute(x^ exp, list(exp = j)), type='l', col="blue")

sapply(1:10, n2mfrow)
}
\keyword{dplot}
\keyword{utilities}
\eof
\name{na.action}
\title{NA Action}
\usage{
na.action(object, \dots)
%na.action.default(object, \dots)
}
\alias{na.action}
\alias{na.action.default}
\arguments{
  \item{object}{any object whose \code{\link{NA}} action is given.}
  \item{\dots}{further arguments special methods could require.}
}
\description{
  \code{na.action} is a generic function, and \code{na.action.default} its
  default method.
}
\value{
  The \dQuote{NA action} which should be applied to \code{object} whenever
  \code{\link{NA}}s are not desired.
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S.}
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{options}("na.action")}, \code{\link{na.omit}},
  \code{\link{na.fail}}
}
\examples{
na.action(c(1, NA))
}
\keyword{NA}
\keyword{methods}
\eof
\name{na.fail}
\alias{na.fail}
\alias{na.fail.default}
\alias{na.omit}
\alias{na.omit.data.frame}
\alias{na.omit.default}
\alias{na.exclude}
\alias{na.exclude.data.frame}
\alias{na.exclude.default}
\alias{na.pass}
\title{Handle Missing Values in Objects}
\usage{
na.fail(object, \dots)
na.omit(object, \dots)
na.exclude(object, \dots)
na.pass(object, \dots)
}
\arguments{
  \item{object}{an \R object, typically a data frame}
  \item{\dots}{further arguments special methods could require.}
}
\description{
  These generic functions are useful for dealing with \code{\link{NA}}s
  in e.g., data frames.
  \code{na.fail} returns the object if it does not contain any
  missing values, and signals an error otherwise.
  \code{na.omit} returns the object with incomplete cases removed.
  \code{na.pass} returns the object unchanged.
}
\details{
  At present these will handle vectors, matrices and data frames
  comprising vectors and matrices (only).

  If \code{na.omit} removes cases, the row numbers of the cases form the
  \code{"na.action"} attribute of the result, of class \code{"omit"}.

  \code{na.exclude} differs from \code{na.omit} only in the class of the
  \code{"na.action"} attribute of the result, which is
  \code{"exclude"}.  This gives different behaviour in functions making
  use of \code{\link{naresid}} and \code{\link{napredict}}: when
  \code{na.exclude} is used the residuals and predictions are padded to
  the correct length by inserting \code{NA}s for cases omitted by
  \code{na.exclude}.
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S.}
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{na.action}};
  \code{\link{options}} with argument \code{na.action} for setting
  \dQuote{NA actions};
  and \code{\link{lm}} and \code{\link{glm}} for functions using these.
}
\examples{
DF <- data.frame(x = c(1, 2, 3), y = c(0, 10, NA))
na.omit(DF)
m <- as.matrix(DF)
na.omit(m)
stopifnot(all(na.omit(1:3) == 1:3))  # does not affect objects with no NA's
try(na.fail(DF))#> Error: missing values in ...

options("na.action")
}
\keyword{NA}
\eof
\name{naresid}
\alias{naresid}
\alias{naresid.default}
\alias{naresid.exclude}
\alias{napredict}
\alias{napredict.default}
\alias{napredict.exclude}
\title{
Adjust for Missing Values
}
\description{
  Use missing value information to adjust residuals and predictions.
}
\usage{
naresid(omit, x, \dots)
napredict(omit, x, \dots)
}
\arguments{
  \item{omit}{
    An object produced by an \code{na.action} function.
  }
  \item{x}{
    A vector, data frame, or matrix to be adjusted based upon the
    missing value information.
  }
  \item{\dots}{further arguments passed to or from other methods.}
}
\value{
  These return a similar object to \code{x}.
}
\details{
  These are utility functions used to allow \code{\link{predict}} and
  \code{\link{resid}} methods for modelling functions to compensate for
  the removal of \code{NA}s in the fitting process.  There are used by
  the default, \code{"lm"} and \code{"glm"} methods, and by further
  methods in packages \pkg{MASS}, \pkg{rpart} and \pkg{survival}.

  The default methods do nothing.  The method for the \code{na.exclude}
  action to pad the object with \code{NA}s in the correct positions to
  have the same number of rows as the original data frame.

  Currently \code{naresid} and \code{napredict} are identical, but
  future methods need not be.  \code{naresid} is used for residuals, and
  \code{napredict} for fitted values and predictions.
}
\note{
  Packages \code{rpart} and \code{survival5} used to contain versions of
  these functions that had an \code{na.omit} action equivalent to that
  now used for \code{na.exclude}.
}
\keyword{NA}
\keyword{models}
\eof
\name{name}
\alias{name}
\alias{is.symbol}
\alias{as.symbol}
\alias{as.name}
\alias{is.name}
\title{Variable Names or Symbols, respectively}
\description{
  \code{as.symbol} coerces its argument to be a \emph{symbol}, or
  equivalently, a \emph{name}.  The argument must be of mode
  \code{"character"}.  \code{as.name} is an alias for \code{as.symbol}.

  \code{is.symbol} (and \code{is.name} equivalently) returns \code{TRUE}
  or \code{FALSE} depending on whether its argument is a symbol (i.e.,
  name) or not.
}
\usage{
as.symbol(x)
is.symbol(y)

as.name(x)
is.name(y)
}
\arguments{
  \item{x, y}{objects to be coerced or tested.} 
}
\note{
  The term \dQuote{symbol} is from the LISP background of \R, whereas
  \dQuote{name} has been the standard S term for this.
}
\details{
  \code{is.symbol} is generic: you can write methods to handle
  of specific classes of objects, see \link{InternalMethods}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{call}}, \code{\link{is.language}}.
  For the internal object mode, \code{\link{typeof}}.
}
\examples{
an <- as.name("arrg")
is.name(an) # TRUE
str(an)# symbol
}
\keyword{programming}
\keyword{attribute}
\eof
\name{names}
\alias{names}
\alias{names.default}
\alias{names<-}
\alias{names<-.default}
\title{The Names Attribute of an Object}
\description{
  Functions to get or set the names of an object.
}
\usage{
names(x)
names(x) <- value
}
\arguments{
  \item{x}{an \R object.}
  \item{value}{a character vector of up to the same length as \code{x}, or
    \code{NULL}.} 
}
\value{
  For \code{names}, \code{NULL} or a character vector of the same length
  as \code{x}.

  For \code{names<-}, the updated object.  (Note that the value of
  \code{names(x) <- value} is that of the assignment, \code{value}, not
  the return value from the left-hand side.)
}
\details{
  \code{names} is a generic accessor function, and \code{names<-} is a
  generic replacement function.  The default methods get and set
  the \code{"names"} attribute of a vector or list.

  If \code{value} is shorter than \code{x}, it is extended by character
  \code{NA}s to the length of \code{x}.
  
  It is possible to update just part of the names attribute via the
  general rules: see the examples.  This works because the expression
  there is evaluated as \code{z <- "names<-"(z, "[<-"(names(z), 3, "c2"))}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
data(islands)
# print the names attribute of the islands data set
names(islands)

# remove the names attribute
names(islands) <- NULL

z <- list(a=1, b="c", c=1:3)
names(z)
# change just the name of the third element.
names(z)[3] <- "c2"
z

## assign just one name
z <- 1:3
names(z)
# change just the name of the third element.
names(z)[2] <- "b"
z
}
\keyword{attribute}
\eof
\name{naprint}
\alias{naprint}
\alias{naprint.default}
\alias{naprint.exclude}
\alias{naprint.omit}
\title{
Adjust for Missing Values
}
\description{
  Use missing value information to report the effects of an \code{na.action}.
}
\usage{
naprint(x, \dots)
}
\arguments{
  \item{x}{
    An object produced by an \code{na.action} function.
  }
  \item{\dots}{further arguments passed to or from other methods.}
}
\details{
  This is a generic function, and the exact information differs by
  method. \code{naprint.omit} reports the number of rows omitted:
  \code{naprint.default} reports an empty string.
}
\value{
  A character string providing information on missing values, for
  example the number.
}
\keyword{NA}
\keyword{models}
\eof
\name{nargs}
\title{The Number of Arguments to a Function}
\usage{nargs()}
\alias{nargs}
\description{
  When used inside a function body, \code{nargs} returns the number of
  arguments supplied to that function, \emph{including} positional
  arguments left blank. 
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{\code{\link{args}}, \code{\link{formals}} and \code{\link{sys.call}}.}
\examples{
tst <- function(a, b = 3, ...) {nargs()}
tst() # 0
tst(clicketyclack) # 1 (even non-existing)
tst(c1, a2, rr3) # 3

foo <- function(x, y, z, w) {
   cat("call was", deparse(match.call()), "\n")
   nargs()
}
foo()    # 0
foo(,,3) # 3
foo(z=3) # 1, even though this is the same call

nargs()# not really meaningful
}
\keyword{programming}
\eof
\name{nchar}
\title{Count the Number of Characters}
\usage{nchar(x)}
\alias{nchar}
\description{
  \code{nchar} takes a character vector as an argument and
  returns a vector whose elements contain the number of characters in
  the corresponding element of \code{x}.
}
\arguments{
  \item{x}{character vector, or a vector to be coerced to a character
    vector.} 
}
\details{
  The internal equivalent of \code{\link{as.character}} is performed on
  \code{x}. If you want to operate
  on non-vector objects passing them through \code{\link{deparse}} first
  will be required.
}
\value{
  The number of characters as the string will be printed (integer
  \code{2} for a missing string).
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{strwidth}} giving width of strings for plotting;
  \code{\link{paste}}, \code{\link{substr}}, \code{\link{strsplit}}
}
\examples{
x <- c("asfef","qwerty","yuiop[","b","stuff.blah.yech")
nchar(x)
# 5  6  6  1 15

nchar(deparse(mean))
# 23  1 16 45 11 64  2 17 50 43  2 17  1
}
\keyword{character}
\eof
\name{nclass}
\alias{nclass.Sturges}
\alias{nclass.scott}
\alias{nclass.FD}
\title{
Compute the Number of Classes for a Histogram
}
\description{
  Compute the number of classes for a histogram, for use internally in
  \code{\link{hist}}.
}
\usage{
nclass.Sturges(x)
nclass.scott(x)
nclass.FD(x)
}
\arguments{
  \item{x}{
    A data vector.
  }
}
\value{
  The suggested number of classes.
}
\details{
  \code{nclass.Sturges} uses Sturges' formula, implicitly basing bin
  sizes on the range of the data.
  
  \code{nclass.scott} uses Scott's choice for a normal distribution based on
  the estimate of the standard error.

  \code{nclass.FD} uses the
  Freedman-Diaconis choice based on the inter-quartile range.
}
\references{
  Venables, W. N. and Ripley, B. D. (2002)
  \emph{Modern Applied Statistics with S-PLUS.}
  Springer, page 112.

  Freedman, D. and Diaconis, P. (1981)
  On the histogram as a density estimator: \eqn{L_2} theory.
  \emph{Zeitschrift für Wahrscheinlichkeitstheorie und verwandte
    Gebiete} \bold{57}, 453--476.

  Scott, D. W. (1979) On optimal and data-based histograms.
  \emph{Biometrika} \bold{66}, 605--610.

  Scott, D. W. (1992)
  \emph{Multivariate Density Estimation. Theory, Practice, and
    Visualization}. Wiley.
}
\seealso{
  \code{\link{hist}}
}
\keyword{univar}
\eof
\name{nextn}
\title{Highly Composite Numbers}
\usage{
nextn(n, factors=c(2,3,5))
}
\alias{nextn}
\arguments{
\item{n}{an integer.}
\item{factors}{a vector of positive integer factors.}
}
\description{
\code{nextn} returns the smallest integer,
greater than or equal to \code{n}, which can be obtained
as a product of powers of the values contained in \code{factors}.
\code{nextn} is intended to be used to find a suitable length
to zero-pad the argument of \code{fft} to
so that the transform is computed quickly.
The default value for \code{factors} ensures this.
}
\seealso{
\code{\link{convolve}}, \code{\link{fft}}.
}
\examples{
nextn(1001) # 1024
table(sapply(599:630, nextn))
}
\keyword{math}

\eof
\name{nhtemp}
\docType{data}
\alias{nhtemp}
\title{Average Yearly Temperatures in New Haven}
\description{
  The mean annual temperature in degrees Fahrenheit in New Haven,
  Connecticut, from 1912 to 1971.
}
\usage{data(nhtemp)}
\format{A time series of 60 observations.}
\source{
  Vaux, J. E. and Brinker, N. B. (1972)
  \emph{Cycles}, \bold{1972}, 117--121.
}
\references{
  McNeil, D. R. (1977)
  \emph{Interactive Data Analysis}.
  New York: Wiley.
}
\examples{
data(nhtemp)
plot(nhtemp, main = "nhtemp data",
  ylab = "Mean annual temperature in New Haven, CT (deg. F)")
}
\keyword{datasets}
\eof
\name{nlevels}
\title{The Number of Levels of a Factor}
\usage{
nlevels(x)
}
\alias{nlevels}
\description{
  Return the number of levels which its argument has.
}
\arguments{
  \item{x}{an object, usually a factor.} 
}
\details{
  If the argument is not a \code{\link{factor}}, \code{NA} is returned.

  The actual factor levels (if they exist) can be obtained
  with the \code{\link{levels}} function.
}
\examples{
nlevels(gl(3,7)) # = 3
}
\keyword{category}
\eof
\name{nlm}
\alias{nlm}
\title{Non-Linear Minimization}
\usage{
nlm(f, p, hessian = FALSE, typsize=rep(1, length(p)), fscale=1,
    print.level = 0, ndigit=12, gradtol = 1e-6,
    stepmax = max(1000 * sqrt(sum((p/typsize)^2)), 1000),
    steptol = 1e-6, iterlim = 100, check.analyticals = TRUE, \dots)
}
\description{
  This function carries out a minimization of the function \code{f}
  using a Newton-type algorithm.  See the references for details.
}
\arguments{
  \item{f}{the function to be minimized.  If the function value has
    an attribute called \code{gradient} or both \code{gradient} and
    \code{hessian} attributes, these will be used in the calculation of
    updated parameter values.  Otherwise, numerical derivatives are
    used. \code{\link{deriv}} returns a function with suitable
    \code{gradient} attribute.  This should be a function a vector of
    the length of \code{p} followed by any other arguments specified
    in \code{dots}.}
  \item{p}{starting parameter values for the minimization.}
  \item{hessian}{if \code{TRUE}, the hessian of \code{f}
    at the minimum is returned.}
  \item{typsize}{an estimate of the size of each parameter
    at the minimum.}
  \item{fscale}{an estimate of the size of \code{f} at the minimum.}
  \item{print.level}{this argument determines the level of printing
    which is done during the minimization process.  The default
    value of \code{0} means that no printing occurs, a value of \code{1}
    means that initial and final details are printed and a value
    of 2 means that full tracing information is printed.}
  \item{ndigit}{the number of significant digits in the function \code{f}.}
  \item{gradtol}{a positive scalar giving the tolerance at which the
    scaled gradient is considered close enough to zero to
    terminate the algorithm.  The scaled gradient is a
    measure of the relative change in \code{f} in each direction
    \code{p[i]} divided by the relative change in \code{p[i]}.}
  \item{stepmax}{a positive scalar which gives the maximum allowable
    scaled step length.  \code{stepmax} is used to prevent steps which
    would cause the optimization function to overflow, to prevent the
    algorithm from leaving the area of interest in parameter space, or to
    detect divergence in the algorithm. \code{stepmax} would be chosen
    small enough to prevent the first two of these occurrences, but should
    be larger than any anticipated reasonable step.}
  \item{steptol}{A positive scalar providing the minimum allowable
    relative step length.}
  \item{iterlim}{a positive integer specifying the maximum number of
    iterations to be performed before the program is terminated.}
  \item{check.analyticals}{a logical scalar specifying whether the
    analytic gradients and Hessians, if they are supplied, should be
    checked against numerical derivatives at the initial parameter
    values. This can help detect incorrectly formulated gradients or
    Hessians.}
  \item{\dots}{additional arguments to \code{f}.}
}
\details{
  If a gradient or hessian is supplied but evaluates to the wrong mode
  or length, it will be ignored if \code{check.analyticals = TRUE} (the
  default) with a warning.  The hessian is not even checked unless the
  gradient is present and passes the sanity checks.

  From the three methods available in the original source, we always use
  method \dQuote{1} which is line search.
}
\value{
  A list containing the following components:
  \item{minimum}{the value of the estimated minimum of \code{f}.}
  \item{estimate}{the point at which the mininum value of
    \code{f} is obtained.}
  \item{gradient}{the gradient at the estimated minimum of \code{f}.}
  \item{hessian}{the hessian at the estimated minimum of \code{f} (if
    requested).}
  \item{code}{an integer indicating why the optimization process terminated.
    \describe{
      \item{1:}{relative gradient is close to zero, current iterate is
	probably solution.}
      \item{2:}{successive iterates within tolerance, current iterate
	is probably solution.}
      \item{3:}{last global step failed to locate a point lower than
	\code{estimate}.  Either \code{estimate} is an approximate local
	minimum of the function or \code{steptol} is too small.}
      \item{4:}{iteration limit exceeded.}
      \item{5:}{maximum step size \code{stepmax} exceeded five consecutive
	times.  Either the function is unbounded below,
	becomes asymptotic to a finite value from above in
	some direction or \code{stepmax} is too small.}
    }
  }
  \item{iterations}{the number of iterations performed.}
}
\references{
  Dennis, J. E. and Schnabel, R. B. (1983) \emph{Numerical Methods for
    Unconstrained Optimization and Nonlinear Equations.} Prentice-Hall,
  Englewood Cliffs, NJ.

  Schnabel, R. B., Koontz, J. E. and Weiss, B. E. (1985) A modular
  system of algorithms for unconstrained minimization.
  \emph{ACM Trans. Math. Software}, \bold{11}, 419--440.
}
\seealso{
  \code{\link{optim}}.  \code{\link{optimize}} for one-dimensional
  minimization and \code{\link{uniroot}} for root finding.
  \code{\link{deriv}} to calculate analytical derivatives.

  For nonlinear regression, \code{\link[nls]{nls}} (in package
  \pkg{nls}), may be of better use.
}
\examples{
f <- function(x) sum((x-1:length(x))^2)
nlm(f, c(10,10))
nlm(f, c(10,10), print.level = 2)
str(nlm(f, c(5), hessian = TRUE))

f <- function(x, a) sum((x-a)^2)
nlm(f, c(10,10), a=c(3,5))
f <- function(x, a)
{
    res <- sum((x-a)^2)
    attr(res, "gradient") <- 2*(x-a)
    res
}
nlm(f, c(10,10), a=c(3,5))

## more examples, including the use of derivatives.
\dontrun{demo(nlm)}
}
\keyword{nonlinear}
\keyword{optimize}
\eof
\name{noquote}
\alias{noquote}
\alias{print.noquote}
\alias{as.matrix.noquote}
\alias{[.noquote}
\title{Class for ``no quote'' Printing of Character Strings}
\description{
  Print character strings without quotes.
}
\usage{
noquote(obj)
\method{print}{noquote}(x, \dots)
}
\arguments{
  \item{obj}{any \R object, typically a vector of
    \code{\link{character}} strings.}
  \item{x}{an object of class \code{"noquote"}.}
  \item{\dots}{further options for \code{\link{print}}.}
}
\details{
  \code{noquote} returns its argument as an object of class
  \code{"noquote"}.  There is a subscript method (\code{"[.noquote"})
  which ensures that the class is not lost by subsetting.  The print
  method (\code{print.noquote}) prints character stringss \emph{without}
  quotes (\code{"\dots"}).

  These functions exist both as utilities and as an example of using
  \code{\link[base]{class}} and object orientation.
}
\author{Martin Maechler \email{maechler@stat.math.ethz.ch}}
\seealso{
  \code{\link{methods}},
  \code{\link[base]{class}},
  \code{\link{print}}.
}
\examples{
letters
nql <- noquote(letters)
nql
nql[1:4] <- "oh"
nql[1:12]

cmp.logical <- function(log.v)
{
  ## Purpose: compact printing of logicals
  log.v <- as.logical(log.v)
  noquote(if(length(log.v)==0)"()" else c(".","|")[1+log.v])
}
cmp.logical(runif(20) > 0.8)
}
\keyword{print}
\keyword{methods}
\keyword{utilities}
\eof
\name{NotYet}
\title{Not Yet Implemented Functions and Unused Arguments}
\alias{NotYetImplemented}
\alias{.NotYetImplemented}
\alias{NotYetUsed}
\alias{.NotYetUsed}
\description{
  In order to pinpoint missing functionality, the \R core team uses
  these functions for missing \R functions and not yet used arguments of
  existing \R functions (which are typically there for compatibility
  purposes).

  You are very welcome to contribute your code \dots
}
\usage{
.NotYetImplemented()
.NotYetUsed(arg, error = TRUE)
}
\arguments{
  \item{arg}{an argument of a function that is not yet used.}
  \item{error}{a logical.  If \code{TRUE}, an error is signalled; if
    \code{FALSE}; only a warning is given.}
}
%------ PLEASE: put \alias{.} here for  EACH !
%done\alias{symbols}
%done\alias{plot.lm}
%NOT done, but in ./plot.lm.Rd on purpose:  \alias{plot.mlm}
\seealso{the contrary, \code{\link{Deprecated}} and
  \code{\link{Defunct}} for outdated code.}
\examples{
plot.mlm         # to see how the "NotYetImplemented"
                 # reference is made automagically
try(plot.mlm())

barplot(1:5, inside = TRUE) # 'inside' is not yet used
}
\keyword{documentation}
\keyword{utilities}
\eof
\name{nrow}
\title{The Number of Rows/Columns of an Array}
\usage{
nrow(x)
ncol(x)
NCOL(x)
NROW(x)
}
\alias{nrow}
\alias{NROW}
\alias{ncol}
\alias{NCOL}
\arguments{
  \item{x}{a vector, array or data frame}
}
\description{
  \code{nrow} and \code{ncol} return the number of rows or columns
  present in \code{x}.
  \code{NCOL} and \code{NROW} do the same treating a vector as
  1-column matrix.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole (\code{ncol} and \code{nrow}.)
}
\seealso{
  \code{\link{dim}} which returns \emph{all} dimensions;
  \code{\link{array}}, \code{\link{matrix}}.
}
\value{an \code{\link{integer}} of length 1 or \code{\link{NULL}}.}
\examples{
ma <- matrix(1:12, 3, 4)
nrow(ma)   # 3
ncol(ma)   # 4

ncol(array(1:24, dim = 2:4)) # 3, the second dimension
NCOL(1:12) # 1
NROW(1:12) # 12
}
\keyword{array}
\eof
\name{ns-alt}
\title{Experimental Alternative Name Specification Support}
\alias{.Export}
\alias{.Import}
\alias{.ImportFrom}
\alias{.S3method}
\description{
  Alternative interface for specifying a name space within the code of a
  package.
}
\usage{
.Export(\dots)
.Import(\dots)
.ImportFrom(name, \dots)
.S3method(generic, class, method)
}
\arguments{
  \item{\dots}{name or literal character string arguments.}
  \item{name}{name or literal character string.}
  \item{generic}{name or literal character string.}
  \item{class}{name or literal character string.}
  \item{method}{optional character or function argument.}
}
\details{
  As an experimental alternative to using a \file{NAMESPACE} file it is
  possible to add a name space to a package by adding a
  \code{Namespace: <package_name>} entry to the \file{DESCRIPTION}
  file and placing directives to specify imports and exports directly in
  package code.  These directives should be viewed as declarations, not
  as function calls.   Except to the optional method argument to
  \code{.S3method} arguments are not evaluated.  These directives should
  only be used at top level of package code except as noted below.

  \code{.Export} is used to declare exports.  Its arguments should be
  literal names or character strings.  \code{.Export} should only be
  used at package top level.

  \code{.Import} is used to declare the import of entire name spaces.
  Its arguments should be literal names or character strings.
  \code{.ImportFrom} is used to declare the import of selected
  variables from a single name space.  The first argument is a literal
  name or character string identifying the source name space; the
  remaining arguments are literal names or character strings identifying
  the variables to import.  As an experimental feature both
  \code{.Import} and \code{.ImportFrom} can be used to import
  variables into a local environment.  The drawback of allowing this
  is that dependencies cannot be determined easily at package load
  time, and as a result this feature may need to be dropped.

  \code{.S3method} is used to declare a method for S3-style
  \code{UseMethod} dispatch.  This is needed since methods in packages
  that are imported but not on the search path might not be visible to
  the standard dispatch mechanism at a call site.  The first argument
  is the name of the generic, the second specifies the class.  The third
  argument is optional and defaults to the usual concatenation of
  generic and class separated by a period.  If supplied, the third
  argument should evaluate to a character string or a function.  If the
  third argument is omitted or a character string is supplied, then a
  function by that name must be defined.  If a function is supplied,
  it is used as the method.  When the method is specified as a name,
  explicitly or implicitly, the function lookup is handled lazily;
  this allows the definition to occur after the \code{.S3method}
  declaration and also integrates with possible data base storage of
  package code.
}
\examples{
\dontrun{
## code for package/name space 'foo'
x <- 1
f <- function(y) c(x,y)
print.foo <- function(x, ...) cat("<a foo>\n")
.Export(f)
S3method(print,foo)

## code for package/name space 'bar'
.Import(foo)
c <- function(...) sum(...)
g <- function(y) f(c(y, 7))
h <- function(y) y+9
.Export(g, h)
}
}
\keyword{internal}
\author{Luke Tierney}
\eof
\name{ns-dblcolon}
\title{Double Colon and Triple Colon Operators}
\alias{::}
\alias{:::}
\description{
  Accessing exported and internal variables in a name space.
}
\usage{
pkg::name
pkg:::name
}
\arguments{
  \item{pkg}{package name symbol or literal character string.}
  \item{name}{variable name symbol or literal character string.}
}
\details{
  The expression \code{pkg::name} returns the value of the exported
  variable \code{name} in package \code{pkg} if the package has a name
  space.  The expression \code{pkg:::name} returns the value of the
  internal variable \code{name} in package \code{pkg} if the package has
  a name space.  The package will be loaded if it was not loaded already
  before the call.  Assignment into name spaces is not supported.
}
\examples{
base::log
base::"+"
}
\keyword{programming}
\eof
\name{ns-internals}
\title{Name Space Internals}

\alias{asNamespace}
\alias{getNamespaceInfo}
\alias{importIntoEnv}
\alias{isBaseNamespace}
\alias{isNamespace}
\alias{namespaceExport}
\alias{namespaceImport}
\alias{namespaceImportClasses}
\alias{namespaceImportFrom}
\alias{namespaceImportMethods}
\alias{packageHasNamespace}
\alias{parseNamespaceFile}
\alias{registerS3method}
\alias{setNamespaceInfo}
\alias{.__S3MethodsTable__.}
\alias{.mergeExportMethods}
\usage{
asNamespace(ns, base.OK = TRUE)
getNamespaceInfo(ns, which)
importIntoEnv(impenv, impnames, expenv, expnames)
isBaseNamespace(ns)
namespaceExport(ns, vars)
namespaceImport(self, \dots)
namespaceImportFrom(self, ns, vars)
namespaceImportClasses(self, ns, vars)
namespaceImportMethods(self, ns, vars)
packageHasNamespace(package, package.lib)
parseNamespaceFile(package, package.lib, mustExist = TRUE)
registerS3method(genname, class, method, envir = parent.frame())
setNamespaceInfo(ns, which, val)
.mergeExportMethods(new, ns)
}

\arguments{
  \item{ns}{string or name space environment.}
  \item{base.OK}{logical.}
  \item{impenv}{environment.}
  \item{expenv}{name space environment.}
  \item{vars}{character vector.}
  \item{self}{name space environment.}
  \item{package}{string naming the package/name space to load.}
  \item{package.lib}{character vector specifying library.}
  \item{mustExist}{logical.}
  \item{genname}{character.}
  \item{class}{character.}
  \item{envir}{environment.}
  \item{which}{character.}
  \item{val}{any object.}
  \item{\dots}{character arguments.}
}
\description{
  Internal name space support functions.  Not intended to be called directly.
}
\keyword{internal}
\author{Luke Tierney}
\eof
\name{ns-lowlev}
\title{Low Level Name Space Support Functions}

\alias{attachNamespace}
\alias{loadNamespace}
\alias{loadedNamespaces}
\alias{unloadNamespace}
\alias{.onLoad}
\alias{.onUnload}
\alias{.onAttach}
\alias{loadingNamespaceInfo}
\alias{saveNamespaceImage}

\usage{
attachNamespace(ns, pos = 2)
loadNamespace(package, lib.loc = NULL,
              keep.source = getOption("keep.source.pkgs"),
              partial = FALSE, declarativeOnly = FALSE)
loadedNamespaces()
unloadNamespace(ns)
loadingNamespaceInfo()
saveNamespaceImage(package, rdafile, lib.loc = NULL,
                   keep.source = getOption("keep.source.pkgs"))
}
\arguments{
  \item{ns}{string or namespace object.}
  \item{pos}{integer specifying position to attach.}
  \item{package}{string naming the package/name space to load.}
  \item{lib.loc}{character vector specifying library search path.}
  \item{keep.source}{logical specifying whether to retain source.}
  \item{partial}{logical; if true, stop just after laoding code.}
  \item{declarativeOnly}{logical; disables \code{.Import}, etc, if true.}
}
\description{
  Low level name space support functions.
}
\details{
  The functions \code{loadNamespace} and \code{attachNamespace} are
  usually called implicitly when \code{library} is used to load a name
  space and any imports needed.  However it may be useful to call
  these functions directly at times.

  \code{loadNamespace} loads the specified name space and registers it in
  an internal data base.  A request to load a name space that is already
  loaded has no effect.  The arguments have the same meaning as the
  corresponding arguments to \code{library}.  After loading,
  \code{loadNamespace} looks for a hook function named \code{.onLoad} as 
  an internal variable in the name space (it should not be exported).
  This function is called with the same arguments as
  \code{.First.lib}.  Partial loading is used so support installation with
  the \option{--save} option.

  \code{loadNamespace} does not attach the name space it loads to the
  search path.  \code{attachNamespace} can be used to attach a frame
  containing the exported values of a name space to the search path.
  The hook function \code{.onAttach} is run after the name space
  exports are attached, but this is not likely to be useful.  Shared
  library loading and setting of options should be handled at load
  time by the \code{.onLoad} hook.

  \code{loadedNamespaces} returns a character vector of the names of
  the loaded name spaces.

  \code{unloadNamespace} can be used to force
  a name space to be unloaded.  An error is signaled if the name space
  is imported by other loaded name spaces.  If defined, a hook
  function \code{.onUnload}, analogous to \code{.Last.lib}, is run
  before removing the name space from the internal registry.
  \code{unloadNamespace} will first \code{\link{detach}} a package of
  the same name if one is on the path, thereby running a
  \code{.Last.lib} function in the package if one is exported.

  \code{loadingNamespaceInfo} returns a list of the arguments that
  would be passed to \code{.onLoad} when a name space is being loaded.
  An error is signaled of a name space is not currently being loaded.

  \code{saveNamespaceImage} is used to save name space images for
  packages installed with \option{--save}.
}
\keyword{internal}
\author{Luke Tierney}
\eof
\name{ns-reflect.Rd}
\title{Name Space Reflection Support}

\alias{getExportedValue}
\alias{getNamespace}
\alias{getNamespaceExports}
\alias{getNamespaceImports}
\alias{getNamespaceName}
\alias{getNamespaceUsers}
\alias{getNamespaceVersion}

\usage{
getExportedValue(ns, name)
getNamespace(name)
getNamespaceExports(ns)
getNamespaceImports(ns)
getNamespaceName(ns)
getNamespaceUsers(ns)
getNamespaceVersion(ns)
}
\arguments{
  \item{ns}{string or name space object.}
  \item{name}{string or name.}
}
\description{
  Functions to support reflection on name space objects.
}
\details{
  \code{getExportedValue} returns the value of the exported variable
  \code{name} in name space \code{ns}.

  \code{getNamespace} returns the environment representing the name
  space \code{name}.  The name space is loaded if necessary.

  \code{getNamespaceExports} returns a character vector of the names
  exported by \code{ns}.

  \code{getNamespaceImports} returns a representation of the imports
  used by name space \code{ns}.  This representation is experimental
  and subject to change.

  \code{getNamespaceName} and \code{getNamespaceVersion} return the name
  and version of the name space \code{ns}.

  \code{getNamespaceUsers} returns a character vector of the names of
  the name spaces that import name space \code{ns}.
}
\keyword{internal}
\author{Luke Tierney}
\eof
\name{ns-topenv}
\title{Top Level Environment}
\alias{topenv}
\description{
  Finding the top level environment.
}
\usage{
topenv(envir = parent.frame(), matchThisEnv = getOption("topLevelEnvironment"))
}
\arguments{
  \item{envir}{environment.}

  \item{matchThisEnv}{return this environment, if it matches before
      any other criterion is satisfied.  The default, the option
      \dQuote{topLevelEnvironment}, is set by \code{\link{sys.source}},
      which treats a specific environment as the top level environment.
      Supplying the argument as \code{NULL} means it will never match.}
}
\details{
  \code{topenv} returns the first top level environment found when
  searching \code{envir} and its parent environments.  An environment is
  considered top level if it is the internal environment of a name space,
  a package environment in the search path, or \code{.GlobalEnv}.
}
\examples{
topenv(.GlobalEnv)
topenv(new.env())
}
\keyword{programming}
\eof
\name{numeric}
\title{Numeric Vectors}
\alias{numeric}
\alias{as.numeric}
\alias{is.numeric}
\usage{
numeric(length = 0)
as.numeric(x, \dots)
is.numeric(x)
}
\arguments{
  \item{length}{desired length.}
  \item{x}{object to be coerced or tested.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\description{
  \code{numeric} creates a real vector of the specified length.  The
  elements of the vector are all equal to \code{0}.

  \code{as.numeric} attempts to coerce its argument to numeric type
  (either integer or real).

  \code{is.numeric} returns \code{TRUE} if its argument is of type real
  or type integer and \code{FALSE} otherwise.
}
\details{
  \code{is.numeric} is  generic: you can write methods to handle
  of specific classes of objects, see \link{InternalMethods}.

  Note that factors are false for \code{is.numeric} but true for
  \code{\link{is.integer}}.
}

\note{
  \emph{\R has no single precision data type.  All real numbers are
    stored in double precision format}. While \code{as.numeric} is a
  generic function, user methods must be written for \code{as.double},
  which it calls

  \code{as.numeric} for factors yields the codes underlying the factor
    levels, not the numeric representation of the labels.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
as.numeric(c("-.1"," 2.7 ","B")) # (-0.1, 2.7, NA)  +  warning
as.numeric(factor(5:10))
}
\keyword{classes}
\keyword{attribute}
\eof
\name{object.size}
\alias{object.size}
\title{Report the Space Allocated for an Object}
\description{
  Provides an estimate of the memory that is being used to store an \R object.
}
\usage{
object.size(x)
}
\arguments{
  \item{x}{An \R object.}
}
\details{
  Exactly which parts of the memory allocation should be attributed
  to which object is not clear-cut.  This function merely provides
  a rough indication.  For example, it will not detect if character
  storage for character strings are shared between identical elements
  (which it will be if \code{rep} was used, for example).

  The calculation is of the size of the object, and excludes the space
  needed to store its name in the symbol table.

}
\value{
  An estimate of the memory allocation attributable to the object, in bytes.
}

\examples{
object.size(letters)
object.size(ls)
## find the 10 largest objects in base
z <- sapply(ls("package:base"), function(x) object.size(get(x, envir=NULL)))
as.matrix(rev(sort(z))[1:10])
}
\keyword{utilities}
\eof
\name{octmode}
\alias{format.octmode}
\alias{print.octmode}
\alias{as.character.octmode}
\title{Display Numbers in Octal}
\description{
  Convert or print integers in octal format, with as many digits as are
  needed to display the largest, using leading zeroes as necessary.
}
\usage{
\method{as.character}{octmode}(x, \dots)
\method{format}{octmode}(x, \dots)
\method{print}{octmode}(x, \dots)
}
\arguments{
  \item{x}{An object inheriting from class \code{"octmode"}.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\details{
  Class \code{"octmode"} consists of integer vectors with that class
  attribute, used merely to ensure that they are printed in octal
  notation, specifically for Unix-like file permissions such as
  \code{755}.
}
\seealso{
  These are auxiliary functions for \code{\link{file.info}}
}
\keyword{print}
\eof
\name{offset}
\title{Include an Offset in a Model Formula}
\usage{
offset(object)
}
\alias{offset}
\arguments{
 \item{object}{An offset to be included in a model frame}
}
\description{
  An offset is a term to be added to a linear predictor, such as in a
  generalised linear model, with known coefficient 1 rather than an
  estimated coefficient.
}
\value{
  The input value.
}

\seealso{
  \code{\link{model.offset}}, \code{\link{model.frame}}.
  
  For examples see \code{\link{glm}}, \code{\link[MASS]{Insurance}}.
}
\keyword{models}
\eof
\name{on.exit}
\alias{on.exit}
\title{Function Exit Code}
\description{
  \code{on.exit} records the expression given as its argument as needing
  to be executed when the current function exits (either naturally or as
  the result of an error).  This is useful for resetting graphical
  parameters or performing other cleanup actions.

  If no expression is provided, i.e., the call is \code{on.exit()}, then
  the current \code{on.exit} code is removed.
}
\usage{
on.exit(expr, add = FALSE)
}
\arguments{
  \item{expr}{an expression to be executed.}
  \item{add}{if TRUE, add \code{expr} to be executed after any previously
    set expressions.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{sys.on.exit}} to see the current expression.
}
\examples{
opar <- par(mai = c(1,1,1,1))
on.exit(par(opar))
\dontshow{par(opar)}
}
\keyword{programming}
\eof
\name{optim}
\alias{optim}
\title{General-purpose Optimization}
\description{
  General-purpose optimization based on Nelder--Mead, quasi-Newton and
  conjugate-gradient algorithms. It includes an option for
  box-constrained optimization and simulated annealing.
}
\usage{
optim(par, fn, gr = NULL,
      method = c("Nelder-Mead", "BFGS", "CG", "L-BFGS-B", "SANN"),
      lower = -Inf, upper = Inf,
      control = list(), hessian = FALSE, \dots)
}
\arguments{
 \item{par}{Initial values for the parameters to be optimized over.}
 \item{fn}{A function to be minimized (or maximized), with first
   argument the vector of parameters over which minimization is to take
   place. It should return a scalar result.}
 \item{gr}{A function to return the gradient for the \code{"BFGS"},
   \code{"CG"} and \code{"L-BFGS-B"} methods.  If it is \code{NULL}, a
   finite-difference approximation will be used.

   For the \code{"SANN"} method it specifies a function to generate a new
   candidate point.  If it is \code{NULL} a default Gaussian Markov
   kernel is used.
 }
 \item{method}{The method to be used. See \bold{Details}.}
 \item{lower, upper}{Bounds on the variables for the \code{"L-BFGS-B"} method.}
 \item{control}{A list of control parameters. See \bold{Details}.}
 \item{hessian}{Logical. Should a numerically differentiated Hessian
   matrix be returned?}
 \item{\dots}{Further arguments to be passed to \code{fn} and \code{gr}.}
}
\details{
  By default this function performs minimization, but it will maximize
  if \code{control$fnscale} is negative.

  The default method is an implementation of that of Nelder and Mead
  (1965), that uses only function values and is robust but relatively
  slow. It will work reasonably well for non-differentiable functions.

  Method \code{"BFGS"} is a quasi-Newton method (also known as a variable
  metric algorithm), specifically that published simultaneously in 1970
  by Broyden, Fletcher, Goldfarb and Shanno. This uses function values
  and gradients to build up a picture of the surface to be optimized.

  Method \code{"CG"} is a conjugate gradients method based on that by
  Fletcher and Reeves (1964) (but with the option of Polak--Ribiere or
  Beale--Sorenson updates).  Conjugate gradient methods will generally
  be more fragile that the BFGS method, but as they do not store a
  matrix they may be successful in much larger optimization problems.

  Method \code{"L-BFGS-B"} is that of Byrd \emph{et. al.} (1994) which
  allows \emph{box constraints}, that is each variable can be given a lower
  and/or upper bound. The initial value must satisfy the constraints.
  This uses a limited-memory modification of the BFGS quasi-Newton
  method. If non-trivial bounds are supplied, this method will be
  selected, with a warning.

  Nocedal and Wright (1999) is a comprehensive reference for the
  previous three methods.
  
  Method \code{"SANN"} is by default a variant of simulated annealing
  given in Belisle (1992). Simulated-annealing belongs to the class of
  stochastic global optimization methods. It uses only function values
  but is relatively slow. It will also work for non-differentiable
  functions. This implementation uses the Metropolis function for the
  acceptance probability. By default the next candidate point is
  generated from a Gaussian Markov kernel with scale proportional to the
  actual temperature. If a function to generate a new candidate point is
  given, method \code{"SANN"} can also be used to solve combinatorial
  optimization problems. Temperatures are decreased according to the
  logarithmic cooling schedule as given in Belisle (1992, p. 890). Note
  that the \code{"SANN"} method depends critically on the settings of
  the control parameters. It is not a general-purpose method but can be 
  very useful in getting to a good value on a very rough surface.

  Function \code{fn} can return \code{NA} or \code{Inf} if the function
  cannot be evaluated at the supplied value, but the initial value must
  have a computable finite value of \code{fn}.
  (Except for method \code{"L-BFGS-B"} where the values should always be
  finite.)

  \code{optim} can be used recursively, and for a single parameter
  as well as many.

  The \code{control} argument is a list that can supply any of the
  following components:
  \describe{
    \item{\code{trace}}{Non-negative integer. If positive,
      tracing information on the
      progress of the optimization is produced. Higher values may
      produce more tracing information: for method \code{"L-BFGS-B"}
      there are six levels of tracing.  (To understand exactly what
      these do see the source code: higher levels give more detail.)}
    \item{\code{fnscale}}{An overall scaling to be applied to the value
      of \code{fn} and \code{gr} during optimization. If negative,
      turns the problem into a maximization problem. Optimization is
      performed on \code{fn(par)/fnscale}.}
    \item{\code{parscale}}{A vector of scaling values for the parameters.
	Optimization is performed on \code{par/parscale} and these should be
	comparable in the sense that a unit change in any element produces
	about a unit change in the scaled value.}
    \item{\code{ndeps}}{A vector of step sizes for the finite-difference
      approximation to the gradient, on \code{par/parscale}
      scale. Defaults to \code{1e-3}.}
    \item{\code{maxit}}{The maximum number of iterations. Defaults to
      \code{100} for the derivative-based methods, and
      \code{500} for \code{"Nelder-Mead"}. For \code{"SANN"}
      \code{maxit} gives the total number of function evaluations. There is
      no other stopping criterion. Defaults to \code{10000}.}
    \item{\code{abstol}}{The absolute convergence tolerance. Only
      useful for non-negative functions, as a tolerance for reaching zero.}
    \item{\code{reltol}}{Relative convergence tolerance.  The algorithm
      stops if it is unable to reduce the value by a factor of
      \code{reltol * (abs(val) + reltol)} at a step.  Defaults to
      \code{sqrt(.Machine$double.eps)}, typically about \code{1e-8}.}
    \item{\code{alpha}, \code{beta}, \code{gamma}}{Scaling parameters
      for the \code{"Nelder-Mead"} method. \code{alpha} is the reflection
      factor (default 1.0), \code{beta} the contraction factor (0.5) and
      \code{gamma} the expansion factor (2.0).}
    \item{\code{REPORT}}{The frequency of reports for the \code{"BFGS"}
      and \code{"L-BFGS-B"} methods if \code{control$trace} is positive.
      Defaults to every 10 iterations.}
    \item{\code{type}}{for the conjugate-gradients method. Takes value
      \code{1} for the Fletcher--Reeves update, \code{2} for
      Polak--Ribiere and \code{3} for Beale--Sorenson.}
    \item{\code{lmm}}{is an integer giving the number of BFGS updates
      retained in the \code{"L-BFGS-B"} method, It defaults to \code{5}.}
    \item{\code{factr}}{controls the convergence of the \code{"L-BFGS-B"}
      method. Convergence occurs when the reduction in the objective is
      within this factor of the machine tolerance. Default is \code{1e7},
      that is a tolerance of about \code{1e-8}.}
    \item{\code{pgtol}}{helps controls the convergence of the \code{"L-BFGS-B"}
      method. It is a tolerance on the projected gradient in the current
      search direction. This defaults to zero, when the check is
      suppressed.}
    \item{\code{temp}}{controls the \code{"SANN"} method. It is the
      starting temperature for the cooling schedule. Defaults to
      \code{10}.}
    \item{\code{tmax}}{is the number of function evaluations at each
      temperature for the \code{"SANN"} method. Defaults to \code{10}.}
  }
}
\value{
  A list with components:
  \item{par}{The best set of parameters found.}
  \item{value}{The value of \code{fn} corresponding to \code{par}.}
  \item{counts}{A two-element integer vector giving the number of calls
    to \code{fn} and \code{gr} respectively. This excludes those calls needed
    to compute the Hessian, if requested, and any calls to \code{fn} to
    compute a finite-difference approximation to the gradient.}
  \item{convergence}{An integer code. \code{0} indicates successful
    convergence. Error codes are
    \describe{
      \item{\code{1}}{indicates that the iteration limit \code{maxit}
      had been reached.}
      \item{\code{10}}{indicates degeneracy of the Nelder--Mead simplex.}
      \item{\code{51}}{indicates a warning from the \code{"L-BFGS-B"}
      method; see component \code{message} for further details.}
      \item{\code{52}}{indicates an error from the \code{"L-BFGS-B"}
      method; see component \code{message} for further details.}
    }
  }
  \item{message}{A character string giving any additional information
    returned by the optimizer, or \code{NULL}.}
  \item{hessian}{Only if argument \code{hessian} is true. A symmetric
    matrix giving an estimate of the Hessian at the solution found. Note
    that this is the Hessian of the unconstrained problem even if the
    box constraints are active.}
}
\references{
  Belisle, C. J. P. (1992) Convergence theorems for a class of simulated
  annealing algorithms on \eqn{R^d}{Rd}. \emph{J Applied Probability},
  \bold{29}, 885--895.

  Byrd, R. H., Lu, P., Nocedal, J. and Zhu, C.  (1995) A limited
  memory algorithm for bound constrained optimization.
  \emph{SIAM J. Scientific Computing}, \bold{16}, 1190--1208.

  Fletcher, R. and Reeves, C. M. (1964) Function minimization by
  conjugate gradients. \emph{Computer Journal} \bold{7}, 148--154.
  
  Nash, J. C. (1990) \emph{Compact Numerical Methods for
    Computers. Linear Algebra and Function Minimisation.} Adam Hilger.

  Nelder, J. A. and Mead, R. (1965) A simplex algorithm for function
  minimization. \emph{Computer Journal} \bold{7}, 308--313.

  Nocedal, J. and Wright, S. J. (1999) \emph{Numerical Optimization}.
  Springer.
}
\note{
  \code{optim} will work with one-dimensional \code{par}s, but the
  default method does not work well (and will warn).  Use
  \code{\link{optimize}} instead.
  
  The code for methods \code{"Nelder-Mead"}, \code{"BFGS"} and
  \code{"CG"} was based originally on Pascal code in Nash (1990) that was
  translated by \code{p2c} and then hand-optimized.  Dr Nash has agreed
  that the code can be made freely available.

  The code for method \code{"L-BFGS-B"} is based on Fortran code by Zhu,
  Byrd, Lu-Chen and Nocedal obtained from Netlib (file
  \file{opt/lbfgs\_bcm.shar}: another version is in \file{toms/778}).

  The code for method \code{"SANN"} was contributed by A. Trapletti.
}

\seealso{\code{\link{nlm}}, \code{\link{optimize}}, \code{\link{constrOptim}}}

\examples{
fr <- function(x) {   ## Rosenbrock Banana function
    x1 <- x[1]
    x2 <- x[2]
    100 * (x2 - x1 * x1)^2 + (1 - x1)^2
}
grr <- function(x) { ## Gradient of 'fr'
    x1 <- x[1]
    x2 <- x[2]
    c(-400 * x1 * (x2 - x1 * x1) - 2 * (1 - x1),
       200 *      (x2 - x1 * x1))
}
optim(c(-1.2,1), fr)
optim(c(-1.2,1), fr, grr, method = "BFGS")
optim(c(-1.2,1), fr, NULL, method = "BFGS", hessian = TRUE)
optim(c(-1.2,1), fr, grr, method = "CG")
optim(c(-1.2,1), fr, grr, method = "CG", control=list(type=2))
optim(c(-1.2,1), fr, grr, method = "L-BFGS-B")

flb <- function(x)
    { p <- length(x); sum(c(1, rep(4, p-1)) * (x - c(1, x[-p])^2)^2) }
## 25-dimensional box constrained
optim(rep(3, 25), flb, NULL, "L-BFGS-B",
      lower=rep(2, 25), upper=rep(4, 25)) # par[24] is *not* at boundary

## "wild" function , global minimum at about -15.81515
fw <- function (x)
    10*sin(0.3*x)*sin(1.3*x^2) + 0.00001*x^4 + 0.2*x+80
plot(fw, -50, 50, n=1000, main = "optim() minimising 'wild function'")

res <- optim(50, fw, method="SANN",
             control=list(maxit=20000, temp=20, parscale=20))
res
## Now improve locally
(r2 <- optim(res$par, fw, method="BFGS"))
points(r2$par, r2$val, pch = 8, col = "red", cex = 2)

## Combinatorial optimization: Traveling salesman problem
library(mva) # normally loaded
library(ts)  # for embed, normally loaded

data(eurodist)
eurodistmat <- as.matrix(eurodist)

distance <- function(sq) {  # Target function
    sq2 <- embed(sq, 2)
    return(sum(eurodistmat[cbind(sq2[,2],sq2[,1])]))
}

genseq <- function(sq) {  # Generate new candidate sequence 
    idx <- seq(2, NROW(eurodistmat)-1, by=1)
    changepoints <- sample(idx, size=2, replace=FALSE)
    tmp <- sq[changepoints[1]]
    sq[changepoints[1]] <- sq[changepoints[2]]
    sq[changepoints[2]] <- tmp
    return(sq)
}

sq <- c(1,2:NROW(eurodistmat),1)  # Initial sequence
distance(sq)

set.seed(2222) # chosen to get a good soln quickly
res <- optim(sq, distance, genseq, method="SANN",
             control = list(maxit=6000, temp=2000, trace=TRUE))
res  # Near optimum distance around 12842

loc <- cmdscale(eurodist)
rx <- range(x <- loc[,1])
ry <- range(y <- -loc[,2])
tspinit <- loc[sq,]
tspres <- loc[res$par,]
s <- seq(NROW(tspres)-1)

plot(x, y, type="n", asp=1, xlab="", ylab="",
     main="initial solution of traveling salesman problem")
arrows(tspinit[s,1], -tspinit[s,2], tspinit[s+1,1], -tspinit[s+1,2],
       angle=10, col="green") 
text(x, y, names(eurodist), cex=0.8)

plot(x, y, type="n", asp=1, xlab="", ylab="",
     main="optim() 'solving' traveling salesman problem") 
arrows(tspres[s,1], -tspres[s,2], tspres[s+1,1], -tspres[s+1,2],
       angle=10, col="red")
text(x, y, names(eurodist), cex=0.8)
}}
\keyword{nonlinear}
\keyword{optimize}
\eof
\name{optimize}
\title{One Dimensional Optimization}
\usage{
optimize(f = , interval = , lower = min(interval),
        upper = max(interval), maximum = FALSE,
        tol = .Machine$double.eps^0.25, \dots)
optimise(f = , interval = , lower = min(interval),
        upper = max(interval), maximum = FALSE,
        tol = .Machine$double.eps^0.25, \dots)
}
\alias{optimize}
\alias{optimise}
\arguments{
  \item{f}{the function to be optimized. The function is
    either minimized or maximized over its first argument
    depending on the value of \code{maximum}.}
  \item{interval}{a vector containing the end-points of the interval
    to be searched for the minimum.}
  \item{lower}{the lower end point of the interval
    to be searched.}
  \item{upper}{the upper end point of the interval
    to be searched.}
  \item{maximum}{logical. Should we maximize or minimize (the default)?}
  \item{tol}{the desired accuracy.}
  \item{\dots}{additional arguments to \code{f}.}
}
\description{
  The function \code{optimize} searches the interval from
  \code{lower} to \code{upper} for a minimum or maximum of
  the function \code{f} with respect to its first argument.

  \code{optimise} is an alias for \code{optimize}.
}
\details{
  The method used is a combination of golden section search and
  successive parabolic interpolation.  Convergence is never much slower
  than that for a Fibonacci search.  If \code{f} has a continuous second
  derivative which is positive at the minimum (which is not at \code{lower} or
  \code{upper}), then convergence is superlinear, and usually of the
  order of about 1.324.

  The function \code{f} is never evaluated at two points closer together
  than \eqn{\epsilon}{eps *}\eqn{ |x_0| + (tol/3)}, where
  \eqn{\epsilon}{eps} is approximately \code{sqrt(\link{.Machine}$double.eps)}
  and \eqn{x_0} is the final abscissa \code{optimize()$minimum}.\cr
  If \code{f} is a unimodal function and the computed values of \code{f}
  are always unimodal when separated by at least \eqn{\epsilon}{eps *}
  \eqn{ |x| + (tol/3)}, then \eqn{x_0} approximates the abcissa of the
  global minimum of \code{f} on the interval \code{lower,upper} with an
  error less than \eqn{\epsilon}{eps *}\eqn{ |x_0|+ tol}.\cr
  If \code{f} is not unimodal, then \code{optimize()} may approximate a
  local, but perhaps non-global, minimum to the same accuracy.

  The first evaluation of \code{f} is always at
  \eqn{x_1 = a + (1-\phi)(b-a)} where \code{(a,b) = (lower, upper)} and
  \eqn{\phi = (\sqrt 5 - 1)/2 = 0.61803..} is the golden section ratio.
  Almost always, the second evaluation is at \eqn{x_2 = a + \phi(b-a)}.
  Note that a local minimum inside \eqn{[x_1,x_2]} will be found as
  solution, even when \code{f} is constant in there, see the last
  example.

  It uses a C translation of Fortran code (from Netlib) based on the
  Algol 60 procedure \code{localmin} given in the reference.
}
\value{
  A list with components \code{minimum} (or \code{maximum})
  and \code{objective} which give the location of the minimum (or maximum)
  and the value of the function at that point.
}
\references{
  Brent, R. (1973)
  \emph{Algorithms for Minimization without Derivatives.}
  Englewood Cliffs N.J.: Prentice-Hall.
}
\seealso{
  \code{\link{nlm}}, \code{\link{uniroot}}.
}
\examples{
f <- function (x,a) (x-a)^2
xmin <- optimize(f, c(0, 1), tol = 0.0001, a = 1/3)
xmin

## See where the function is evaluated:
optimize(function(x) x^2*(print(x)-1), l=0, u=10)

## "wrong" solution with unlucky interval and piecewise constant f():
f  <- function(x) ifelse(x > -1, ifelse(x < 4, exp(-1/abs(x - 1)), 10), 10)
fp <- function(x) { print(x); f(x) }

plot(f, -2,5, ylim = 0:1, col = 2)
optimize(fp, c(-4, 20))# doesn't see the minimum
optimize(fp, c(-7, 20))# ok
}
\keyword{optimize}
\eof
\name{options}
\alias{options}
\alias{.Options}
\alias{getOption}
\title{Options Settings}
\description{
  Allow the user to set and examine a variety of global \dQuote{options}
  which affect the way in which \R computes and displays its results.
}
\usage{
options(\dots)
getOption(x)
.Options
}
%%-- NOTE : Keep the list up-to-date,
%%-- ====   Consider also the leading comments in ../../../main/options.c
\arguments{
  \item{\dots}{any options can be defined, using \code{name = value}.

    However, only the ones below are used in \dQuote{base \R}.

    Further, \code{options('name') == options()['name']}, see the example.
  }
  \item{x}{a character string holding an option name.}
}
\details{
  Invoking \code{options()} with no arguments returns a list with the
  current values of the options.  Note that not all options listed below
  are set initially.  To access the value of a single option, one should
  use \code{getOption("width")}, e.g., rather than
  \code{options("width")} which is a \emph{list} of length one.

  \code{.Options} also always contains the \code{options()} list, for
  S compatibility.  You must use it \dQuote{read only} however.
}
\value{
  For \code{options}, a list (in any case) with the previous values of
  the options changed, or all options when no arguments were given.
}
\section{Options used in base \R}{
  \describe{
    \item{\code{prompt}:}{a string, used for \R's prompt; should usually
      end in a blank (\code{" "}).}

    \item{\code{continue}:}{a string setting the prompt used for lines
      which continue over one line.}

    \item{\code{width}:}{controls the number of characters on a line.
      You may want to change this if you re-size the window that \R is
      running in.  Valid values are 10\dots10000 with default normally
      80.  (The valid values are in file \file{Print.h} and can be
      changed by re-compiling \R.)}

    \item{\code{digits}:}{controls the number of digits to print when
      printing numeric values.  It is a suggestion only.  Valid values
      are 1\dots22 with default 7.  See \code{\link{print.default}}.}

    \item{\code{editor}:}{sets the default text editor, e.g., for
      \code{\link{edit}}.  Set from the environment variable
      \code{VISUAL} on UNIX.}

    \item{\code{pager}:}{the (stand-alone) program used for displaying
      ASCII files on \R's console.
#ifdef unix
      Defaults to \file{\$R\_HOME/bin/pager}.
#endif
#ifdef windows
      Defaults to \code{"internal"}, which uses a pager similar to the
      GUI console.  Another possibility is \code{"console"} to use the
      console itself.
#endif
    }

    \item{\code{browser}:}{default HTML browser used by
      \code{\link{help.start}()} on UNIX, or a non-default browser on
      Windows.}

#ifdef unix
    \item{\code{pdfviewer}:}{default PDF viewer.  Set from the
      environment variable \env{R\_PDFVIEWER}.}
#endif

    \item{\code{mailer}:}{default mailer used by
      \code{\link{bug.report}()}.  Can be \code{"none"}.}

    \item{\code{contrasts}:}{the default \code{\link{contrasts}} used in
      model fitting such as with \code{\link{aov}} or \code{\link{lm}}.
      A character vector of length two, the first giving the function to
      be used with unordered factors and the second the function to be
      used with ordered factors.}

    \item{\code{defaultPackages}:}{the packages that are attached by
      default when \R starts up.  Initially set from value of the
      environment variables \env{R\_DefaultPackages}, or if that is unset
      %%  default is set in ../../profile/Common.R :
      to \code{c("ts", "nls", "modreg", "mva", "ctest", "methods")}.  (Set
      \env{R\_DEFAULT\_PACKAGES} to \code{NULL} or a comma-separated list
      of package names.)  A call to \code{options} should be in your
      \file{.Rprofile} file to ensure that the change takes effect
      before the base package is initialized (see \code{\link{Startup}}).}

    \item{\code{expressions}:}{sets a limit on the number of nested
      expressions that will be evaluated.
      Valid values are 25\dots100000 with default 500.}

    \item{\code{keep.source}:}{When \code{TRUE}, the source code for
      functions (newly defined or loaded) is stored in their
      \code{"source"} attribute (see \code{\link{attr}}) allowing
      comments to be kept in the right places.

      The default is \code{\link{interactive}()}, i.e., \code{TRUE} for
      interactive use.}

    \item{\code{keep.source.pkgs}:}{As for \code{keep.source}, for
      functions in packages loaded by \code{\link{library}} or
      \code{\link{require}}.  Defaults to \code{FALSE} unless the
      environment variable \env{R\_KEEP\_PKG\_SOURCE} is set to
      \code{yes}.}

    \item{\code{na.action}:}{the name of a function for treating missing
      values (\code{\link{NA}}'s) for certain situations.}

    \item{\code{papersize}:}{the default paper format used by
      \code{\link{postscript}};  set by environment variable
      \env{R\_PAPERSIZE} when \R is started and defaulting to
      \code{"a4"} if that is unset or invalid.}

    \item{\code{printcmd}:}{the command used by \code{\link{postscript}}
      for printing; set by environment variable \env{R\_PRINTCMD} when
      \R is started.  This should be a command that expects either input
      to be piped to \file{stdin} or to be given a single filename
      argument.
#ifdef windows
      See \code{\link{postscript}} for ways to set this up.
#endif
    }

#ifdef unix
    \item{\code{latexcmd, dvipscmd}:}{character strings giving commands
      to be used in off-line printing of help pages.}
#endif

    \item{\code{show.signif.stars, show.coef.Pvalues}:}{logical,
      affecting P value printing, see \code{\link{print.coefmat}}.}

    \item{\code{ts.eps}:}{the relative tolerance for certain time series
      (\code{\link{ts}}) computations.}

    \item{\code{error}:}{either a function or an expression governing
      the handling of non-catastrophic errors such as those generated by
      \code{\link{stop}} as well as by signals and internally detected
      errors.  If the option is a function, a call to that function,
      with no arguments, is generated as the expression.  The default
      value is \code{NULL}: see \code{\link{stop}} for the behaviour in
      that case.  The function \code{\link{dump.frames}} provides one
      alternative that allows post-mortem debugging.}

    \item{\code{show.error.messages}:}{a logical.  Should error messages
      be printed?  Intended for use with \code{\link{try}} or a
      user-installed error handler.}

    \item{\code{warn}:}{sets the handling of warning messages.  If
      \code{warn} is negative all warnings are ignored.  If \code{warn}
      is zero (the default) warnings are stored until the top--level
      function returns.  If fewer than 10 warnings were signalled they
      will be printed otherwise a message saying how many (max 50) were
      signalled.  A top--level variable called \code{last.warning} is
      created and can be viewed through the function
      \code{\link{warnings}}.  If \code{warn} is one, warnings are
      printed as they occur.  If \code{warn} is two or larger all
      warnings are turned into errors.}

    \item{\code{warning.length}:}{sets the truncation limit for error
      and warning messages.  A non-negative integer, with allowed values
      100--8192, default 1000.}

    \item{\code{warning.expression}:}{an \R code expression to be called
      if a warning is generated, replacing the standard message.  If
      non-null is called irrespective of the value of option
      \code{warn}.}
#ifdef windows

	\item{\code{warn.FPU}:}{logical, by default undefined.  If true,
	  a \link{warning} is produced whenever \link{dyn.load} repairs the
	  control word damaged by a buggy DLL.}
#endif

    \item{\code{check.bounds}:}{logical, defaulting to \code{FALSE}.  If
      true, a \link{warning} is produced whenever a \dQuote{generalized
      vector} (atomic or \code{\link{list}}) is extended, by something
      like \code{x <- 1:3; x[5] <- 6}.}

    \item{\code{echo}:}{logical.  Only used in non-interactive mode,
      when it controls whether input is echoed.  Command-line option
      \option{--slave} sets this initially to \code{FALSE}.}

    \item{\code{verbose}:}{logical.  Should \R report extra information
      on progress?  Set to \code{TRUE} by the command-line option
      \option{--verbose}.}

    \item{\code{device}:}{a character string giving the default device
      for that session.  This defaults to the normal screen device
      (e.g., \code{x11}, \code{windows} or \code{gtk}) for an
      interactive session, and \code{postscript} in batch use or if a
      screen is not available.}

#ifdef unix
    \item{\code{X11colortype}:}{The default colour type for
      \code{\link{X11}} devices.}
#endif

    \item{\code{CRAN}:}{The URL of the preferred CRAN node for use by
      \code{\link{update.packages}}.  Defaults to
      \url{http://cran.r-project.org}.}

    \item{\code{download.file.method}:}{Method to be used for
      \code{download.file}.  Currently download methods
      \code{"internal"}, \code{"wget"} and \code{"lynx"} are available.
      There is no default for this option, when \code{method = "auto"}
      is chosen: see \code{\link{download.file}}.}

    \item{\code{unzip}:}{the command used for unzipping help files.
#ifdef unix
      Defaults to the value of \env{R\_UNZIPCMD}, which is set in
      \file{etc/Renviron} if an \code{unzip} command was found during
      configuration.}
#endif
#ifdef windows
      Defaults to \code{"internal"} when the internal unzip code is
      used.}
#endif

    \item{\code{de.cellwidth}:}{integer: the cell widths (number of
      characters) to be used in the data editor \code{\link{dataentry}}.
      If this is unset, 0, negative or \code{NA}, variable cell widths
      are used.}

    \item{\code{encoding}:}{An integer vector of length 256 holding an
      input encoding.  Defaults to \code{native.enc} (= \code{0:255}).
      See \code{\link{connections}}.}

    \item{\code{timeout}:}{integer.  The timeout for some Internet
      operations, in seconds.  Default 60 seconds.
      See \code{\link{download.file}} and \code{\link{connections}}.}

    \item{\code{internet.info}:}{The minimum level of information to be
      printed on URL downloads etc.  Default is 2, for failure causes.
      Set to 1 or 0 to get more information.}

    \item{\code{scipen}:}{integer.  A penalty to be applied
      when deciding to print numeric values in fixed or exponential
      notation.  Positive values bias towards fixed and negative towards
      scientific notation: fixed notation will be preferred unless it is
      more than \code{scipen} digits wider.}

    \item{\code{locatorBell}:}{logical.  Should selection in \code{locator}
      and \code{identify} be confirmed by a bell.  Default \code{TRUE}.
      Honoured at least on \code{X11} and \code{windows} devices.}
  }

  The default settings of some of these options are
  \tabular{llll}{
    \code{prompt} \tab \code{"> "} \tab
    \code{continue} \tab \code{"+ "}\cr
    \code{width}  \tab \code{80} \tab
    \code{digits} \tab \code{7}\cr
    \code{expressions} \tab \code{500} \tab
    \code{keep.source} \tab \code{TRUE}\cr
    \code{show.signif.stars} \tab \code{TRUE} \tab
    \code{show.coef.Pvalues} \tab \code{TRUE}\cr
    \code{na.action} \tab \code{na.omit} \tab
    \code{ts.eps} \tab \code{1e-5}\cr
    \code{error} \tab \code{NULL} \tab
    \code{show.error.messags} \tab \code{TRUE} \cr
    \code{warn} \tab \code{0}\tab
    \code{warning.length} \tab \code{1000}\cr
    \code{echo} \tab \code{TRUE} \tab
    \code{verbose} \tab \code{FALSE} \cr
    \code{scipen} \tab \code{0} \tab \code{locatorBell} \tab \code{TRUE}
  }
  Others are set from environment variables or are platform-dependent.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
options() # printing all current options
op <- options(); str(op) # nicer printing

# .Options is the same:
all(sapply(1:length(op), function(i) all(.Options[[i]] == op[[i]])))

options('width')[[1]] == options()$width # the latter needs more memory
options(digits=20)
pi

# set the editor, and save previous value
old.o <- options(editor="nedit")
old.o

options(check.bounds = TRUE)
x <- NULL; x[4] <- "yes" # gives a warning

options(digits=5)
print(1e5)
options(scipen=3); print(1e5)

options(op)     # reset (all) initial options
options('digits')

\dontrun{## set contrast handling to be like S
options(contrasts=c("contr.helmert", "contr.poly"))
}
\dontrun{## on error, terminate the R session with error status 66
options(error=quote(q("no", status=66, runLast=FALSE)))
stop("test it")
}
\dontrun{## set an error action for debugging: see ?debugger.
options(error=dump.frames)
## A possible setting for non-interactive sessions
options(error=quote({dump.frames(to.file=TRUE); q()}))
}}
\keyword{environment}
\keyword{error}
\keyword{print}
\eof
\name{order}
\title{Ordering Permutation}
\alias{order}
\alias{sort.list}
\description{
  \code{order} returns a permutation which rearranges its first
  argument into ascending or descending order, breaking ties by further
  arguments. \code{sort.list} is the same, using only one argument.
}
\usage{
order(\dots, na.last = TRUE, decreasing = FALSE)

sort.list(x, partial = NULL, na.last = TRUE, decreasing = FALSE,
          method = c("shell", "quick", "radix"))
}
\arguments{
  \item{\dots}{a sequence of vectors, all of the same length.}
  \item{x}{a vector.}
  \item{partial}{vector of indices for partial sorting.}
  \item{decreasing}{logical. Should the sort order be increasing or
    decreasing?}
  \item{na.last}{for controlling the treatment of \code{NA}s.
    If \code{TRUE}, missing values in the data are put last; if
    \code{FALSE}, they are put first; if \code{NA}, they are removed.
  }
  \item{method}{the method to be used: partial matches are allowed.}
}
\details{
  In the case of ties in the first vector, values in the second are used
  to break the ties.  If the values are still tied, values in the later
  arguments are used to break the tie (see the first example).
  The sort used is \emph{stable} (except for \code{method = "quick"}),
  so any unresolved ties will be left in their original ordering.

  The default method for \code{sort.list} is a good compromise.
  Method \code{"quick"} is only supported for numeric \code{x} with
  \code{na.last=NA}, and is not stable, but will be faster for long vectors.
  Method \code{"radix"} is only implemented for integer \code{x} with
  a range of less than 100,000.  For such \code{x} it is very
  fast (and stable), and hence is ideal for sorting factors.

  \code{partial} is supplied for compatibility with other
  implementations of S, but no other values are accepted and ordering is
  always complete.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{\code{\link{sort}} and \code{\link{rank}}.}
\examples{
(ii <- order(x <- c(1,1,3:1,1:4,3), y <- c(9,9:1), z <-c(2,1:9)))
## 6  5  2  1  7  4 10  8  3  9
rbind(x,y,z)[,ii] # shows the reordering (ties via 2nd & 3rd arg)

## Suppose we wanted descending order on y. A simple solution is
rbind(x,y,z)[, order(x, -y, z)]
## For character vectors we can make use of rank:
cy <- as.character(y)
rbind(x,y,z)[, order(x, -rank(y), z)]

## rearrange matched vectors so that the first is in ascending order
x <- c(5:1, 6:8, 12:9)
y <- (x - 5)^2
o <- order(x)
rbind(x[o], y[o])

## tests of na.last
a <- c(4, 3, 2, NA, 1)
b <- c(4, NA, 2, 7, 1)
z <- cbind(a, b)
(o <- order(a, b)); z[o, ]
(o <- order(a, b, na.last = FALSE)); z[o, ]
(o <- order(a, b, na.last = NA)); z[o, ]

\dontrun{
##  speed examples for long vectors: timings are immediately after gc()
x <- factor(sample(letters, 1e6, replace=TRUE))
system.time(o <- sort.list(x)) ## 4 secs
stopifnot(!is.unsorted(x[o]))
system.time(o <- sort.list(x, method="quick", na.last=NA)) # 0.4 sec
stopifnot(!is.unsorted(x[o]))
system.time(o <- sort.list(x, method="radix")) # 0.04 sec
stopifnot(!is.unsorted(x[o]))
xx <- sample(1:26, 1e7, replace=TRUE)
system.time(o <- sort.list(xx, method="radix")) # 0.4 sec
xx <- sample(1:100000, 1e7, replace=TRUE)
system.time(o <- sort.list(xx, method="radix")) # 4 sec
}}
\keyword{univar}
\keyword{manip}
\eof
\name{outer}
\alias{outer}
\alias{\%o\%}
\title{Outer Product of Arrays}
\description{
  The outer product of the arrays \code{X} and \code{Y} is the array
  \code{A} with dimension \code{c(dim(X), dim(Y))} where element
  \code{A[c(arrayindex.x, arrayindex.y)]
    = FUN(X[arrayindex.x], Y[arrayindex.y], \dots)}.
}
\usage{
outer(X, Y, FUN="*", \dots)
X \%o\% Y
}

\arguments{
  \item{X}{A vector or array.}
  \item{Y}{A vector or array.}
  \item{FUN}{a function to use on the outer products, it may be a quoted
    string.}
  \item{\dots}{optional arguments to be passed to \code{FUN}.}
}
\details{
  \code{FUN} must be a function (or the name of it) which expects at
  least two arguments and which operates elementwise on arrays.
    
  Where they exist, the [dim]names of \code{X} and \code{Y} will be
  preserved.
    
  \code{\%o\%} is an alias for \code{outer} (where \code{FUN}
  cannot be changed from \code{"*"}).
}
\author{Jonathan Rougier}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{\%*\%}} for usual (\emph{inner}) matrix vector
  multiplication;
  \code{\link{kronecker}} which is based on \code{outer}.
}
\examples{
x <- 1:9; names(x) <- x
# Multiplication & Power Tables
x \%o\% x
y <- 2:8; names(y) <- paste(y,":",sep="")
outer(y, x, "^")

outer(month.abb, 1999:2003, FUN = "paste")

## three way multiplication table:
x \%o\% x \%o\% y[1:3]
}
\keyword{array}
\eof
\name{p.adjust}
\alias{p.adjust}
\alias{p.adjust.methods}
\title{Adjust p-values for multiple comparisons}
\description{Given a set of p-values, returns p-values adjusted using
  one of several methods.}
\usage{
p.adjust(p, method=p.adjust.methods, n=length(p))

p.adjust.methods
}
\arguments{
  \item{p}{vector of p-values}
  \item{method}{correction method}
  \item{n}{number of comparisons}
}
\value{A vector of corrected p-values.}
\details{
  The adjustment methods include the Bonferroni correction
  (\code{"bonferroni"}) in which the p-values are multiplied by the
  number of comparisons.  Four less conservative corrections are also
  included by Holm (1979) (\code{"holm"}), Hochberg (1988)
  (\code{"hochberg"}), Hommel (1988) (\code{"hommel"}) and Benjamini &
  Hochberg (1995) (\code{"fdr"}), respectively.
  A pass-through option (\code{"none"}) is also included.
  The set of methods are contained in the \code{p.adjust.methods} vector
  for the benefit of methods that need to have the method as an option
  and pass it on to \code{p.adjust}.

  The first four methods are designed to give strong control of the
  family wise error rate.  There seems no reason to use the unmodified
  Bonferroni correction because it is dominated by Holm's method, which
  is also valid under arbitrary assumptions.

  Hochberg's and Hommel's methods are valid when the hypothesis tests
  are independent or when they are non-negatively associated (Sarkar,
  1998; Sarkar and Chang, 1997).  Hommel's method is more powerful than
  Hochberg's, but the difference is usually small and the Hochberg
  p-values are faster to compute.

  The \code{"fdr"} method of Benjamini and Hochberg (1995) controls the
  false discovery rate, the expected proportion of false discoveries
  amongst the rejected hypotheses.  The false discovery rate is a less
  stringent condition than the family wise error rate, so Benjamini and
  Hochberg's method is more powerful than the other methods.
}

\references{
  Benjamini, Y., and Hochberg, Y. (1995).
  Controlling the false discovery rate: a practical and powerful
  approach to multiple testing.
  \emph{Journal of the Royal Statistical Society Series} B, \bold{57},
  289--300.

  Holm, S. (1979).
  A simple sequentially rejective multiple test procedure.
  \emph{Scandinavian Journal of Statistics}, \bold{6}, 65--70.

  Hommel, G. (1988).
  A stagewise rejective multiple test procedure based on a modified
  Bonferroni test.
  \emph{Biometrika}, \bold{75}, 383--386.

  Hochberg, Y. (1988).
  A sharper Bonferroni procedure for multiple tests of significance.
  \emph{Biometrika}, \bold{75}, 800--803.

  Shaffer, J. P. (1995).
  Multiple hypothesis testing.
  \emph{Annual Review of Psychology}, \bold{46}, 561--576.
  (An excellent review of the area.)

  Sarkar, S. (1998).
  Some probability inequalities for ordered MTP2 random variables: a
  proof of Simes conjecture.
  \emph{Annals of Statistics}, \bold{26}, 494--504.

  Sarkar, S., and Chang, C. K. (1997).
  Simes' method for multiple hypothesis testing with positively
  dependent test statistics.
  \emph{Journal of the American Statistical Association}, \bold{92},
  1601--1608.

  Wright, S. P. (1992).
  Adjusted P-values for simultaneous inference.
  \emph{Biometrics}, \bold{48}, 1005--1013.
  (Explains the adjusted P-value approach.)
}

\seealso{
  \code{pairwise.*} functions in the \pkg{ctest} package, such
  as \code{\link[ctest]{pairwise.t.test}}.
}

\examples{
x <- rnorm(50, m=c(rep(0,25),rep(3,25)))
p <- 2*pnorm( -abs(x))

round(p, 3)

round(p.adjust(p), 3)
round(p.adjust(p,"bonferroni"), 3)

round(p.adjust(p,"fdr"), 3)
}
\keyword{htest}
\eof
\name{package.contents}
\alias{package.contents}
\alias{package.description}
\title{Package Contents and Description}
\description{
  Parses and returns the \file{CONTENTS} and \file{DESCRIPTION} file of
  a package.
}
\usage{
package.contents(pkg, lib.loc = NULL)
package.description(pkg, lib.loc = NULL, fields = NULL)
}
\arguments{
  \item{pkg}{a character string with the package name.}
  \item{lib.loc}{a character vector describing the location of \R
    library trees to search through, or \code{NULL}.  The default value
    of \code{NULL} corresponds to all libraries currently known.}
  \item{fields}{a character vector giving the tags of fields to return
    (if other fields occur in the file they are ignored).}
}
\value{
  \code{package.contents} returns \code{NA} if there is no
  \file{CONTENTS} file for the given package; otherwise, a character
  matrix with column names \code{c("Entry", "Keywords", "Description")}
  and rows giving the corresponding entries in the CONTENTS data base
  for each Rd file in the package.

  If a \file{DESCRIPTION} for the given package is found and can
  successfully be read, \code{package.description} returns a named
  character vector with the values of the (given) fields as elements and
  the tags as names.  If not, it returns a named vector of \code{NA}s
  with the field tags as names if \code{fields} is not null, and
  \code{NA} otherwise.
}
\seealso{\code{\link{read.dcf}}}
\examples{
package.contents("mva")
package.contents("mva")[, c("Entry", "Description")]

package.description("ts")
package.description("ts")[c("Package", "Version")]
## NOTE: No subscripting using '$' or abbreviated field tags!
}
\keyword{utilities}
\eof
\name{package.dependencies}
\alias{package.dependencies}
\title{Check Package Dependencies}
\description{
    Parses and checks the dependencies of a package against the
    currently installed version of R [and other packages].
}
\usage{
package.dependencies(x, check=FALSE)
}
\arguments{
    \item{x}{A matrix of package descriptions as returned by
	\code{\link{CRAN.packages}}.}
    \item{check}{If \code{TRUE}, return logical vector of check results.
	If \code{FALSE}, return parsed list of dependencies.}
}
\details{
    Currently we only check if the package conforms with the currently
    running version of R. IN the future we might add checks for
    inter-package dependencies.
}
\seealso{\code{\link{update.packages}}}
\keyword{utilities}
\eof
\name{package.skeleton}
\alias{package.skeleton}
\title{Create a skeleton for a new package}
\description{
  \code{package.skeleton} automates some of the setup for a new
  package.  It creates directories, saves functions and data to
  appropriate places, and creates skeleton help files and \file{README}
  files describing further steps in packaging.
}
\usage{
package.skeleton(name="anRpackage", list, environment=.GlobalEnv, 
	path=".", force=FALSE)
}
\arguments{
  \item{name}{directory name for your package}
  \item{list}{vector of names of R objects to put in the package}
  \item{environment}{if \code{list} is omitted, the contents of this
    environment are packaged}
  \item{path}{path to put the package directories in}
  \item{force}{If \code{FALSE} will not overwrite an existing directory}
}
\value{
  used for its side-effects.
}

\references{Read the \emph{Writing R Extensions} manual for more details }
\seealso{\code{\link{install.packages}}}

\examples{
\dontrun{
    f<-function(x,y) x+y
    g<-function(x,y) x-y
    d<-data.frame(a=1,b=2)
    e<-rnorm(1000)
    package.skeleton(list=c("f","g","d","e"),name="AnExample")
}
}

\keyword{file}
\keyword{utilities}
\eof
\name{packageStatus}
\title{Package Management Tools}
\alias{compareVersion}
\alias{newestVersion}
\alias{packageStatus}
\alias{print.packageStatus}
\alias{summary.packageStatus}
\alias{update.packageStatus}
\alias{upgrade.packageStatus}
\alias{upgrade}
\description{Summarize information about installed packages and packages
  available at various repositories, and automatically upgrade outdated
  packages. These tools will replace \code{\link{update.packages}} and friends
  in the future and are currently work in progress.}
\usage{
packageStatus(lib.loc = NULL, repositories = getOption("repositories"))

\method{summary}{packageStatus}(object, \dots)

\method{update}{packageStatus}(object, lib.loc = levels(object$inst$LibPath),
       repositories = levels(object$avail$Repository), \dots)

\method{upgrade}{packageStatus}(object, ask = TRUE, \dots)
}
\arguments{
  \item{lib.loc}{a character vector describing the location of \R
    library trees to search through, or \code{NULL}.  The default value
    of \code{NULL} corresponds to all libraries currently known.}
  \item{repositories}{a character vector of URLs describing the location of \R
    package repositories on the Internet or on the local machine.}
  \item{object}{return value of \code{packageStatus}.}
  \item{ask}{if \code{TRUE}, the user is prompted which packages should
    be upgraded and which not.}
  \item{\dots}{currently not used.}
}
\examples{
\dontrun{
x <- packageStatus()
print(x)
summary(x)
upgrade(x)
x <- update(x)
print(x)
}}
\keyword{utilities}
\eof
\name{page}
\alias{page}
\title{Invoke a Pager on an R Object}
\usage{
page(x, method = c("dput", "print"), \dots)
}
\arguments{
  \item{x}{the name of an \R object.}
  \item{method}{The default method is to dump the object \emph{via}
    \code{\link{dput}}. An alternative is to print to a file.}
  \item{\dots}{additional arguments for \code{\link{file.show}}.
    Intended for setting \code{pager} as \code{title} and
    \code{delete.file} are already used.}
}
\description{
  Displays a representation of the object named by \code{x} in a pager.
}
\seealso{
  \code{\link{file.show}}, \code{\link{edit}}, \code{\link{fix}}.

  To go to a new page when graphing, see \code{\link{frame}}.
}
\keyword{utilities}
\eof
\name{pairs}
\alias{pairs}
\alias{pairs.default}
\alias{pairs.formula}

\title{Scatterplot Matrices}
\description{
  A matrix of scatterplots is produced.
}
\synopsis{
pairs(x, \dots)
pairs.formula(formula, data = NULL, \dots, subset)
pairs.default(x, labels, panel = points, \dots,
              main = NULL, oma = NULL,
              font.main = par("font.main"), cex.main = par("cex.main"),
              lower.panel = panel, upper.panel = panel,
              diag.panel = NULL, text.panel = textPanel,
              label.pos = 0.5 + has.diag/3,
              cex.labels = NULL, font.labels = 1,
              row1attop = TRUE, gap = 1)
}
\usage{
pairs(x, \dots)

\method{pairs}{formula}(formula, data = NULL, \dots, subset)

\method{pairs}{default}(x, labels, panel = points, \dots,
      lower.panel = panel, upper.panel = panel,
      diag.panel = NULL, text.panel = textPanel,
      label.pos = 0.5 + has.diag/3,
      cex.labels = NULL, font.labels = 1,
      row1attop = TRUE, gap = 1)
}
\arguments{
  \item{x}{the coordinates of points given as columns of a matrix.}
  \item{formula}{a formula, such as \code{y ~ x}.}
  \item{data}{a data.frame (or list) from which the variables in
    \code{formula} should be taken.}
  \item{subset}{an optional vector specifying a subset of observations
    to be used for plotting.}
  \item{labels}{the names of the variables.}
  \item{panel}{\code{function(x,y,\dots)} which is used to plot
    the contents of each panel of the display.}
  \item{\dots}{graphical parameters can be given as arguments to
    \code{plot}.}
  \item{lower.panel, upper.panel}{separate panel functions to be used
    below and above the diagonal respectively.}
  \item{diag.panel}{optional \code{function(x, \dots)} to be
    applied on the diagonals.}
  \item{text.panel}{optional \code{function(x, y, labels, cex,
      font, \dots)} to be applied on the diagonals.}
  \item{label.pos}{\code{y} position of labels in the text panel.}
  \item{cex.labels, font.labels}{graphics parameters for the text panel.}
  \item{row1attop}{logical. Should the layout be matrix-like with row 1
    at the top, or graph-like with row 1 at the bottom?}
  \item{gap}{Distance between subplots, in margin lines.}
}
\details{
  The \eqn{ij}th scatterplot contains \code{x[,i]} plotted against
  \code{x[,j]}.  The \dQuote{scatterplot} can be customised by setting panel
  functions to appear as something completely different. The
  off-diagonal panel functions are passed the appropriate columns of
  \code{x} as \code{x} and \code{y}: the diagonal panel function (if
  any) is passed a single column, and the \code{text.panel} function is
  passed a single \code{(x, y)} location and the column name.

  The graphical parameters \code{pch} and \code{col} can be used to
  specify a vector of plotting symbols and colors to be used in the
  plots.

  The graphical parameter \code{oma} will be set by \code{pairs.default}
  unless supplied as an argument.

  A panel function should not attempt to start a new plot, but just plot
  within a given coordinate system: thus \code{plot} and \code{boxplot}
  are not panel functions.
}
\author{
  Enhancements for \R 1.0.0 contributed by Dr. Jens
  Oehlschlaegel-Akiyoshi and R-core members.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
data(iris)
pairs(iris[1:4], main = "Anderson's Iris Data -- 3 species",
      pch = 21, bg = c("red", "green3", "blue")[unclass(iris$Species)])

## formula method
data(swiss)
pairs(~ Fertility + Education + Catholic, data = swiss,
      subset = Education < 20, main = "Swiss data, Education < 20")

data(USJudgeRatings)
pairs(USJudgeRatings)

## put histograms on the diagonal
panel.hist <- function(x, ...)
{
    usr <- par("usr"); on.exit(par(usr))
    par(usr = c(usr[1:2], 0, 1.5) )
    h <- hist(x, plot = FALSE)
    breaks <- h$breaks; nB <- length(breaks)
    y <- h$counts; y <- y/max(y)
    rect(breaks[-nB], 0, breaks[-1], y, col="cyan", ...)
}
pairs(USJudgeRatings[1:5], panel=panel.smooth,
      cex = 1.5, pch = 24, bg="light blue",
      diag.panel=panel.hist, cex.labels = 2, font.labels=2)

## put (absolute) correlations on the upper panels,
## with size proportional to the correlations.
panel.cor <- function(x, y, digits=2, prefix="", cex.cor)
{
    usr <- par("usr"); on.exit(par(usr))
    par(usr = c(0, 1, 0, 1))
    r <- abs(cor(x, y))
    txt <- format(c(r, 0.123456789), digits=digits)[1]
    txt <- paste(prefix, txt, sep="")
    if(missing(cex.cor)) cex <- 0.8/strwidth(txt)
    text(0.5, 0.5, txt, cex = cex * r)
}
pairs(USJudgeRatings, lower.panel=panel.smooth, upper.panel=panel.cor)
}
\keyword{hplot}
\eof
\name{palette}
\title{Set or View the Graphics Palette}
\usage{
palette(value)
}
\alias{palette}
\arguments{
  \item{value}{an optional character vector.}
}
\description{
  View or manipulate the color palette which is used when a \code{col=}
  has a numeric index.
}
\details{
  If \code{value} has length 1, it is taken to be the name of
  a built in color palette.  If \code{value} has length greater
  than 1 it is assumed to contain a description of the colors
  which are to make up the new palette (either by name or
  by RGB levels).
  
  If \code{value} is omitted or has length 0, no change is made
  the current palette.

  Currently, the only built-in palette is \code{"default"}.
}
\value{
  The palette which \emph{was} in effect.  This is \code{\link{invisible}}
  unless the argument is omitted.
}
\seealso{
  \code{\link{colors}} for the vector of built-in \dQuote{named} colors;
  \code{\link{hsv}}, \code{\link{gray}}, \code{\link{rainbow}},
  \code{\link{terrain.colors}},\dots to construct colors;
  
  \code{\link{col2rgb}} for translating colors to RGB 3-vectors.
}
\examples{
palette()               # obtain the current palette
palette(rainbow(6))     # six color rainbow

(palette(gray(seq(0,.9,len=25)))) # gray scales; print old palette
matplot(outer(1:100,1:30), type='l', lty=1,lwd=2, col=1:30,
        main = "Gray Scales Palette",
        sub = "palette(gray(seq(0,.9,len=25)))")
palette("default")      # reset back to the default
}
\keyword{color}
\keyword{sysdata}
\eof
\name{Palettes}
\alias{rainbow}
\alias{heat.colors}
\alias{terrain.colors}
\alias{topo.colors}
\alias{cm.colors}
\title{Color Palettes}
\description{
  Create a vector of \code{n} \dQuote{contiguous} colors.
}
\usage{
rainbow(n, s = 1, v = 1, start = 0, end = max(1,n - 1)/n, gamma = 1)
heat.colors(n)
terrain.colors(n)
topo.colors(n)
cm.colors(n)
}
\arguments{
  \item{n}{the number of colors (\eqn{\ge 1}{>= 1}) to be in the
    palette.}
  \item{s,v}{the \dQuote{saturation} and \dQuote{value} to be used to complete the
    HSV color descriptions.}
  \item{start}{the (corrected) hue in [0,1] at which the rainbow
    begins.}
  \item{end}{the (corrected) hue in [0,1] at which the rainbow ends.}
  \item{gamma}{the gamma correction, see argument \code{gamma} in
    \code{\link{hsv}}.}
}
\details{
  Conceptually, all of these functions actually use (parts of) a line
  cut out of the 3-dimensional color space, parametrized by
  \code{\link{hsv}(h,s,v, gamma)}, where \code{gamma}\eqn{=1} for the
  \emph{foo}\code{.colors} function, and hence,
  equispaced hues in RGB space tend to cluster at
  the red, green and blue primaries.

  Some applications such as contouring require a palette
  of colors which do not \dQuote{wrap around} to give a final
  color close to the starting one.

  With \code{rainbow}, the parameters \code{start} and \code{end} can be used
  to specify particular subranges of hues.
  The following values can be used when generating such a subrange:
  red=0, yellow=\eqn{\frac 1 6}{1/6}, green=\eqn{\frac 2 6}{2/6},
  cyan=\eqn{\frac 3 6}{3/6}, blue=\eqn{\frac 4 6}{4/6}
  and magenta=\eqn{\frac 5 6}{5/6}.
}
\value{A character vector, \code{cv}, of color names.  This can be used
  either to create a user--defined color palette for subsequent
  graphics by \code{\link{palette}(cv)}, a \code{col=} specification
  in graphics functions or in \code{par}.
}
\seealso{
  \code{\link{colors}}, \code{\link{palette}},  \code{\link{hsv}},
  \code{\link{rgb}}, \code{\link{gray}} and \code{\link{col2rgb}} for
  translating to RGB numbers.
}
\examples{
# A Color Wheel
pie(rep(1,12), col=rainbow(12))

##------ Some palettes ------------
demo.pal <-
  function(n, border = if (n<32) "light gray" else NA,
           main = paste("color palettes;  n=",n),
           ch.col = c("rainbow(n, start=.7, end=.1)", "heat.colors(n)",
                      "terrain.colors(n)", "topo.colors(n)", "cm.colors(n)"))
{
    nt <- length(ch.col)
    i <- 1:n; j <- n / nt; d <- j/6; dy <- 2*d
    plot(i,i+d, type="n", yaxt="n", ylab="", main=main)
    for (k in 1:nt) {
        rect(i-.5, (k-1)*j+ dy, i+.4, k*j,
             col = eval(parse(text=ch.col[k])), border = border)
        text(2*j,  k * j +dy/4, ch.col[k])
    }
}
n <- if(.Device == "postscript") 64 else 16
     # Since for screen, larger n may give color allocation problem
demo.pal(n)
}
\keyword{color}
\keyword{dplot}
\eof
\name{panel.smooth}
\alias{panel.smooth}
\title{Simple Panel Plot}
\description{
  An example of a simple useful \code{panel} function to be used as
  argument in e.g., \code{\link{coplot}} or \code{\link{pairs}}.
}
\usage{
panel.smooth(x, y, col = par("col"), bg = NA, pch = par("pch"), cex = 1,
             col.smooth = "red", span = 2/3, iter=3, \dots)
}
\arguments{
  \item{x,y}{numeric vectors of the same length}
  \item{col,bg,pch,cex}{numeric or character codes for the color(s),
    point type and size of \code{\link{points}}; see also
    \code{\link{par}}.}
  \item{col.smooth}{color to be used by \code{lines} for drawing the
    smooths.}
  \item{span}{smoothing parameter \code{f} for \code{\link{lowess}}, see
    there.}
  \item{iter}{number of robustness iterations for \code{\link{lowess}}.}
  \item{\dots}{further arguments to \code{\link{lines}}.}
}
\seealso{
  \code{\link{coplot}} and \code{\link{pairs}} where \code{panel.smooth}
  is typically used;
  \code{\link{lowess}}.
}
\examples{
data(swiss)
pairs(swiss, panel = panel.smooth, pch = ".")# emphasize the smooths
pairs(swiss, panel = panel.smooth, lwd = 2, cex= 1.5, col="blue")# hmm...
}
\keyword{hplot}
\keyword{dplot}
\eof
\name{par}
\alias{par}
\alias{.Pars}
\alias{.Pars.readonly}
\title{Set or Query Graphical Parameters}

%% The 'real documentation' is the code	in ../../../main/par.c
%% AND (defined AND commented)		in ../../../include/Graphics.h
%% Default initialization by GInit()	in ../../../main/graphics.c

\description{
  \code{par} can be used to set or query graphical parameters.
  Parameters can be set by specifying them as arguments to \code{par} in
  \code{tag = value} form, or by passing them as a list of tagged
  values.
}
\usage{
par(\dots, no.readonly = FALSE)

<highlevel plot> (\dots, <tag> = <value>)
}

\arguments{
  \item{\dots}{arguments in \code{tag = value} form, or a list of tagged
    values.  The tags must come from the graphical parameters described
    below.}
  \item{no.readonly}{logical; if \code{TRUE} and there are no other
    arguments, only parameters are returned which can be set by a
    subsequent \code{par()} call.}
}

\details{
  Parameters are queried by giving one or more character vectors to
  \code{par}.

  \code{par()} (no arguments) or \code{par(no.readonly=TRUE)} is used to
  get \emph{all} the graphical parameters (as a named list).  Their
  names are currently taken from the variable \code{.Pars}.
  \code{.Pars.readonly} contains the names of the \code{par} arguments
  which are \emph{readonly}.

  \emph{\bold{R.O.}} indicates \emph{\bold{read-only arguments}}: These
  may only be used in queries, i.e., they do \emph{not} set anything.

  All but these \emph{\bold{R.O.}} and the following
  \emph{\bold{low-level arguments}} can be set as well in high-level and
  mid-level plot functions, such as \code{\link{plot}},
  \code{\link{points}}, \code{\link{lines}}, \code{\link{axis}},
  \code{\link{title}}, \code{\link{text}}, \code{\link{mtext}}:
  \itemize{
    \item \code{"ask"}
    \item \code{"fig"}, \code{"fin"}
    \item \code{"mai"}, \code{"mar"}, \code{"mex"}
    \item \code{"mfrow"}, \code{"mfcol"}, \code{"mfg"}
    \item \code{"new"}
    \item \code{"oma"}, \code{"omd"}, \code{"omi"}
    \item \code{"pin"}, \code{"plt"}, \code{"ps"}, \code{"pty"}
    \item \code{"usr"}
    \item \code{"xlog"}, \code{"ylog"}
  }
}

\value{
  When parameters are set, their former values are returned in an
  invisible named list.  Such a list can be passed as an argument to
  \code{par} to restore the parameter values.
  Use \code{par(no.readonly = TRUE)} for the full list of parameters
  that can be restored.

  When just one parameter is queried, the value is a character string.
  When two or more parameters are queried, the result is a list of
  character strings, with the list names giving the parameters.

  Note the inconsistency: setting one parameter returns a list, but
  querying one parameter returns a vector.
}

\section{Graphical Parameters}{
  \describe{
    \item{\code{adj}}{The value of \code{adj} determines the way in
      which text strings are justified.  A value of \code{0} produces
      left-justified text, \code{0.5} centered text and \code{1}
      right-justified text.  (Any value in \eqn{[0, 1]} is allowed, and
      on most devices values outside that interval will also work.)
      Note that the \code{adj} argument of \code{\link{text}} also
      allows \code{adj = c(x, y)} for different adjustment in x- and y-
      direction.}
    \item{\code{ann}}{If set to \code{FALSE}, high-level plotting
      functions do not annotate the plots they produce with axis and
      overall titles.  The default is to do annotation.}
    \item{\code{ask}}{logical.  If \code{TRUE}, the user is asked for
      input, before a new figure is drawn.}
    \item{\code{bg}}{The color to be used for the background of plots.
      A description of how colors are specified is given below.}
    \item{\code{bty}}{A character string which determined the type of
      box which is drawn about plots.  If \code{bty} is one of
      \code{"o"}, \code{"l"}, \code{"7"}, \code{"c"}, \code{"u"}, or
      \code{"]"} the resulting box resembles the corresponding upper
      case letter.  A value of \code{"n"} suppresses the box.}
    \item{\code{cex}}{A numerical value giving the amount by which
      plotting text and symbols should be scaled relative to the
      default.}
    \item{\code{cex.axis}}{The magnification to be used for axis
      annotation relative to the current.}
    \item{\code{cex.lab}}{The magnification to be used for x and y
      labels relative to the current.}
    \item{\code{cex.main}}{The magnification to be used for main titles
      relative to the current.}
    \item{\code{cex.sub}}{The magnification to be used for sub-titles
      relative to the current.}
    \item{\code{cin}}{\emph{\bold{R.O.}}; character size
      \code{(width,height)} in inches.}
    \item{\code{col}}{A specification for the default plotting color.  A
      description of how colors are specified is given below.}
    \item{\code{col.axis}}{The color to be used for axis annotation.}
    \item{\code{col.lab}}{The color to be used for x and y labels.}
    \item{\code{col.main}}{The color to be used for plot main titles.}
    \item{\code{col.sub}}{The color to be used for plot sub-titles.}
    \item{\code{cra}}{\emph{\bold{R.O.}}; size of default character
      \code{(width,height)} in \dQuote{rasters} (pixels).}
    \item{\code{crt}}{A numerical value specifying (in degrees) how
      single characters should be rotated.  It is unwise to expect
      values other than multiples of 90 to work.  Compare with
      \code{srt} which does string rotation.}
    \item{\code{csi}}{\emph{\bold{R.O.}}; height of (default sized)
      characters in inches.}
    \item{\code{cxy}}{\emph{\bold{R.O.}}; size of default character
      \code{(width,height)} in user coordinate units.
      \code{par("cxy")} is \code{par("cin")/par("pin")} scaled to user
      coordinates.
      Note that \code{c(\link{strwidth}(ch), \link{strheight}(ch))} for
      a given string \code{ch} is usually much more precise.}
    \item{\code{din}}{\emph{\bold{R.O.}}; the device dimensions in
      inches.}
    \item{\code{err}}{(\emph{Unimplemented}; \R is silent when points
      outside the plot region are \emph{not} plotted.)
      The degree of error reporting desired.}
    \item{\code{fg}}{The color to be used for the foreground of plots.
      This is the default color is used for things like axes and boxes
      around plots.  A description of how colors are specified is given
      below.}
    \item{\code{fig}}{A numerical vector of the form \code{c(x1, x2, y1,
	y2)} which gives the (NDC) coordinates of the figure region in
      the display region of the device.}
    \item{\code{fin}}{A numerical vector of the form \code{c(x, y)}
      which gives the size of the figure region in inches.}
    \item{\code{font}}{An integer which specifies which font to use for
      text.  If possible, device drivers arrange so that 1 corresponds
      to plain text, 2 to bold face, 3 to italic and 4 to bold italic.}
    \item{\code{font.axis}}{The font to be used for axis annotation.}
    \item{\code{font.lab}}{The font to be used for x and y labels.}
    \item{\code{font.main}}{The font to be used for plot main titles.}
    \item{\code{font.sub}}{The font to be used for plot sub-titles.}
    \item{\code{gamma}}{the gamma correction, see argument \code{gamma}
      to \code{\link{hsv}}.}
    \item{\code{lab}}{A numerical vector of the form \code{c(x, y, len)}
      which modifies the way that axes are annotated.  The values of
      \code{x} and \code{y} give the (approximate) number of tickmarks
      on the x and y axes and \code{len} specifies the label size.  The
      default is \code{c(5, 5, 7)}.
      \emph{Currently}, \code{len} \emph{is unimplemented}.}
    \item{\code{las}}{numeric in \{0,1,2,3\}; the style of axis labels.
      \describe{
	\item{0:}{always parallel to the axis [\emph{default}],}
	\item{1:}{always horizontal,}
	\item{2:}{always perpendicular to the axis,}
	\item{3:}{always vertical.}
      }
      Note that other string/character rotation (via argument \code{srt}
      to \code{par}) does \emph{not} affect the axis labels.
    }
    \item{\code{lty}}{The line type.
      Line types can either be specified as an integer (0=blank,
      1=solid, 2=dashed, 3=dotted, 4=dotdash, 5=longdash, 6=twodash) or
      as one of the character strings \code{"blank"}, \code{"solid"},
      \code{"dashed"}, \code{"dotted"}, \code{"dotdash"},
      \code{"longdash"}, or \code{"twodash"}, where \code{"blank"} uses
      \sQuote{invisible lines} (i.e., doesn't draw them).

      Alternatively, a string of up to 8 characters (from \code{c(1:9,
	"A":"F")}) may be given, giving the length of line segments
      which are alternatively drawn and skipped.  See section
      \sQuote{Line Type Specification} below.}
    \item{\code{lwd}}{The line width, a \emph{positive} number,
      defaulting to \code{1}.}
    \item{\code{mai}}{A numerical vector of the form \code{c(bottom,
	left, top, right)} which gives the margin size specified in
      inches.}
    \item{\code{mar}}{A numerical vector of the form \code{c(bottom,
	left, top, right)} which gives the lines of margin to be
      specified on the four sides of the plot.
      The default is \code{c(5, 4, 4, 2) + 0.1}.}
    \item{\code{mex}}{\code{mex} is a character size expansion factor
      which is used to describe coordinates in the margins of plots.}
    \item{\code{mfcol, mfrow}}{A vector of the form \code{c(nr, nc)}.
      Subsequent figures will be drawn in an \code{nr}-by-\code{nc}
      array on the device by \emph{columns} (\code{mfcol}), or
      \emph{rows} (\code{mfrow}), respectively.

      Consider the alternatives, \code{\link{layout}} and
      \code{\link{split.screen}}.
    }
    \item{\code{mfg}}{A numerical vector of the form \code{c(i, j)}
      where \code{i} and \code{j} indicate which figure in an array of
      figures is to be drawn next (if setting) or is being drawn (if
      enquiring).  The array must already have been set by \code{mfcol}
      or \code{mfrow}.

      For compatibility with S, the form \code{c(i, j, nr, nc)} is also
      accepted, when \code{nr} and \code{nc} should be the current
      number of rows and number of columns.  Mismatches will be ignored,
      with a warning.}
    \item{\code{mgp}}{The margin line (in \code{mex} units) for the axis
      title, axis labels and axis line.
      The default is \code{c(3, 1, 0)}.}
    \item{\code{mkh}}{The height in inches of symbols to be drawn when
      the value of \code{pch} is an integer.
      %% <FIXME>
      \emph{Completely ignored currently}.
      %% </FIXME>
    }
    \item{\code{new}}{logical, defaulting to \code{FALSE}.  If set to
      \code{TRUE}, the next high-level plotting command (actually
      \code{\link{plot.new}}) should \emph{not clean} the frame before
      drawing \dQuote{as if it was on a \bold{\emph{new}} device}.}
    \item{\code{oma}}{A vector of the form \code{c(bottom, left, top,
	right)} giving the size of the outer margins in lines of text.}
    \item{\code{omd}}{A vector of the form \code{c(x1, x2, y1, y2)}
      giving the outer margin region in NDC (= normalized device
      coordinates), i.e., as fraction (in \eqn{[0,1]}) of the device
      region.}
    \item{\code{omi}}{A vector of the form \code{c(bottom, left, top,
	right)} giving the size of the outer margins in inches.}
    \item{\code{pch}}{Either an integer specifying a symbol or a single
      character to be used as the default in plotting points. }
    \item{\code{pin}}{The width and height of the current plot in
      inches.}
    \item{\code{plt}}{A vector of the form \code{c(x1, x2, y1, y2)}
      giving the coordinates of the plot region as fractions of the
      current figure region.}
    \item{\code{ps}}{integer; the pointsize of text and symbols.}
    \item{\code{pty}}{A character specifying the type of plot region to
      be used; \code{"s"} generates a square plotting region and
      \code{"m"} generates the maximal plotting region.}
    \item{\code{smo}}{(\emph{Unimplemented}) a value which indicates how
      smooth circles and circular arcs should be.}
    \item{\code{srt}}{The string rotation in degrees.  See the comment
      about \code{crt}.
      %% NOT true for R (but for S): Causes \code{srt} to be set to the
      %% same value.
    }
    \item{\code{tck}}{The length of tick marks as a fraction of the
      smaller of the width or height of the plotting region.
      If \code{tck >= 0.5} it is interpreted as a fraction of the
      relevant side, so if
      \code{tck=1} grid lines are drawn.  The default setting
      (\code{tck = NA}) is to use \code{tcl = -0.5} (see below).}
    \item{\code{tcl}}{The length of tick marks as a fraction of the
      height of a line of text.  The default value is \code{-0.5};
      setting \code{tcl = NA} sets \code{tck = -0.01} which is S' default.}
    \item{\code{tmag}}{A number specifying the enlargement of text of
      the main title relative to the other annotating text of the plot.}
    \item{\code{type}}{character;  the default plot type desired, see
      \code{\link{plot.default}(type=\dots)}, defaulting to \code{"p"}.}
    \item{\code{usr}}{A vector of the form \code{c(x1, x2, y1, y2)}
      giving the extremes of the user coordinates of the plotting
      region.  When a logarithmic scale is in use (i.e.,
      \code{par("xlog")} is true, see below), then the x-limits will be
      \code{10 ^ par("usr")[1:2]}.  Similarly for the y-axis.
    }
    \item{\code{xaxp}}{A vector of the form \code{c(x1, x2, n)} giving
      the coordinates of the extreme tick marks and the number of
      intervals between tick-marks when \code{par("xlog")} is false.
      Otherwise, when \emph{log} coordinates are active, the three
      values have a different meaning: For a small range, \code{n} is
      \emph{negative}, and the ticks are as in the linear case,
      otherwise, \code{n} is in \code{1:3}, specifying a case number,
      and \code{x1} and \code{x2} are the lowest and highest power of 10
      inside the user coordinates, \code{par("usr")[1:2]}.  See
      \code{\link{axTicks}()} for more details.
      }
    \item{\code{xaxs}}{The style of axis interval calculation to be used
      for the x-axis.  Possible values are \code{"r"}, \code{"i"},
      \code{"e"}, \code{"s"}, \code{"d"}.  The styles are generally
      controlled by the range of data or \code{xlim}, if given.
      Style \code{"r"} (regular) first extends the data range by 4
      percent and then finds an axis with pretty labels that fits within
      the range.
      Style \code{"i"} (internal) just finds an axis with pretty labels
      that fits within the original data range.
      Style \code{"s"} (standard) finds an axis with pretty labels
      within which the original data range fits.
      Style \code{"e"} (extended) is like style \code{"s"}, except that
      it is also ensured that there is room for plotting symbols within
      the bounding box.
      Style \code{"d"} (direct) specifies that the current axis should
      be used on subsequent plots.
      (\emph{Only \code{"r"} and \code{"i"} styles are currently
	implemented})}
    \item{\code{xaxt}}{A character which specifies the axis type.
      Specifying \code{"n"} causes an axis to be set up, but not
      plotted.  The standard value is \code{"s"}: for compatibility with
      S values \code{"l"} and \code{"e"} are accepted but are equivalent
      to \code{"s"}.}
    \item{\code{xlog}}{logical value (see \code{log} in
      \code{\link{plot.default}}).  If \code{TRUE}, a logarithmic scale
      is in use (e.g., after \code{plot(*, log = "x")}).
      For a new device, it defaults to \code{FALSE}, i.e., linear scale.}
    \item{\code{xpd}}{A logical value or \code{NA}.
      If \code{FALSE}, all plotting is clipped to the plot region, if
      \code{TRUE}, all plotting is clipped to the figure region, and if
      \code{NA}, all plotting is clipped to the device region.}
    \item{\code{yaxp}}{A vector of the form \code{c(y1, y2, n)} giving
      the coordinates of the extreme tick marks and the number of
      intervals between tick-marks unless for log coordinates, see
      \code{xaxp} above.}
    \item{\code{yaxs}}{The style of axis interval calculation to be used
      for the y-axis.  See \code{xaxs} above.}
    \item{\code{yaxt}}{A character which specifies the axis type.
      Specifying \code{"n"} causes an axis to be set up, but not plotted.}
    \item{\code{ylog}}{a logical value; see \code{xlog} above.}
  }
}

\section{Color Specification}{
  Colors can be specified in several different ways. The simplest way is
  with a character string giving the color name (e.g., \code{"red"}).  A
  list of the possible colors can be obtained with the function
  \code{\link{colors}}. Alternatively, colors can be specified directly in
  terms of their RGB components with a string of the form \code{"#RRGGBB"}
  where each of the pairs \code{RR}, \code{GG}, \code{BB} consist of two
  hexadecimal digits giving a value in the range \code{00} to \code{FF}.
  Colors can also be specified by giving an index into a small table of
  colors, the \code{\link{palette}}.  This provides compatibility with
  S.  Index \code{0} corresponds to the background color.

  Additionally, \code{"transparent"} or (integer) \code{NA} is
  \emph{transparent}, useful for filled areas (such as the background!),
  and just invisible for things like lines or text.

  The functions \code{rgb}, \code{hsv}, \code{gray} and \code{rainbow}
  provide additional ways of generating colors.}

\section{Line Type Specification}{
  Line types can either be specified by giving an index into a small
  built in table of line types (1 = solid, 2 = dashed, etc, see
  \code{lty} above) or directly as the lengths of on/off stretches of
  line.  This is done with a string of an even number (up to eight)
  of characters, namely non-zero
  (hexadecimal) digits which give the lengths in consecutive positions
  in the string.  For example, the string \code{"33"} specifies three
  units on followed by three off and \code{"3313"} specifies three units
  on followed by three off followed by one on and finally three off.
  The \sQuote{units} here are (on most devices) proportional to
  \code{lwd}, and with \code{lwd = 1} are in pixels or points.

  The five standard dash-dot line types (\code{lty = 2:6}) correspond to
  \code{c("44", "13", "1343", "73", "2262")}.

  Note that \code{NA} is not a valid value for \code{lty}.
}

\note{
  The effect of restoring all the (settable) graphics parameters as
  in the examples is hard to predict if the device has been resized.
  Several of them are attempting to set the same things in different
  ways, and those last in the alphabet will win.  In particular, the
  settings of \code{mai}, \code{mar}, \code{pin}, \code{plt} and
  \code{pty} interact, as do the outer margin settings, the figure
  layout and figure region size.
}

\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{plot.default}} for some high-level plotting parameters;
  \code{\link{colors}}, \code{\link{gray}}, \code{\link{rainbow}},
  \code{\link{rgb}};
  \code{\link{options}} for other setup parameters;
  graphic devices \code{\link{x11}}, \code{\link{postscript}} and
  setting up device regions by \code{\link{layout}} and
  \code{\link{split.screen}}.
}

\examples{
op <- par(mfrow = c(2, 2), # 2 x 2 pictures on one plot
          pty = "s")       # square plotting region,
                           # independent of device size

## At end of plotting, reset to previous settings:
par(op)

## Alternatively,
op <- par(no.readonly = TRUE) # the whole list of settable par's.
## do lots of plotting and par(.) calls, then reset:
par(op)

par("ylog") # FALSE
plot(1 : 12, log = "y")
par("ylog") # TRUE

plot(1:2, xaxs = "i") # 'inner axis' w/o extra space
stopifnot(par("xaxp")[1:2] == 1:2 &&
          par("usr") [1:2] == 1:2)

( nr.prof <-
  c(prof.pilots=16,lawyers=11,farmers=10,salesmen=9,physicians=9,
    mechanics=6,policemen=6,managers=6,engineers=5,teachers=4,
    housewives=3,students=3,armed.forces=1))
par(las = 3)
barplot(rbind(nr.prof)) # R 0.63.2: shows alignment problem
par(las = 0)# reset to default

## 'fg' use:
plot(1:12, type = "b", main="'fg' : axes, ticks and box in gray",
     fg = gray(0.7), bty="7" , sub=R.version.string)

ex <- function() {
   old.par <- par(no.readonly = TRUE) # all par settings which
                                      # could be changed.
   on.exit(par(old.par))
   ## ...
   ## ... do lots of par() settings and plots
   ## ...
   invisible() #-- now,  par(old.par)  will be executed
}
ex()
}

\keyword{iplot}
\keyword{dplot}
\keyword{environment}
\eof
\name{parse}
\alias{parse}
\title{Parse Expressions}
\description{
  \code{parse} returns the parsed but unevaluated expressions in a
  list.  Each element of the list is of mode \code{expression}.
}
\usage{
parse(file = "", n = NULL, text = NULL, prompt = "?")
}
\arguments{
  \item{file}{a connection, or a character string giving the name of a
    file or a URL to read the expressions from.
    If \code{file} is \code{""} and \code{text} is missing or \code{NULL}
    then input is taken from the console.}
  \item{n}{the number of statements to parse.  If \code{n} is negative
    the file is parsed in its entirety.}
  \item{text}{character vector. The text to parse. Elements are treated
    as if they were lines of a file.}
  \item{prompt}{the prompt to print when parsing from the keyboard.
    \code{NULL} means to use \R's prompt, \code{getOption("prompt")}.}
    \code{NULL} means to use \R's prompt, \code{getOption("prompt")}.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{scan}}, \code{\link{source}}, \code{\link{eval}},
  \code{\link{deparse}}.
}
\details{
  All versions of \R accept input from a connection with end of line
  marked by LF (as used on Unix), CRLF (as used on DOS/Windows)
  or CR (as used on classic MacOS).  The final line can be incomplete,
  that is missing the final EOL marker.

  See \code{\link{source}} for the limits on the size of functions
  that can be parsed (by default).
}
\examples{
cat("x <- c(1,4)\n  x ^ 3 -10 ; outer(1:7,5:9)\n", file="xyz.Rdmped")
# parse 3 statements from the file "xyz.Rdmped"
parse(file = "xyz.Rdmped", n = 3)
unlink("xyz.Rdmped")
}
\keyword{file}
\keyword{programming}
\keyword{connection}
\eof
\name{paste}
\title{Concatenate Strings}
\usage{
paste(\dots, sep = " ", collapse = NULL)
}
\alias{paste}
\arguments{
  \item{\dots}{one or more \R objects, to be coerced to character vectors.}
  \item{sep}{a character string to separate the terms.}
  \item{collapse}{an optional character string to separate the results.}
}
\description{
  Concatenate vectors after converting to character.
}
\details{
  \code{paste} converts its arguments to character strings, and
  concatenates them (separating them by the string given by \code{sep}).
  If the arguments are vectors, they are concatenated term-by-term to
  give a character vector result.

  If a value is specified for \code{collapse}, the values in the result
  are then concatenated into a single string, with the elements being
  separated by the value of \code{collapse}.
}
\value{
  A character vector of the concatenated values.  Thus will be of length
  zero if all the objects are unless \code{collapse} is non-NULL, in
  which case it is a single empty string.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  String manipulation with
  \code{\link{as.character}}, \code{\link{substr}}, \code{\link{nchar}},
  \code{\link{strsplit}}; further, \code{\link{cat}} which concatenates and
  writes to a file, and \code{\link{sprintf}} for C like string
  construction.
}
\examples{
paste(1:12) # same as as.character(1:12)
paste("A", 1:6, sep = "")
paste("Today is", date())
}
\keyword{character}
\eof
\name{path.expand}
\alias{path.expand}
\title{Expand File Paths}
\description{
  Expand a path name, for example by replacing a leading tilde by the
  user's home directory (if defined on that platform).
}
\usage{
path.expand(path)
}
\arguments{
  \item{path}{character vector containing one or more path names.}
}
#ifdef unix
\details{
  On \emph{some Unix} versions, a leading \code{~user} will expand to
  the home directory of \code{user}, but not on Unix versions without
  \code{readline} installed.
}
#endif
\seealso{
  \code{\link{basename}}
}
\examples{
path.expand("~/foo")
}
\keyword{file}
\eof
\name{pdf}
\alias{pdf}
\title{PDF Graphics Device}
%% The definitive doc is the source :-)
%% 	../../../main/devices.c  &   ../../../unix/devPS.c
\description{
  \code{pdf} starts the graphics device driver for producing PDF
  graphics.
}
\synopsis{
pdf(file = ifelse(onefile, "Rplots.pdf", "Rplot\%03d.pdf"),
    width = 6, height = 6, onefile = TRUE, title = "R Graphics Output", \dots)
}
\usage{
pdf(file = ifelse(onefile, "Rplots.pdf", "Rplot\%03d.pdf"),
    width = 6, height = 6, onefile = TRUE, family = "Helvetica",
    title = "R Graphics Output", encoding, bg, fg, pointsize)
}
\arguments{
  \item{file}{a character string giving the name of the file.}
  \item{width, height}{the width and height of the graphics region in
    inches.}
  \item{onefile}{logical: if true (the default) allow multiple figures
    in one file.  If false, generate a file name containing the page
    number.} 
  \item{family}{the font family to be used, one of \code{"AvantGarde"},
    \code{"Bookman"}, \code{"Courier"}, \code{"Helvetica"},
    \code{"Helvetica-Narrow"}, \code{"NewCenturySchoolbook"},
    \code{"Palatino"} or \code{"Times"}. }
  \item{title}{title string to embed in the file.}
  \item{encoding}{the name of an encoding file.  Defaults to
#ifdef unix
\code{"ISOLatin1.enc"}
#endif
#ifdef windows
\code{"WinAnsi.enc"}
#endif
    in the \file{R\_HOME/afm} directory, which is used if the path does
    not contain a path separator.  An extension \code{".enc"} can be
    omitted.}
  \item{pointsize}{the default point size to be used.}
  \item{bg}{the default background color to be used.}
  \item{fg}{the default foreground color to be used.}
}
\details{
  \code{pdf()} opens the file \code{file} and the PDF commands needed to
  plot any graphics requested are sent to that file.

  See \code{\link{postscript}} for details of encodings, as the internal
  code is shared between the drivers.  The native PDF encoding is given
  in file \file{PDFDoc.enc}.

  \code{pdf} writes uncompressed PDF.  It is primarily intended for
  producing PDF graphics for inclusion in other documents, and
  PDF-includers such as \code{pdftex} are usually able to handle
  compression.

  At present the PDF is fairly simple, with each page being represented
  as a single stream.  The \R graphics model does not distinguish
  graphics objects at the level of the driver interface.
}
\note{
  Acrobat Reader does not use the fonts specified but rather emulates
  them from multiple-master fonts.  This can be seen in imprecise
  centring of characters, for example the multiply and divide signs in
  Helvetica.
}
\seealso{
  \code{\link{Devices}},
  \code{\link{postscript}}
}
\examples{
\dontrun{
## Test function for encodings
TestChars <- function(encoding="ISOLatin1")
{
    pdf(encoding=encoding)
    par(pty="s")
    plot(c(0,15), c(0,15), type="n", xlab="", ylab="")
    title(paste("Centred chars in encoding", encoding))
    grid(15, 15, lty=1)
    for(i in c(32:255)) {
	x <- i %% 16
	y <- i %/% 16
	points(x, y, pch=i)
    }
    dev.off()
}
## there will be many warnings.
TestChars("ISOLatin2")
## doesn't view properly in US-spec Acrobat 5.05, but gs7.04 works.
## Lots of characters are not centred.
}}
\keyword{device}
\eof
\name{persp}
\alias{persp}
\alias{persp.default}
\title{Perspective Plots}
\description{
  This function draws perspective plots of surfaces over the
  x--y plane. \code{persp} is a generic function.
}
\usage{
persp(x, \dots)

\method{persp}{default}(x = seq(0, 1, len = nrow(z)), y = seq(0, 1, len = ncol(z)), z,
      xlim = range(x), ylim = range(y), zlim = range(z, na.rm = TRUE),
      xlab = NULL, ylab = NULL, zlab = NULL, main = NULL, sub = NULL,
      theta = 0, phi = 15, r = sqrt(3), d = 1, scale = TRUE, expand = 1,
      col = "white", border = NULL, ltheta = -135, lphi = 0, shade = NA,
      box = TRUE, axes = TRUE, nticks = 5, ticktype = "simple",
      \dots)
}
\arguments{
  \item{x, y}{locations of grid lines at which the values in \code{z} are
    measured.  These must be in ascending order.  By default, equally
    spaced values from 0 to 1 are used.  If \code{x} is a \code{list},
    its components \code{x$x} and \code{x$y} are used for \code{x}
    and \code{y}, respectively.}
  \item{z}{a matrix containing the values to be plotted (\code{NA}s are
    allowed).  Note that \code{x} can be used instead of \code{z} for
    convenience.}
  \item{xlim, ylim, zlim}{x-, y-  and z-limits.  The plot is produced
    so that the rectangular volume defined by these limits is visible.}
  \item{xlab, ylab, zlab}{titles for the axes.  N.B. These must be
    character strings; expressions are not accepted.  Numbers will be
    coerced to character strings.}
  \item{main, sub}{main and sub title, as for \code{\link{title}}.}
  \item{theta, phi}{angles defining the viewing direction.
    \code{theta} gives the azimuthal direction and \code{phi}
    the colatitude.}
  \item{r}{the distance of the eyepoint from the centre of the plotting box.}
  \item{d}{a value which can be used to vary the strength of
    the perspective transformation.  Values of \code{d} greater
    than 1 will lessen the perspective effect and values less
    and 1 will exaggerate it.}
  \item{scale}{before viewing the x, y and z coordinates of the
    points defining the surface are transformed to the interval
    [0,1].  If \code{scale} is \code{TRUE} the x, y and z coordinates
    are transformed separately.  If \code{scale} is \code{FALSE}
    the coordinates are scaled so that aspect ratios are retained.
    This is useful for rendering things like DEM information.}
  \item{expand}{a expansion factor applied to the \code{z}
    coordinates. Often used with \code{0 < expand < 1} to shrink the
    plotting box in the \code{z} direction.}
  \item{col}{the color(s) of the surface facets.  Transparent colours are
    ignored.  This is recycled to the \eqn{(nx-1)(ny-1)} facets.}
  \item{border}{the color of the line drawn around the surface facets.
    A value of \code{NA} will disable the drawing of borders.  This is
    sometimes useful when the surface is shaded.}
  \item{ltheta, lphi}{if finite values are specified for \code{ltheta}
    and \code{lphi}, the surface is shaded as though it was being
    illuminated from the direction specified by azimuth \code{ltheta}
    and colatitude \code{lphi}.}
  \item{shade}{the shade at a surface facet is computed as
    \code{((1+d)/2)^shade}, where \code{d} is the dot product of
    a unit vector normal to the facet and a unit vector in the
    direction of a light source.  Values of \code{shade} close
    to one yield shading similar to a point light source model
    and values close to zero produce no shading.  Values in the
    range 0.5 to 0.75 provide an approximation to daylight
    illumination.}
  \item{box}{should the bounding box for the surface be displayed.
    The default is \code{TRUE}.}
  \item{axes}{should ticks and labels be added to the box.  The
    default is \code{TRUE}.  If \code{box} is \code{FALSE} then no
    ticks or labels are drawn.}
  \item{ticktype}{character: \code{"simple"} draws just an arrow
    parallel to the axis to indicate direction of increase;
    \code{"detailed"} draws normal ticks as per 2D plots.}
  \item{nticks}{the (approximate) number of tick marks to draw on the
    axes.  Has no effect if \code{ticktype} is \code{"simple"}.}
  \item{\dots}{additional graphical parameters (see \code{\link{par}}).}
}
\value{
  The \emph{viewing transformation matrix}, say \code{VT}, a
  \eqn{4 \times 4}{4 x 4} matrix suitable for projecting 3D coordinates
  \eqn{(x,y,z)} into the 2D plane using homogenous 4D coordinates
  \eqn{(x,y,z,t)}.
  It can be used to superimpose additional graphical elements on the 3D
  plot, by \code{\link{lines}()} or \code{\link{points}()}, e.g.
  using the function \code{trans3d} given in the last examples section
  below.
}
\details{
  The plots are produced by first transforming the
  coordinates to the interval [0,1].  The surface is then viewed
  by looking at the origin from a direction defined by \code{theta}
  and \code{phi}.  If \code{theta} and \code{phi} are both zero
  the viewing direction is directly down the negative y axis.
  Changing \code{theta} will vary the azimuth and changing \code{phi}
  the colatitude.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{contour}} and \code{\link{image}}.
}
\examples{
## More examples in  demo(persp) !!
##                   -----------

# (1) The Obligatory Mathematical surface.
#     Rotated sinc function.

x <- seq(-10, 10, length= 30)
y <- x
f <- function(x,y) { r <- sqrt(x^2+y^2); 10 * sin(r)/r }
z <- outer(x, y, f)
z[is.na(z)] <- 1
op <- par(bg = "white")
persp(x, y, z, theta = 30, phi = 30, expand = 0.5, col = "lightblue")
persp(x, y, z, theta = 30, phi = 30, expand = 0.5, col = "lightblue",
      ltheta = 120, shade = 0.75, ticktype = "detailed",
      xlab = "X", ylab = "Y", zlab = "Sinc( r )"
) -> res
round(res, 3)

# (2) Add to existing persp plot :

trans3d <- function(x,y,z, pmat) {
  tr <- cbind(x,y,z,1) \%*\% pmat
  list(x = tr[,1]/tr[,4], y= tr[,2]/tr[,4])
}
xE <- c(-10,10); xy <- expand.grid(xE, xE)
points(trans3d(xy[,1], xy[,2], 6, pm = res), col = 2, pch =16)
lines (trans3d(x, y=10, z= 6 + sin(x), pm = res), col = 3)

phi <- seq(0, 2*pi, len = 201)
r1 <- 7.725 # radius of 2nd maximum
xr <- r1 * cos(phi)
yr <- r1 * sin(phi)
lines(trans3d(xr,yr, f(xr,yr), res), col = "pink", lwd=2)## (no hidden lines)

# (3) Visualizing a simple DEM model

data(volcano)
z <- 2 * volcano        # Exaggerate the relief
x <- 10 * (1:nrow(z))   # 10 meter spacing (S to N)
y <- 10 * (1:ncol(z))   # 10 meter spacing (E to W)
## Don't draw the grid lines :  border = NA
par(bg = "slategray")
persp(x, y, z, theta = 135, phi = 30, col = "green3", scale = FALSE,
      ltheta = -120, shade = 0.75, border = NA, box = FALSE)
par(op)
}
\keyword{hplot}
\keyword{aplot}
\eof
\name{phones}
\docType{data}
\alias{phones}
\title{The World's Telephones}
\description{
  The number of telephones in various regions of the world (in
  thousands).
}
\usage{data(phones)}
\format{
  A matrix with 7 rows and 8 columns.  The columns of the matrix give
  the figures for a given region, and the rows the figures for a year.

  The regions are: North America, Europe, Asia, South America, Oceania,
  Africa, Central America.
  
  The years are: 1951, 1956, 1957, 1958, 1959, 1960, 1961.
}
\source{
  AT&T (1961) \emph{The World's Telephones}.
}
\references{
  McNeil, D. R. (1977)
  \emph{Interactive Data Analysis}.
  New York: Wiley.
}
\examples{
data(phones)
matplot(rownames(phones), phones, type = "b", log = "y",
        xlab = "Year", ylab = "Number of telephones (1000's)")
legend(1951.5, 80000, colnames(phones), col = 1:6, lty = 1:5, pch = rep(21, 7))
title(main = "phones data: log scale for response")
}
\keyword{datasets}
\eof
\name{pictex}
\alias{pictex}
\title{A PicTeX Graphics Driver}
\usage{
pictex(file = "Rplots.tex", width = 5, height = 4, debug = FALSE,
       bg = "white", fg = "black")
}
\arguments{
  \item{file}{the file where output will appear.}
  \item{width}{The width of the plot in inches.}
  \item{height}{the height of the plot in inches.}
  \item{debug}{should debugging information be printed.}
  \item{bg}{the background color for the plot.}
  \item{fg}{the foreground color for the plot.}
}
\description{
  This function produces graphics suitable for inclusion in TeX and
  LaTeX documents.
}
\details{
  This driver does not have any font metric information, so the use of
  \code{\link{plotmath}} is not supported.

  Multiple plots will be placed as separate environments in the output file.
}
\references{
  Knuth, D. E. (1984)
  \emph{The TeXbook.}
  Reading, MA: Addison-Wesley.

  Lamport, L. (1994)
  \emph{LATEX: A Document Preparation System.}
  Reading, MA: Addison-Wesley.

  Goossens, M., Mittelbach, F. and Samarin, A. (1994)
  \emph{The LATEX Companion.}
  Reading, MA: Addison-Wesley.
}
\author{
  This driver was provided by Valerio Aimale
  \email{valerio@svpop.com.dist.unige.it}
  of the Department of Internal Medicine, University of Genoa, Italy.
}
\seealso{
  \code{\link{postscript}}, \code{\link{Devices}}.
}
\examples{
pictex()
plot(1:11,(-5:5)^2, type='b', main="Simple Example Plot")
dev.off()
##--------------------
\dontrun{
\%\% LaTeX Example
\\documentclass{article}
\\usepackage{pictex}
\\begin{document}
\%...
\\begin{figure}[h]
  \\centerline{\\input{Rplots.tex}}
  \\caption{}
\\end{figure}
\%...
\\end{document}

\%\%-- TeX Example --
\\input pictex
$$ \\input Rplots.tex $$
}
##--------------------
unlink("Rplots.tex")
}
\keyword{device}
%%-
%%--- on CTAN, searching for "pictex" in file FILES.byname  [April 3, 1998]:
% 1994/04/20 |        473 | graphics/pictex/addon/00index
% 1994/04/20 |       1568 | graphics/pictex/addon/piccorr.sty
% 1994/04/20 |       2952 | graphics/pictex/addon/picmore.tex
% 1994/04/20 |        311 | graphics/pictex/addon/pictex.sty
% 1994/04/20 |        416 | graphics/pictex/addon/pictexwd.sty
% 1994/04/20 |     133232 | graphics/pictex/addon/pictexwd.tex
% 1994/04/20 |        457 | graphics/pictex/addon/pictexzusatz.txt
% 1992/08/27 |       3041 | graphics/pictex/errorbars.tex
% 1992/08/27 |      10519 | graphics/pictex/latexpicobjs.tex
% 1992/08/27 |     129709 | graphics/pictex/pictex.tex
% 1992/08/27 |       1322 | graphics/pictex/pointers.tex
% 1992/08/27 |       1399 | graphics/pictex/postpictex.tex
% 1992/08/27 |       1082 | graphics/pictex/prepictex.tex
% 1992/08/27 |        175 | graphics/pictex/readme
% 1992/08/27 |        876 | graphics/pictex/readme.errorbars
% 1989/11/26 |       7270 | graphics/pictex/texpictex.tex
% 1992/08/31 |      11382 | graphics/pictex/tree.sty
% 1994/01/13 |        162 | info/stammtisch/wuppertal/updates/pictex.sty
% 1997/07/26 |      58723 | macros/context/generic/doc/m-pictex.pdf
% 1997/04/29 |       8053 | macros/context/generic/tex/m-pictex.tex
% 1997/08/20 |      58724 | macros/context/pictex/doc/m-pictex.pdf
% 1997/08/20 |       1261 | macros/context/pictex/doc/readme.de
% 1997/08/20 |       1207 | macros/context/pictex/doc/readme.en
% 1997/08/20 |       1323 | macros/context/pictex/doc/readme.nl
% 1997/08/20 |        145 | macros/context/pictex/tex/m-pictex.sty
% 1997/08/20 |       8689 | macros/context/pictex/tex/m-pictex.tex
% 1997/06/30 |         39 | macros/context/ppchtex/tex/m-pictex.sty
% 1997/04/29 |       8053 | macros/context/ppchtex/tex/m-pictex.tex
% 1994/01/14 |        162 | macros/latex209/contrib/konstruk/pictex.sty
% 1992/08/27 |       7251 | macros/plain/contrib/texpictex.tex
% 1991/07/29 |      27946 | support/pictex-converter/PiCUNIX.PASCAL
% 1991/07/25 |      23812 | support/pictex-converter/piccon1.uue
% 1991/07/25 |      25756 | support/pictex-converter/piccon2.uue
% 1991/07/25 |        379 | support/pictex-converter/picconv.anleit
% 1991/07/25 |      35840 | support/pictex-converter/picconv.lzh
% 1991/07/25 |       1906 | support/pictex-converter/pictex.info-cb
% 1991/07/25 |      54800 | support/pictex-converter/pictexte.exe
% 1991/07/25 |      43757 | support/pictex-converter/pictexte.pas
% 1992/08/25 |        835 | support/qfig/q-pictex.tex
% 1991/10/11 |      51141 | systems/atari/texutils/texdraw/pictex.tos
% 1995/07/13 |      45973 | systems/msdos/4alltex/disk04/pictex.zip
% 1995/06/26 |      39887 | systems/msdos/emtex/pictex.zip
% 1998/02/02 |        676 | systems/unix/linux/fastpictex-0.3.lsm
% 1998/02/02 |     309581 | systems/unix/linux/fastpictex-0.3.tar.gz
% 1997/01/27 |      73930 | systems/unix/teTeX/distrib/goodies/pictex.tar.gz
\eof
\name{pie}
\title{Pie Charts}
\alias{pie}
\description{
  Draw a pie chart.
}
\usage{
pie(x, labels = names(x), edges = 200, radius = 0.8,
    density = NULL, angle = 45, col = NULL, border = NULL, lty = NULL,
    main = NULL, \dots)
}
\arguments{
  \item{x}{a vector of positive quantities.
    The values in \code{x} are displayed as the areas of pie slices.}
  \item{labels}{a vector of character strings giving names for the
    slices.  For empty or NA labels, no pointing line is drawn either.}
  \item{edges}{the circular outline of the pie is approximated by a
    polygon with this many edges.}
  \item{radius}{the pie is drawn centered in a square box whose sides
    range from \eqn{-1} to \eqn{1}.  If the character strings labeling
    the slices are long it may be necessary to use a smaller radius.}
  \item{density}{the density of shading lines, in lines per inch.
    The default value of \code{NULL} means that no shading lines
    are drawn. Non-positive values of \code{density} also inhibit the
    drawing of shading lines.}
  \item{angle}{the slope of shading lines, given as an angle in
    degrees (counter-clockwise).}
  \item{col}{a vector of colors to be used in filling or shading
    the slices. If missing a set of 6 pastel colours is used,
    unless \code{density} is specified when \code{par("fg")} is used.}
  \item{border, lty}{(possibly vectors) arguments passed to
    \code{\link{polygon}} which draws each slice.}
  \item{main}{an overall title for the plot.}
  \item{\dots}{graphical parameters can be given as arguments to
    \code{pie}.  They will affect the main title and labels only.}
}
\note{
  Pie charts are a very bad way of displaying information.
  The eye is good at judging linear measures and bad at judging
  relative areas.  A bar chart or dot chart is a preferable way of
  displaying this type of data.

  Cleveland (1985), page 264: \dQuote{Data that can be shown by pie charts
    always can be shown by a dot chart.  This means that judgements of
    position along a common scale can be made instead of the less
    accurate angle judgements.}
  This statement is based on the empirical investigations of Cleveland
  and McGill as well as investigations by perceptual psychologists.
  
  Prior to \R 1.5.0 this was known as \code{piechart}, which is the name
  of a Trellis function, so the name was changed to be compatible with S.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Cleveland, W. S. (1985)
  \emph{The elements of graphing data}.
  Wadsworth: Monterey, CA, USA.
}
\seealso{
  \code{\link{dotchart}}.
}
\examples{
pie(rep(1, 24), col = rainbow(24), radius = 0.9)

pie.sales <- c(0.12, 0.3, 0.26, 0.16, 0.04, 0.12)
names(pie.sales) <- c("Blueberry", "Cherry",
    "Apple", "Boston Cream", "Other", "Vanilla Cream")
pie(pie.sales) # default colours
pie(pie.sales,
    col = c("purple", "violetred1", "green3", "cornsilk", "cyan", "white"))
pie(pie.sales, col = gray(seq(0.4,1.0,length=6)))
pie(pie.sales, density = 10, angle = 15 + 10 * 1:6)

n <- 200
pie(rep(1,n), labels="", col=rainbow(n), border=NA,
    main = "pie(*, labels=\"\", col=rainbow(n), border=NA,..")
}
\keyword{hplot}
\eof
\name{plot}
\title{Generic X-Y Plotting}
\alias{plot}
\usage{
plot(x, y, \dots)
}
\arguments{
  \item{x}{the coordinates of points in the plot. Alternatively, a
      single plotting structure, function or \emph{any \R object with a
          \code{plot} method} can be provided.}
  \item{y}{the y coordinates of points in the plot, \emph{optional}
      if \code{x} is an appropriate structure.}
  \item{\dots}{graphical parameters can be given as arguments to
    \code{plot}.  Many methods will also accept the following arguments:
    
    \item{type}{what type of plot should be drawn.  Possible types are
      \itemize{
	\item \code{"p"} for \bold{p}oints,
	\item \code{"l"} for \bold{l}ines,
	\item \code{"b"} for \bold{b}oth,
	\item \code{"c"} for the lines part alone of \code{"b"},
	\item \code{"o"} for both \dQuote{\bold{o}verplotted},
	\item \code{"h"} for \dQuote{\bold{h}istogram} like (or
	\dQuote{high-density}) vertical lines,
	\item \code{"s"} for stair \bold{s}teps,
	\item \code{"S"} for other \bold{s}teps, see \emph{Details} below,
	\item \code{"n"} for no plotting.
      }
      All other \code{type}s give a warning or an error; using, e.g.,
      \code{type = "punkte"} being equivalent to \code{type = "p"} for S
      compatibility.
    }
    \item{main}{an overall title for the plot: see \code{\link{title}}.}
    \item{sub}{a sub title for the plot: see \code{\link{title}}.}
    \item{xlab}{a title for the x axis: see \code{\link{title}}.}
    \item{ylab}{a title for the y axis: see \code{\link{title}}.}
  }
}
\description{
  Generic function for plotting of \R objects.  For more details about
  the graphical parameter arguments, see \code{\link{par}}.
}
\details{
  For simple scatter plots, \code{\link{plot.default}} will be used.
  However, there are \code{plot} methods for many \R objects,
  including \code{\link{function}}s, \code{\link{data.frame}}s,
  \code{\link{density}} objects, etc.  Use \code{methods(plot)} and
  the documentation for these.

  The two step types differ in their x-y preference: Going from
  \eqn{(x1,y1)} to \eqn{(x2,y2)} with \eqn{x1 < x2}, \code{type = "s"}
  moves first horizontal, then vertical, whereas \code{type = "S"} moves
  the other way around.
}
\seealso{
  \code{\link{plot.default}}, \code{\link{plot.formula}} and other
  methods; \code{\link{points}}, \code{\link{lines}}, \code{\link{par}}.
}
\examples{
data(cars)
plot(cars)
lines(lowess(cars))

plot(sin, -pi, 2*pi)

## Discrete Distribution Plot:
plot(table(rpois(100,5)), type = "h", col = "red", lwd=10,
     main="rpois(100,lambda=5)")

## Simple quantiles/ECDF, see ecdf() {library(stepfun)} for a better one:
plot(x <- sort(rnorm(47)), type = "s", main = "plot(x, type = \"s\")")
points(x, cex = .5, col = "dark red")
}
\keyword{hplot}
\eof
\name{plot.data.frame}
\alias{plot.data.frame}
\title{Plot Method for Data Frames}
\description{
  \code{plot.data.frame}, a method of the \code{\link{plot}} generic,
  uses \code{\link{stripchart}} for \emph{one} variable,
  \code{\link{plot.default}} (scatterplot) for \emph{two} variables, and
  \code{\link{pairs}} (scatterplot matrix) otherwise.
}
\usage{
\method{plot}{data.frame}(x, \dots)
}
\arguments{
  \item{x}{object of class \code{data.frame}.}
  \item{\dots}{further arguments to \code{\link{stripchart}},
    \code{\link{plot.default}} or \code{\link{pairs}}.}
}
\seealso{
  \code{\link{data.frame}}
}
\examples{
data(OrchardSprays)
plot(OrchardSprays[1], method="jitter")
plot(OrchardSprays[c(4,1)])
plot(OrchardSprays)
}
\keyword{hplot}
\keyword{methods}
\eof
\name{plot.density}
\alias{plot.density}
\title{Plot Method for Kernel Density Estimation}
\usage{
\method{plot}{density}(x, main = NULL, xlab = NULL, ylab = "Density", type = "l",
     zero.line = TRUE, \dots)
}
\arguments{
\item{x}{a \dQuote{density} object.}
\item{main, xlab, ylab, type}{plotting parameters with useful defaults.}
\item{\dots}{further plotting parameters.}
\item{zero.line}{logical; if \code{TRUE}, add a base line at \eqn{y = 0}}
}
\description{
  The \code{plot} method for density objects.
}
\value{
  None.
}
\references{
}
\seealso{
  \code{\link{density}}.
}
\keyword{dplot}
\eof
\name{plot.design}
\alias{plot.design}
\title{Plot Univariate Effects of a `Design' or Model}
\description{
  Plot univariate effects of one ore more \code{\link{factor}}s,
  typically for a designed experiment as analyzed by \code{\link{aov}()}.
  Further, in S this a method of the \code{\link{plot}} generic function
  for \code{design} objects.
}
\usage{
plot.design(x, y = NULL, fun = mean, data = NULL, \dots,
            ylim = NULL, xlab = "Factors", ylab = NULL, main = NULL,
            ask = NULL, xaxt = par("xaxt"), axes = TRUE, xtick = FALSE)
}
\arguments{
  \item{x}{either a data frame containing the design factors and
    optionally the response, or a \code{\link{formula}} or
    \code{\link{terms}} object.}
  \item{y}{the response, if not given in x.}
  \item{fun}{a function (or name of one) to be applied to each
    subset.  It must return one number for a numeric (vector) input.}
  \item{data}{data frame containing the variables referenced by \code{x}
    when that is formula like.}
  \item{\dots}{graphical arguments such as \code{col}, see \code{\link{par}}.}
  \item{ylim}{range of y values, as in \code{\link{plot.default}}.}
  \item{xlab}{x axis label, see \code{\link{title}}.}
  \item{ylab}{y axis label with a \dQuote{smart} default.}
  \item{main}{main title, see \code{\link{title}}.}
  \item{ask}{logical indicating if the user should be asked before a new
    page is started -- in the case of multiple y's.}
  \item{xaxt}{character giving the type of x axis.}
  \item{axes}{logical indicating if axes should be drawn.}
  \item{xtick}{logical indicating if \dQuote{ticks} (one per factor) should
    be drawn on the x axis.}
}
\details{
  The supplied function will be called once for each level of each
  factor in the design and the plot will show these summary values.  The
  levels of a particular factor are shown along a vertical line, and the
  overall value of \code{fun()} for the response is drawn as a
  horizontal line.

  This is a new \R implementation which will not be completely
  compatible to the earlier S implementations.  This is not a bug but
  might still change.
}
\references{
  Chambers, J. M. and Hastie, T. J. eds (1992)
  \emph{Statistical Models in S}.
  Chapman & Hall, London, \bold{the} \emph{white book}, pp. 546--7 (and 163--4).

  Freeny, A. E. and Landwehr, J. M. (1990)
  Displays for data from large designed experiments;
  Computer Science and Statistics: Proc.\ 22nd Symp\. Interface, 117--126,
  Springer Verlag.
}
\author{Roberto Frisullo and Martin Maechler}
\note{A big effort was taken to make this closely compatible to the S
  version.  However, \code{col} (and \code{fg}) specification has
  different effects.
}
\seealso{\code{\link{interaction.plot}} for a \dQuote{standard graphic}
  of designed experiments.}
\examples{
data(warpbreaks)
plot.design(warpbreaks)# automatic for data frame with one numeric var.

Form <- breaks ~ wool + tension
summary(fm1 <- aov(Form, data = warpbreaks))
plot.design(       Form, data = warpbreaks, col = 2)# same as above

## More than one y :
data(esoph)
str(esoph)
plot.design(esoph) ## two plots; if interactive you are "ask"ed

## or rather, compare mean and median:
op <- par(mfcol = 1:2)
plot.design(ncases/ncontrols ~ ., data = esoph, ylim = c(0,0.8))
plot.design(ncases/ncontrols ~ ., data = esoph, ylim = c(0,0.8), fun = median)
par(op)
}
\keyword{hplot}

\eof
\name{plot.lm}
\alias{plot.lm}
\alias{plot.mlm}%which is .NotYetImplemented()
\title{Plot Diagnostics for an lm Object}
\usage{
\method{plot}{lm}(x, which = 1:4,
     caption = c("Residuals vs Fitted", "Normal Q-Q plot",
                 "Scale-Location plot", "Cook's distance plot"),
     panel = points,
     sub.caption = deparse(x$call), main = "",
     ask = prod(par("mfcol")) < length(which) && dev.interactive(),
     \dots,
     id.n = 3, labels.id = names(residuals(x)), cex.id = 0.75)
}
\arguments{
  \item{x}{\code{lm} object, typically result of \code{\link{lm}} or
    \code{\link{glm}}.}
  \item{which}{If a subset of the plots is required, specify a subset of
    the numbers \code{1:4}.}
  \item{caption}{Captions to appear above the plots}
  \item{panel}{Panel function.  A useful alternative to
    \code{\link{points}} is \code{\link{panel.smooth}}.}
  \item{sub.caption}{common title---above figures if there are multiple;
    used as \code{sub} (s.\code{\link{title}}) otherwise.}
  \item{main}{title to each plot---in addition to the above
    \code{caption}.}
  \item{ask}{logical; if \code{TRUE}, the user is \emph{ask}ed before
    each plot, see \code{\link{par}(ask=.)}.}
  \item{\dots}{other parameters to be passed through to plotting
    functions.}
  \item{id.n}{number of points to be labelled in each plot, starting
    with the most extreme.}
  \item{labels.id}{vector of labels, from which the labels for extreme
    points will be chosen.  \code{NULL} uses observation numbers.}
  \item{cex.id}{magnification of point labels.}
}
\description{
  Four plots (selectable by \code{which}) are currently provided: a plot
  of residuals against fitted values, a Scale-Location plot of
  \eqn{\sqrt{| residuals |}} against fitted values, a Normal Q-Q plot,
  and a plot of Cook's distances versus row labels.
}
\details{
  \code{sub.caption}---by default the function call---is shown as
  a subtitle (under the x-axis title) on each plot when plots are on
  separate pages, or as a subtitle in the outer margin (if any) when
  there are multiple plots per page.

  The \dQuote{Scale-Location} plot, also called \dQuote{Spread-Location} or
  \dQuote{S-L} plot, takes the square root of the absolute residuals in
  order to diminish skewness (\eqn{\sqrt{| E |}} is much less skewed
  than \eqn{| E |} for Gaussian zero-mean \eqn{E}).

  This \sQuote{S-L} and the Q-Q plot use \emph{standardized} residuals
  which have identical variance (under the hypothesis).  They are given
  as \eqn{R_i / (s \times \sqrt{1 - h_{ii}})}{R[i] / (s*sqrt(1 - h.ii))}
  where \eqn{h_{ii}}{h.ii} are the diagonal entries of the hat matrix,
% bug in Rdconv: "$" and \link inside \code fails; '\$' doesn't help :
  \code{\link{influence}()}\code{$hat}, see also \code{\link{hat}}.
}
\references{
  Belsley, D. A., Kuh, E. and Welsch, R. E. (1980)
  \emph{Regression Diagnostics.}  New York: Wiley.

  Cook, R. D. and Weisberg, S. (1982)
  \emph{Residuals and Influence in Regression.}
  London: Chapman and Hall.

  Hinkley, D. V. (1975) On power transformations to
  symmetry. \emph{Biometrika} \bold{62}, 101--111.

  McCullagh, P. and Nelder, J. A. (1989)
  \emph{Generalized Linear Models.}
  London: Chapman and Hall.
}
\author{
  John Maindonald and Martin Maechler.
}
\seealso{\code{\link{termplot}}, \code{\link{lm.influence}},
  \code{\link{cooks.distance}}.
}
\examples{
## Analysis of the life-cycle savings data
## given in Belsley, Kuh and Welsch.
data(LifeCycleSavings)
plot(lm.SR <- lm(sr ~ pop15 + pop75 + dpi + ddpi, data = LifeCycleSavings))

## 4 plots on 1 page; allow room for printing model formula in outer margin:
par(mfrow = c(2, 2), oma = c(0, 0, 2, 0))
plot(lm.SR)
plot(lm.SR, id.n = NULL)               # no id's
plot(lm.SR, id.n = 5, labels.id = NULL)# 5 id numbers

## Fit a smmooth curve, where applicable:
plot(lm.SR, panel = panel.smooth)
## Gives a smoother curve
plot(lm.SR, panel = function(x,y) panel.smooth(x, y, span = 1))

par(mfrow=c(2,1))# same oma as above
plot(lm.SR, which = 1:2, sub.caption = "Saving Rates, n=50, p=5")
}
\keyword{hplot}
\keyword{regression}
\eof
\name{plot.table}
\alias{plot.table}
\title{Plot Methods for `table' Objects}
\description{
  This is a method of the generic \code{plot} function for
  (contingency) \code{\link{table}} objects.  Whereas for two- and more
  dimensional tables, a \code{\link{mosaicplot}} is drawn,
  one-dimensional ones are plotted \dQuote{bar like}.
}
\usage{
%% Improvement ideas: see code definition, currently in ../R/plot.R
\method{plot}{table}(x, type = "h", ylim = c(0, max(x)), lwd = 2,
      xlab = NULL, ylab = NULL, frame.plot = is.num, \dots)
}
\arguments{
  \item{x}{a \code{\link{table}} (like) object.}
  \item{type}{plotting type.}
  \item{ylim}{range of y-axis.}
  \item{lwd}{line width for bars when \code{type = "h"} is used in the 1D case.}
  \item{xlab, ylab}{x- and y-axis labels.}
  \item{frame.plot}{logical indicating if a frame (\code{\link{box}})
    should be drawn in the 1D case.  Defaults to true when \code{x} has
    \code{\link{dimnames}} coerceable to numbers.}
  \item{\dots}{further graphical arguments, see \code{\link{plot.default}}.}
}
\details{
  The current implementation (R 1.2) is somewhat experimental and will
  be improved and extended.
}
\seealso{\code{\link{plot.factor}}, the \code{\link{plot}} method for factors.}

\examples{
## 1-d tables
(Poiss.tab <- table(N = rpois(200, lam= 5)))
plot(Poiss.tab, main = "plot(table(rpois(200, lam=5)))")

data(state)
plot(table(state.division))

## 4-D :
data(Titanic)
plot(Titanic, main ="plot(Titanic, main= *)")

}
\keyword{hplot}
\keyword{category}
\eof
\name{plot.ts}
\alias{plot.ts}
\alias{lines.ts}
\title{Plotting Time-Series Objects}
\description{
  Plotting method for objects inheriting from class \code{"ts"}.
}
\usage{
\method{plot}{ts}(x, y = NULL, plot.type = c("multiple", "single"),
     xy.labels, xy.lines, panel = lines, nc, ...)

\method{lines}{ts}(x, \dots)
}
\arguments{
  \item{x, y}{time series objects, usually inheriting from class \code{"ts"}.}

  \item{plot.type}{for multivariate time series, should the series by
    plotted separately (with a common time axis) or on a single plot?}

  \item{xy.labels}{logical, indicating if \code{\link{text}()} labels
    should be used for an x-y plot, \emph{or} character, supplying a
    vector of labels to be used.  The default is to label for up to 150
    points, and not for more.}

  \item{xy.lines}{logical, indicating if \code{\link{lines}}
    should be drawn for an x-y plot.  Defaults to the value of
    \code{xy.labels} if that is logical, otherwise to \code{TRUE}.}

  \item{panel}{a \code{function(x, col, bg, pch, type, ...)} which gives the
    action to be carried out in each panel of the display for
    \code{plot.type="multiple"}.  The default is \code{lines}.}

  \item{nc}{the number of columns to use when \code{type="multiple"}.
    Defaults to 1 for up to 4 series, otherwise to 2.}

  \item{\dots}{additional graphical arguments, see \code{\link{plot}},
    \code{\link{plot.default}} and \code{\link{par}}.}
}
\details{
  If \code{y} is missing, this function creates a time series
  plot, for multivariate series of one of two kinds depending on
  \code{plot.type}.

  If \code{y} is present, both \code{x} and \code{y} must be univariate,
  and a \dQuote{scatter} plot \code{y ~ x} will be drawn, enhanced by
  using \code{\link{text}} if \code{xy.labels} is
  \code{\link{TRUE}} or \code{character}, and \code{\link{lines}} if
  \code{xy.lines} is \code{TRUE}.
}
\seealso{
  \code{\link{ts}} for basic time series construction and access
  functionality.
}
\examples{
## Multivariate
z <- ts(matrix(rt(300, df = 3), 100, 3), start=c(1961, 1), frequency=12)
plot(z, type = "b")    # multiple
plot(z, plot.type="single", lty=1:3, col=4:2)

## A phase plot:
data(nhtemp)
plot(nhtemp, c(nhtemp[-1], NA), cex = .8, col="blue",
     main = "Lag plot of New Haven temperatures")
## a clearer way to do this would be
\dontrun{library(ts)
plot(nhtemp, lag(nhtemp, 1), cex = .8, col="blue",
     main = "Lag plot of New Haven temperatures")
}

library(ts)  # normally loaded

data(sunspots)
## xy.lines and xy.labels are FALSE for large series:
plot(lag(sunspots, 1), sunspots, pch = ".")

data(EuStockMarkets)
SMI <- EuStockMarkets[, "SMI"]
plot(lag(SMI,  1), SMI, pch = ".")
plot(lag(SMI, 20), SMI, pch = ".", log = "xy",
     main = "4 weeks lagged SMI stocks -- log scale", xy.lines= TRUE)
}
\keyword{hplot}
\keyword{ts}
\eof
\name{plot.window}
\alias{plot.window}
\title{Set up World Coordinates for Graphics Window}
\description{
  This function sets up the world coordinate system for a graphics
  window.  It is called by higher level functions such as
  \code{\link{plot.default}} (\emph{after} \code{\link{plot.new}}).
}
\usage{
plot.window(xlim, ylim, log = "", asp = NA, \dots)
}
\arguments{
  \item{xlim, ylim}{numeric of length 2, giving the x and y coordinates
    ranges.}
  \item{log}{character; indicating which axes should be in log scale.}
  \item{asp}{numeric, giving the \bold{asp}ect ratio y/x.}
  \item{\dots}{further graphical parameters as in \code{\link{par}}.}
}
\details{
  Note that if \code{asp} is a finite positive value then the window is
  set up so that one data unit in the x direction is equal in length to
  \code{asp} \eqn{\times}{*} one data unit in the y direction.

  The special case \code{asp == 1} produces plots where distances
  between points are represented accurately on screen.  Values with
  \code{asp > 1} can be used to produce more accurate maps when using
  latitude and longitude.

  Usually, one should rather use the higher level functions such as
  \code{\link{plot}}, \code{\link{hist}}, \code{\link{image}}, \dots,
  instead and refer to their help pages for explanation of the
  arguments.
}
\seealso{
  \code{\link{xy.coords}},
  \code{\link{plot.xy}},
  \code{\link{plot.default}}.
}
\examples{
##--- An example for the use of 'asp' :
library(mva)  # normally loaded
data(eurodist)
loc <- cmdscale(eurodist)
rx <- range(x <- loc[,1])
ry <- range(y <- -loc[,2])
plot(x, y, type="n", asp=1, xlab="", ylab="")
abline(h = pretty(rx, 10), v = pretty(ry, 10), col = "lightgray")
text(x, y, names(eurodist), cex=0.8)
}
\keyword{aplot}
\eof
\name{plot.xy}
\alias{plot.xy}
\title{Basic Internal Plot Function}
\description{
  This is \emph{the} internal function that does the basic plotting of
  points and lines.  Usually, one should rather use the higher level
  functions instead and refer to their help pages for explanation of the
  arguments.
}
\usage{
plot.xy(xy, type, pch=1, lty="solid", col=par("fg"), bg=NA, cex=1, \dots)
}
\arguments{
  \item{xy}{A four-element list as results from
    \code{\link{xy.coords}}.}
  \item{type}{1 character code.}
  \item{pch}{character or integer code for kind of points/lines, see
    \code{\link{points.default}}.}
  \item{lty}{line type code, see \code{\link{lines}}.}
  \item{col}{color code or name, see \code{\link{colors}},
    \code{\link{palette}}.}
  \item{bg}{background (\dQuote{fill}) color for open plot symbols.}
  \item{cex}{character expansion.}
  \item{\dots}{further graphical parameters.}
}
\seealso{
  \code{\link{plot}},
  \code{\link{plot.default}},
  \code{\link{points}},
  \code{\link{lines}}.
}
\examples{
points.default # to see how it calls "plot.xy(xy.coords(x, y), ...)"
}
\keyword{aplot}
\eof
\name{plot.default}
\alias{plot.default}
\title{The Default Scatterplot Function}
\description{
  Draw a scatter plot with \dQuote{decorations} such as axes and titles
  in the active graphics window.
}
\usage{
\method{plot}{default}(x, y = NULL, type = "p",  xlim = NULL, ylim = NULL,
     log = "", main = NULL, sub = NULL, xlab = NULL, ylab = NULL,
     ann = par("ann"), axes = TRUE, frame.plot = axes,
     panel.first = NULL, panel.last = NULL,
     col = par("col"), bg = NA, pch = par("pch"),
     cex = 1, lty = par("lty"), lab = par("lab"),
     lwd = par("lwd"), asp = NA, \dots)
}
\arguments{
  \item{x,y}{the \code{x} and \code{y} arguments provide the x and y
    coordinates for the plot.  Any reasonable way of defining the
    coordinates is acceptable.  See the function \code{\link{xy.coords}}
    for details.}
  \item{type}{1-character string giving the type of plot desired.  The
    following values are possible, for details, see \code{\link{plot}}:
    \code{"p"} for points, \code{"l"} for lines,
    \code{"o"} for overplotted points and lines,
    \code{"b"}, \code{"c"}) for (empty if \code{"c"}) points joined by lines,
    \code{"s"} and \code{"S"} for stair steps and
    \code{"h"} for histogram-like vertical lines.  Finally,
    \code{"n"} does not produce any points or lines.}
  \item{xlim}{the x limits (min,max) of the plot.}
  \item{ylim}{the y limits of the plot.}
  \item{log}{a character string which contains \code{"x"} if the x axis
    is to be logarithmic, \code{"y"} if the y axis is to be logarithmic
    and \code{"xy"} or \code{"yx"} if both axes are to be logarithmic.}

  \item{main}{a main title for the plot.}
  \item{sub}{a sub title for the plot.}
  \item{xlab}{a label for the x axis.}
  \item{ylab}{a label for the y axis.}

  \item{ann}{a logical value indicating whether the default annotation
    (title and x and y axis labels) should appear on the plot.}
  \item{axes}{a logical value indicating whether axes should be drawn on
    the plot.}
  \item{frame.plot}{a logical indicating whether a box should be drawn
    around the plot.}

  \item{panel.first}{an expression to be evaluated after the plot axes
    are set up but before any plotting takes place.  This can be useful
    for drawing background grids or scatterplot smooths.}
  \item{panel.last}{an expression to be evaluated after plotting has
    taken place.}

  \item{col}{The colors for lines and points.  Multiple colors can be
    specified so that each point can be given its own color.  If there
    are fewer colors than points they are recycled in the standard
    fashion.  Lines will all be plotted in the first colour specified.}
  \item{bg}{background color for open plot symbols, see
    \code{\link{points}}.}
  \item{pch}{a vector of plotting characters or symbols: see \code{\link{points}}.}
  \item{cex}{a numerical vector giving the amount by which plotting text
    and symbols should be scaled relative to the default.}
  \item{lty}{the line type, see \code{\link{par}}.}
  \item{lab}{the specification for the (approximate) numbers of tick
    marks on the x and y axes.}
  \item{lwd}{the line width \bold{not yet supported for postscript}.}
  \item{asp}{the \eqn{y/x} aspect ratio, see \code{\link{plot.window}}.}
  \item{\dots}{graphical parameters as in \code{\link{par}} may also be
    passed as arguments.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Cleveland, W. S. (1985)
  \emph{The Elements of Graphing Data.}
  Monterey, CA: Wadsworth.
}
\seealso{
  \code{\link{plot}}, \code{\link{plot.window}}, \code{\link{xy.coords}}.
}
\examples{
data(cars)
Speed <- cars$speed
Distance <- cars$dist
plot(Speed, Distance, panel.first = grid(8,8),
     pch = 0, cex = 1.2, col = "blue")
plot(Speed, Distance,
     panel.first = lines(lowess(Speed, Distance), lty = "dashed"),
     pch = 0, cex = 1.2, col = "blue")

## Show the different plot types
x <- 0:12
y <- sin(pi/5 * x)
op <- par(mfrow = c(3,3), mar = .1+ c(2,2,3,1))
for (tp in c("p","l","b",  "c","o","h",  "s","S","n")) {
   plot(y ~ x, type = tp,
        main = paste("plot(*, type = \"",tp,"\")",sep=""))
   if(tp == "S") {
      lines(x,y, type = "s", col = "red", lty = 2)
      mtext("lines(*, type = \"s\", ...)", col = "red", cex=.8)
   }
}
par(op)

##--- Log-Log Plot  with  custom axes
lx <- seq(1,5, length=41)
yl <- expression(e^{-frac(1,2) * {log[10](x)}^2})
y <- exp(-.5*lx^2)
op <- par(mfrow=c(2,1), mar=par("mar")+c(0,1,0,0))
plot(10^lx, y, log="xy", type="l", col="purple",
     main="Log-Log plot", ylab=yl, xlab="x")
plot(10^lx, y, log="xy", type="o", pch='.', col="forestgreen",
     main="Log-Log plot with custom axes", ylab=yl, xlab="x",
     axes = FALSE, frame.plot = TRUE)
axis(1, at = my.at <- 10^(1:5), labels = formatC(my.at, format="fg"))
at.y <- 10^(-5:-1)
axis(2, at = at.y, labels = formatC(at.y, format="fg"), col.axis="red")
par(op)
}
\keyword{hplot}
\eof
\name{plot.factor}
\title{Plotting Factor Variables}
\usage{
\method{plot}{factor}(x, y, legend.text = levels(y), \dots)
}
\alias{plot.factor}
\arguments{
    \item{x,y}{numeric or factor.  \code{y} may be missing.}
    \item{legend.text}{a vector of text used to construct a legend for
        the plot. Only used if \code{y} is present and a factor.}
    \item{\dots}{Further arguments to \code{\link{plot}}, see also
        \code{\link{par}}.}
}
\description{
  This functions implements a \dQuote{scatterplot} method for
  \code{\link{factor}} arguments of the \emph{generic}
  \code{\link{plot}} function.
  Actually, \code{\link{boxplot}} or \code{\link{barplot}} are used when
  appropriate.
}
\seealso{
    \code{\link{plot.default}}, \code{\link{plot.formula}},
    \code{\link{barplot}}, \code{\link{boxplot}}.
}
\examples{
data(PlantGrowth)
plot(PlantGrowth)                                # -> plot.data.frame
plot(weight ~ group, data = PlantGrowth)         # numeric vector ~ factor
plot(cut(weight, 2) ~ group, data = PlantGrowth) # factor ~ factor
## passing "..." to barplot() eventually:
plot(cut(weight, 3) ~ group, data = PlantGrowth, density = 16*(1:3),col=NULL)

plot(PlantGrowth$group, axes=FALSE, main="no axes")# extremly silly
}
\keyword{hplot}
\eof
\name{plot.formula}
\alias{plot.formula}
\alias{lines.formula}
\alias{points.formula}
\title{Formula Notation for Scatterplots}
\description{
  Specify a scatterplot or add points or lines via a formula.
}
\usage{
\method{plot}{formula}(formula, data = parent.frame(), \dots, subset,
             ylab = varnames[response], ask = TRUE)

\method{points}{formula}(formula, data = parent.frame(), \dots, subset)

\method{lines}{formula}(formula, data = parent.frame(), \dots, subset)
}
\arguments{
  \item{formula}{a \code{\link{formula}}, such as \code{y ~ x}.}
  \item{data}{a data.frame (or list) from which the variables in
    \code{formula} should be taken.}
  \item{\dots}{Further graphical parameters may also be passed as
    arguments, see \code{\link{par}}.  \code{horizontal = TRUE}
    is also accepted.}
  \item{subset}{an optional vector specifying a subset of observations
    to be used in the fitting process.}
  \item{ylab}{the y label of the plot(s).}
  \item{ask}{logical, see \code{\link{par}}.}
}
\details{
  Both the terms in the formula and the \code{\dots} arguments are
  evaluated in \code{data} enclosed in \code{parent.frame()} if
  \code{data} is a list or a data frame. The terms of the formula and
  those arguments in \code{\dots} that are of the same length as
  \code{data} are subjected to the subsetting specified in
  \code{subset}. If the formula in \code{plot.formula} contains more
  than one non-response term, a series of plots of y against each term
  is given.  A plot against the running index can be specified as
  \code{plot(y~1)}.

  If \code{y} is an object (ie. has a \code{\link[base]{class}} attribute)
  then \code{plot.formula} looks for a plot method for that class first.
  Otherwise, the class of \code{x} will determine the type of the plot.
  For factors this will be a parallel boxplot, and argument
  \code{horizontal = TRUE} can be used (see \code{\link{boxplot}}).
}
\value{
  These functions are invoked for their side effect of drawing 
  in the active graphics device.
}
\seealso{
  \code{\link{plot.default}}, \code{\link{plot.factor}}.
}
\examples{
data(airquality)
op <- par(mfrow=c(2,1))
plot(Ozone ~ Wind, data = airquality, pch=as.character(Month))
plot(Ozone ~ Wind, data = airquality, pch=as.character(Month),
     subset = Month != 7)
par(op)
}
\keyword{hplot}
\eof
\name{plot.histogram}
\alias{plot.histogram}
\alias{lines.histogram}
\title{Plot Histograms}
\description{
  These are methods for objects of class \code{"histogram"}, typically
  produced by \code{\link{hist}}.
}
\usage{
\method{plot}{histogram}(x, freq = equidist, density = NULL, angle = 45,
               col = NULL, border = par("fg"), lty = NULL,
               main = paste("Histogram of", x$xname), sub = NULL,
               xlab = x$xname, ylab, xlim = range(x$breaks), ylim = NULL,
               axes = TRUE, labels = FALSE, add = FALSE, \dots)

\method{lines}{histogram}(x, \dots)
}
\arguments{
  \item{x}{a \code{histogram} object, or a list with components
    \code{density}, \code{mid}, etc, see \code{\link{hist}} for
    information about the components of \code{x}.}
  \item{freq}{logical; if \code{TRUE}, the
    histogram graphic is to present a representation of frequencies, i.e,
    \code{x$counts}; if \code{FALSE}, \emph{relative} frequencies
    (\dQuote{probabilities}), i.e., \code{x$density}, are plotted.  The
    default is true for equidistant \code{breaks} and false otherwise.}
  \item{col}{a colour to be used to fill the bars.  The default of
    \code{NULL} yields unfilled bars.}
  \item{border}{the color of the border around the bars.}
  \item{angle, density}{select shading of bars by lines:
    see \code{\link{rect}}.}
  \item{lty}{the line type used for the bars, see also \code{\link{lines}}.}
  \item{main, sub, xlab, ylab}{these arguments to \code{title} have useful
    defaults here.}
  \item{xlim, ylim}{the range of x and y values with sensible defaults.}
  \item{axes}{logical, indicating if axes should be drawn.}
  \item{labels}{logical or character.  Additionally draw labels on top of bars,
    if not \code{FALSE}; if \code{TRUE}, draw the counts or rounded
    densities; if \code{labels} is a \code{character}, draw itself.}
  \item{add}{logical.  If \code{TRUE}, only the bars are added to the
    current plot.  This is what \code{lines.histogram(*)} does.}
  \item{\dots}{further graphical parameters to \code{title} and \code{axis}.}
}
\details{
  \code{lines.histogram(*)} is the same as
  \code{plot.histogram(*, add = TRUE)}.
}
\seealso{
  \code{\link{hist}},
  \code{\link{stem}},
  \code{\link{density}}.
}
\examples{
data(women)
str(wwt <- hist(women$weight, nc= 7, plot = FALSE))
plot(wwt, labels = TRUE) # default main & xlab using wwt$xname
plot(wwt, border = "dark blue", col = "light blue",
     main = "Histogram of 15 women's weights", xlab = "weight [pounds]")

## Fake "lines" example, using non-default labels:
w2 <- wwt; w2$counts <- w2$counts - 1
lines(w2, col = "Midnight Blue", labels = ifelse(w2$counts, "> 1", "1"))
}
\keyword{hplot}
\keyword{iplot}
\eof
\name{plotmath}
\alias{plotmath}
\title{Mathematical Annotation in R}
\description{
  If the \code{text} argument to one of the text-drawing functions
  (\code{\link{text}}, \code{\link{mtext}}, \code{\link{axis}}) in \R
  is an expression, the argument is interpreted as a mathematical
  expression and the output will be formatted according to TeX-like
  rules.  Expressions can also be used for titles, subtitles and
  x- and y-axis labels (but not for axis labels on \code{persp} plots).
}
\details{
  A mathematical expression must obey the normal rules of syntax for any
  \R expression, but it is interpreted according to very different rules
  than for normal \R expressions.

  It is possible to produce many different mathematical symbols, generate
  sub- or superscripts, produce fractions, etc.

  The output from \code{demo(plotmath)} includes several tables which
  show the available features.  In these tables, the columns of grey text
  show sample \R expressions, and the columns of black text show the
  resulting output.

  The available features are also described in the tables below:

  \tabular{ll}{
    \bold{Syntax} \tab \bold{Meaning} \cr
    \code{x + y}   \tab x plus y   \cr
    \code{x - y}   \tab x minus y \cr
    \code{x*y}    \tab juxtapose x and y \cr
    \code{x/y}    \tab x forwardslash y \cr
    \code{x \%+-\% y}   \tab x plus or minus y \cr
    \code{x \%/\% y}   \tab x divided by y \cr
    \code{x \%*\% y}   \tab x times y \cr
    \code{x[i]}   \tab x subscript i \cr
    \code{x^2}    \tab x superscript 2 \cr
    \code{paste(x, y, z)} \tab juxtapose x, y, and z \cr
    \code{sqrt(x)}   \tab square root of x \cr
    \code{sqrt(x, y)}   \tab yth root of x \cr
    \code{x == y}   \tab x equals y \cr
    \code{x != y}   \tab x is not equal to y \cr
    \code{x < y}   \tab x is less than y \cr
    \code{x <= y}   \tab x is less than or equal to y \cr
    \code{x > y}   \tab x is greater than y \cr
    \code{x >= y}   \tab x is greater than or equal to y \cr
    \code{x \%~~\% y}   \tab x is approximately equal to y \cr
    \code{x \%=~\% y}   \tab x and y are congruent \cr
    \code{x \%==\% y}   \tab x is defined as y \cr
    \code{x \%prop\% y}  \tab x is proportional to y \cr
    \code{plain(x)}   \tab draw x in normal font \cr
    \code{bold(x)}   \tab draw x in bold font \cr
    \code{italic(x)}   \tab draw x in italic font \cr
    \code{bolditalic(x)} \tab draw x in bolditalic font \cr
    \code{list(x, y, z)} \tab comma-separated list \cr
    \code{...}    \tab ellipsis (height varies) \cr
    \code{cdots}   \tab ellipsis (vertically centred) \cr
    \code{ldots}   \tab ellipsis (at baseline) \cr
    \code{x \%subset\% y} \tab x is a proper subset of y \cr
    \code{x \%subseteq\% y} \tab x is a subset of y \cr
    \code{x \%notsubset\% y} \tab x is not a subset of y \cr
    \code{x \%supset\% y} \tab x is a proper superset of y \cr
    \code{x \%supseteq\% y} \tab x is a superset of y \cr
    \code{x \%in\% y}   \tab x is an element of y \cr
    \code{x \%notin\% y} \tab x is not an element of y \cr
    \code{hat(x)}   \tab x with a circumflex \cr
    \code{tilde(x)}   \tab x with a tilde \cr
    \code{dot(x)} \tab x with a dot \cr
    \code{ring(x)}   \tab x with a ring \cr
    \code{bar(xy)}   \tab xy with bar \cr
    \code{widehat(xy)}   \tab xy with a wide circumflex \cr
    \code{widetilde(xy)} \tab xy with a wide tilde \cr
    \code{x \%<->\% y}   \tab x double-arrow y \cr
    \code{x \%->\% y}   \tab x right-arrow y \cr
    \code{x \%<-\% y}   \tab x left-arrow y \cr
    \code{x \%up\% y}   \tab x up-arrow y \cr
    \code{x \%down\% y}  \tab x down-arrow y \cr
    \code{x \%<=>\% y}   \tab x is equivalent to y \cr
    \code{x \%=>\% y}   \tab x implies y \cr
    \code{x \%<=\% y}   \tab y implies x \cr
    \code{x \%dblup\% y}   \tab x double-up-arrow y \cr
    \code{x \%dbldown\% y} \tab x double-down-arrow y \cr
    \code{alpha} -- \code{omega} \tab Greek symbols \cr
    \code{Alpha} -- \code{Omega} \tab uppercase Greek symbols \cr
    \code{infinity}   \tab infinity symbol \cr
    \code{partialdiff} \tab partial differential symbol \cr
    \code{32*degree}   \tab 32 degrees \cr
    \code{60*minute}   \tab 60 minutes of angle \cr
    \code{30*second}   \tab 30 seconds of angle \cr
    \code{displaystyle(x)} \tab draw x in normal size (extra spacing) \cr
    \code{textstyle(x)}  \tab draw x in normal size \cr
    \code{scriptstyle(x)} \tab draw x in small size \cr
    \code{scriptscriptstyle(x)} \tab draw x in very small size \cr
    \code{x ~~ y}        \tab put extra space between x and y \cr
    \code{x + phantom(0) + y} \tab leave gap for "0", but don't draw it \cr
    \code{x + over(1, phantom(0))} \tab leave vertical gap for "0" (don't draw) \cr
    \code{frac(x, y)}   \tab x over y \cr
    \code{over(x, y)}   \tab x over y \cr
    \code{atop(x, y)}   \tab x over y (no horizontal bar) \cr
    \code{sum(x[i], i==1, n)} \tab sum x[i] for i equals 1 to n \cr
    \code{prod(plain(P)(X==x), x)} \tab product of P(X=x) for all values of x \cr
    \code{integral(f(x)*dx, a, b)} \tab definite integral of f(x) wrt x \cr
    \code{union(A[i], i==1, n)} \tab union of A[i] for i equals 1 to n \cr
    \code{intersect(A[i], i==1, n)} \tab intersection of A[i] \cr
    \code{lim(f(x), x \%->\% 0)} \tab limit of f(x) as x tends to 0 \cr
    \code{min(g(x), x > 0)} \tab minimum of g(x) for x greater than 0 \cr
    \code{inf(S)}        \tab infimum of S \cr
    \code{sup(S)}   \tab supremum of S \cr
    \code{x^y + z}   \tab normal operator precedence \cr
    \code{x^(y + z)}    \tab visible grouping of operands \cr
    \code{x^{y + z}}  \tab invisible grouping of operands \cr
    \code{group("(",list(a, b),"]")} \tab specify left and right delimiters \cr
    \code{bgroup("(",atop(x,y),")")} \tab use scalable delimiters \cr
    \code{group(lceil, x, rceil)} \tab special delimiters \cr
  }
}
\references{
  Murrell, P. and Ihaka, R. (2000) An approach to providing
  mathematical annotation in plots.
  \emph{Journal of Computational and Graphical Statistics},
  \bold{9}, 582--599.
}
\seealso{
  \code{demo(plotmath)},
  \code{\link{axis}},
  \code{\link{mtext}},
  \code{\link{text}},
  \code{\link{title}},
  \code{\link{substitute}}
  \code{\link{quote}}, \code{\link{bquote}}
}
\examples{
x <- seq(-4, 4, len = 101)
y <- cbind(sin(x), cos(x))
matplot(x, y, type = "l", xaxt = "n",
        main = expression(paste(plain(sin) * phi, "  and  ",
                                plain(cos) * phi)),
        ylab = expression("sin" * phi, "cos" * phi), # only 1st is taken
        xlab = expression(paste("Phase Angle ", phi)),
        col.main = "blue")
axis(1, at = c(-pi, -pi/2, 0, pi/2, pi),
     lab = expression(-pi, -pi/2, 0, pi/2, pi))


## How to combine "math" and numeric variables :
plot(1:10, type="n", xlab="", ylab="", main = "plot math & numbers")
theta <- 1.23 ; mtext(bquote(hat(theta) == .(theta)))
for(i in 2:9)
    text(i,i+1, substitute(list(xi,eta) == group("(",list(x,y),")"),
                           list(x=i, y=i+1)))

plot(1:10, 1:10)
text(4, 9, expression(hat(beta) == (X^t * X)^{-1} * X^t * y))
text(4, 8.4, "expression(hat(beta) == (X^t * X)^{-1} * X^t * y)",
     cex = .8)
text(4, 7, expression(bar(x) == sum(frac(x[i], n), i==1, n)))
text(4, 6.4, "expression(bar(x) == sum(frac(x[i], n), i==1, n))",
     cex = .8)
text(8, 5, expression(paste(frac(1, sigma*sqrt(2*pi)), " ",
                            plain(e)^{frac(-(x-mu)^2, 2*sigma^2)})),
     cex = 1.2)
}
\keyword{aplot}
\eof
\name{pmatch}
\title{Partial String Matching}
\usage{
pmatch(x, table, nomatch = NA, duplicates.ok = FALSE)
}
\alias{pmatch}
\arguments{
  \item{x}{the values to be matched.}
  \item{table}{the values to be matched against.}
  \item{nomatch}{the value returned at non-matching or multiply
    partially matching positions.}
  \item{duplicates.ok}{should elements be in \code{table} be used more
    than once?}
}
\description{
  \code{pmatch} seeks matches for the elements of its first argument
  among those of its second.
}
\details{
  The behaviour differs by the value of \code{duplicates.ok}. Consider
  first the case if this is true.  First exact matches are considered,
  and the positions of the first exact matches are recorded. Then unique
  partial matches are considered, and if found recorded. (A partial
  match occurs if the whole of the element of \code{x} matches the
  beginning of the element of \code{table}.)  Finally,
  all remaining elements of \code{x} are regarded as unmatched.
  In addition, an empty string can match nothing, not even an exact
  match to an empty string.  This is the appropriate behaviour for
  partial matching of character indices, for example.

  If \code{duplicates.ok} is \code{FALSE}, values of \code{table} once
  matched are excluded from the search for subsequent matches.  This
  behaviour is equivalent to the \R algorithm for argument
  matching, except for the consideration of empty strings (which in
  argument matching are matched after exact and partial matching to any
  remaining arguments).

  \code{\link{charmatch}} is similar to \code{pmatch} with
  \code{duplicates.ok} true, the differences being that it
  differentiates between no match and an ambiguous partial match,  it
  does match empty strings, and it does not allow multiple exact matches.
}
\value{
  A numeric vector of integers (including \code{NA} if \code{nomatch =
    NA}) of the same length as \code{x}, giving the indices of the
  elements in \code{table} which matched, or \code{nomatch}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Chambers, J. M. (1998)
  \emph{Programming with Data. A Guide to the S Language}.
  Springer.
}
\seealso{
  \code{\link{match}}, \code{\link{charmatch}} and
  \code{\link{match.arg}}, \code{\link{match.fun}},
  \code{\link{match.call}}, for function argument matching etc.,
  \code{\link{grep}} etc for more general (regexp) matching of strings.
}
\examples{
pmatch("", "")                             # returns NA
pmatch("m",   c("mean", "median", "mode")) # returns NA
pmatch("med", c("mean", "median", "mode")) # returns 2

pmatch(c("", "ab", "ab"), c("abc", "ab"), dup=FALSE)
pmatch(c("", "ab", "ab"), c("abc", "ab"), dup=TRUE)
## compare
charmatch(c("", "ab", "ab"), c("abc", "ab"))
}
\keyword{character}
\eof
\name{points}
\alias{points}
\alias{points.default}
\title{Add Points to a Plot}
\description{
  \code{points} is a generic function to draw a sequence of points at
  the specified coordinates.  The specified character(s) are plotted,
  centered at the coordinates.
}
\usage{
points(x, \dots)

\method{points}{default}(x, y = NULL, type = "p", pch = par("pch"),
       col = par("col"), bg = NA, cex = 1, \dots)
}
\arguments{
  \item{x, y}{coordinate vectors of points to plot.}
  \item{type}{character indicating the type of plotting; actually any of
    the \code{type}s as in \code{\link{plot}}.}
  \item{pch}{plotting \dQuote{character}, i.e., symbol to use.  \code{pch} can
    either be a \code{\link{character}} or an integer code for a set of
    graphics symbols.  The full set of S symbols is available with
    \code{pch=0:18}, see the last picture from \code{example(points)},
    i.e., the examples below.
    % (currently, \R uses circles instead of octagons).

    In addition, there is a special set of \R plotting symbols which
    can be obtained with \code{pch=19:25} and \code{21:25} can be
    colored and filled with different colors:
    \itemize{
      \item \code{pch=19}: solid circle,
      \item \code{pch=20}: bullet (smaller circle),
      \item \code{pch=21}: circle,
      \item \code{pch=22}: square,
      \item \code{pch=23}: diamond,
      \item \code{pch=24}: triangle point-up,
      \item \code{pch=25}: triangle point down.
    }
    Values \code{pch=26:32} are currently unused, and \code{pch=32:255}
    give the text symbol in the encoding in use (see \code{\link{postscript}}).
  }
  \item{col}{color code or name, see \code{\link{par}}.}
  \item{bg}{background (\dQuote{fill}) color for open plot symbols}
  \item{cex}{character expansion: a numerical vector.}
  \item{\dots}{Further graphical parameters (see \code{\link{plot.xy}}
    and \code{\link{par}}) may also be supplied as arguments.}
}
\details{
  The coordinates can be passed in a plotting structure
  (a list with \code{x} and \code{y} components), a two-column matrix, a
  time series, \dots.  See \code{\link{xy.coords}}.

  Arguments \code{pch}, \code{col}, \code{bg} and \code{cex} can be
  vectors (which will be recycled as needed) giving a value for each
  point plotted. 
  Points whose \code{x}, \code{y}, \code{pch}, \code{col} or \code{cex}
  value is \code{NA} are omitted from the plot.
  
  Graphical parameters are permitted as arguments to this function.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{plot}}, \code{\link{lines}}, and the underlying
  \dQuote{primitive} \code{\link{plot.xy}}.
}
\examples{
plot(-4:4, -4:4, type = "n")# setting up coord. system
points(rnorm(200), rnorm(200), col = "red")
points(rnorm(100)/2, rnorm(100)/2, col = "blue", cex = 1.5)

op <- par(bg = "light blue")
x <- seq(0,2*pi, len=51)
## something "between type='b' and type='o'":
plot(x, sin(x), type="o", pch=21, bg=par("bg"), col = "blue", cex=.6,
 main='plot(..., type="o", pch=21, bg=par("bg"))')
par(op)

##-------- Showing all the extra & some char graphics symbols ------------
Pex <- 3 ## good for both .Device=="postscript" and "x11"
ipch <- 1:(np <- 25+11); k <- floor(sqrt(np)); dd <- c(-1,1)/2
rx <- dd + range(ix <- (ipch-1) \%/\% k)
ry <- dd + range(iy <- 3 + (k-1)-(ipch-1) \%\% k)
pch <- as.list(ipch)
pch[25+ 1:11] <- as.list(c("*",".", "o","O","0","+","-",":","|","\%","#"))
plot(rx, ry, type="n", axes = FALSE, xlab = "", ylab = "",
     main = paste("plot symbols :  points (...  pch = *, cex =", Pex,")"))
abline(v = ix, h = iy, col = "lightgray", lty = "dotted")
for(i in 1:np) {
  pc <- pch[[i]]
  points(ix[i], iy[i], pch = pc, col = "red", bg = "yellow", cex = Pex)
  ## red symbols with a yellow interior (where available)
  text(ix[i] - .3, iy[i], pc, col = "brown", cex = 1.2)
}
}
\keyword{aplot}
\eof
\name{poly}
\alias{poly}
\alias{polym}
\alias{predict.poly}
\alias{makepredictcall.poly}
\title{Compute Orthogonal Polynomials}
\usage{
poly(x, \dots, degree = 1, coefs = NULL)
polym(\dots, degree = 1)

\method{predict}{poly}(object, newdata, \dots)
}
\description{
  Returns or evaluates orthogonal polynomials of degree 1 to
  \code{degree} over the specified set of points \code{x}. These are all
  orthogonal to the constant polynomial of degree 0.
}
\arguments{
 \item{x, newdata}{a numeric vector at which to evaluate the
   polynomial. \code{x} can also be a matrix.}
 \item{degree}{the degree of the polynomial}
 \item{coefs}{for prediction, coefficients from a previous fit.}
 \item{object}{an object inheriting from class \code{"poly"}, normally
   the result of a call to \code{poly} with a single vector argument.}
 \item{\dots}{\code{poly, polym}: further vectors.\cr
   \code{predict.poly}: arguments to be passed to or from other methods.
 }
}
\value{
  For \code{poly} with a single vector argument:\cr
  A matrix with rows corresponding to points in \code{x} and columns
  corresponding to the degree, with attributes \code{"degree"} specifying
  the degrees of the columns and \code{"coefs"} which contains the
  centring and normalization constants used in constructing the
  orthogonal polynomials.  The matrix is given class
  \code{c("poly", "matrix")} as from \R 1.5.0.

  Other cases of \code{poly} and \code{polym}, and \code{predict.poly}:
  a matrix.
}
\details{
  Although formally \code{degree} should be named (as it follows
  \code{\dots}), an unnamed second argument of length 1 will be
  interpreted as the degree.
  
  The orthogonal polynomial is summarized by the coefficients, which can
  be used to evaluate it via the three-term recursion given in Kennedy
  \& Gentle (1980, pp. 343-4), and use in the \dQuote{predict} part of
  the code.
}
\note{
  This routine is intended for statistical purposes such as
  \code{contr.poly}: it does not attempt to orthogonalize to
  machine accuracy.
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S}.
  Wadsworth \& Brooks/Cole.

  Kennedy, W. J. Jr and Gentle, J. E. (1980)
  \emph{Statistical Computing} Marcel Dekker.
}

\seealso{\code{\link{contr.poly}}}

\examples{
(z <- poly(1:10, 3))
predict(z, seq(2, 4, 0.5))
poly(seq(4, 6, 0.5), 3, coefs = attr(z, "coefs"))

polym(1:4, c(1, 4:6), degree=3) # or just poly()
poly(cbind(1:4, c(1, 4:6)), degree=3)
}
\keyword{math}
\eof
\name{polygon}
\alias{polygon}
\title{Polygon Drawing}
\description{
  \code{polygon} draws the polygons whose vertices are
  given in \code{x} and \code{y}.
}
\synopsis{
polygon(x, y = NULL, density = NULL, angle = 45,
        border = NULL, col = NA, lty = NULL, xpd = NULL,
        ..debug.hatch = FALSE, \dots)
}
\usage{
polygon(x, y = NULL, density = NULL, angle = 45,
        border = NULL, col = NA, lty = NULL, xpd = NULL, \dots)
}
\arguments{
  \item{x,y}{vectors containing the coordinates of the vertices
    of the polygon.}
  \item{density}{the density of shading lines, in lines per inch.  The
    default value of \code{NULL} means that no shading lines are drawn.
    A zero value of \code{density} means no shading lines whereas
    negative values (and \code{NA}) suppress shading (and so allow
    color filling).}
  \item{angle}{the slope of shading lines, given as an angle
     in degrees (counter-clockwise).}
  \item{col}{the color for filling the polygon.
    The default, \code{NA}, is to leave polygons unfilled.}
  \item{border}{the color to draw the border.  The default, \code{NULL},
    uses \code{\link{par}("fg")}.  Use \code{border = NA} to omit borders.
    
    For compatibility with S, \code{border} can also be logical, it
    which case \code{FALSE} is equivalent to \code{NA} (borders omitted)
    and \code{TRUE} is equivalent to \code{NULL} (use the foreground colour),
  }
  \item{lty}{the line type to be used, as in \code{\link{par}}.}
  \item{xpd}{(where) should clipping take place?  Defaults to
    \code{\link{par}("xpd")}.}
  \item{\dots}{graphical parameters can be given as arguments to
    \code{polygon}.}
}
\details{
  The coordinates can be passed in a plotting structure
  (a list with \code{x} and \code{y} components), a two-column matrix,
  \dots.  See \code{\link{xy.coords}}.

  It is assumed that the polygon is closed by joining the last point to
  the first point.
 
  The coordinates can contain missing values.  The behaviour is similar
  to that of \code{\link{lines}}, except
  that instead of breaking a line into several lines, \code{NA}
  values break the polygon into several complete polygons
  (including closing the last point to the first point).  See
  the examples below.

  When multiple polygons are produced,
  the values of \code{density}, \code{angle}, \code{col}, \code{border},
  and \code{lty} are recycled in the usual manner.
}
\section{Bugs}{
  The present shading algorithm can produce incorrect results for
  self-intesecting polygons.
}
\author{The code implementing polygon shading was donated by
  Kevin Buhr \email{buhr@stat.wisc.edu}.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{segments}} for even more flexibility, \code{\link{lines}},
  \code{\link{rect}}, \code{\link{box}}, \code{\link{abline}}.

  \code{\link{par}} for how to specify colors.
}
\examples{
x <- c(1:9,8:1)
y <- c(1,2*(5:3),2,-1,17,9,8,2:9)
op <- par(mfcol=c(3,1))
for(xpd in c(FALSE,TRUE,NA)) {
  plot(1:10, main=paste("xpd =", xpd)) ; box("figure", col = "pink", lwd=3)
  polygon(x,y, xpd=xpd, col = "orange", lty=2, lwd=2, border = "red")
}
par(op)

n <- 100
xx <- c(0:n, n:0)
yy <- c(c(0,cumsum(rnorm(n))), rev(c(0,cumsum(rnorm(n)))))
plot   (xx, yy, type="n", xlab="Time", ylab="Distance")
polygon(xx, yy, col="gray", border = "red")
title("Distance Between Brownian Motions")

# Multiple polygons from NA values
# and recycling of col, border, and lty
op <- par(mfrow=c(2,1))
plot(c(1,9), 1:2, type="n")
polygon(1:9, c(2,1,2,1,1,2,1,2,1),
        col=c("red", "blue"),
        border=c("green", "yellow"),
        lwd=3, lty=c("dashed", "solid"))
plot(c(1,9), 1:2, type="n")
polygon(1:9, c(2,1,2,1,NA,2,1,2,1),
        col=c("red", "blue"),
        border=c("green", "yellow"),
        lwd=3, lty=c("dashed", "solid"))
par(op)

# Line-shaded polygons
plot(c(1,9), 1:2, type="n")
polygon(1:9, c(2,1,2,1,NA,2,1,2,1),
        density=c(10, 20), angle=c(-45, 45))
}
\keyword{aplot}
\eof
\name{polyroot}
\title{Find Zeros of a Real or Complex Polynomial}
\usage{
polyroot(z)
}
\alias{polyroot}
\arguments{
  \item{z}{the vector of polynomial coefficients in increasing order.}
}
\description{
  Find zeros of a real or complex polynomial.
}
\details{
  A polynomial of degree \eqn{n - 1},
  \deqn{
    p(x) = z_1 + z_2 x + \cdots + z_n x^{n-1}}{
    p(x) = z1 + z2 * x + \ldots + z[n] * x^(n-1)}
  is given by its coefficient vector \code{z[1:n]}.
  \code{polyroot} returns the \eqn{n-1} complex zeros of \eqn{p(x)}
  using the Jenkins-Traub algorithm.

  If the coefficient vector \code{z} has zeroes for the highest powers,
  these are discarded.
}
\value{
  A complex vector of length \eqn{n - 1}, where \eqn{n} is the position
  of the largest non-zero element of \code{z}. 
}
\references{
  Jenkins and Traub (1972)
  TOMS Algorithm 419.
  \emph{Comm. ACM}, \bold{15}, 97--99.
}
\seealso{
  \code{\link{uniroot}} for numerical root finding of arbitrary
  functions;
  \code{\link{complex}} and the \code{zero} example in the demos
  directory.
}
\examples{
polyroot(c(1, 2, 1))
round(polyroot(choose(8, 0:8)), 11) # guess what!
for (n1 in 1:4) print(polyroot(1:n1), digits = 4)
polyroot(c(1, 2, 1, 0, 0)) # same as the first
}
\keyword{math}
\eof
\name{pos.to.env}
\alias{pos.to.env}
\title{Convert Positions in the Search Path to Environments}
\description{
  Returns the environment at a specified position in the search path.
}
\usage{pos.to.env(x)}
\arguments{
  \item{x}{an integer between 1 and \code{length(search())}, the length
    of the search path.}
}
\details{
  Several \R functions for manipulating objects in environments (such as
  \code{\link{get}} and \code{\link{ls}}) allow specifying environments
  via corresponding positions in the search path.  \code{pos.to.env} is
  a convenience function for programmers which converts these positions
  to corresponding environments; users will typically have no need for
  it.
}
\examples{
pos.to.env(1) # R_GlobalEnv
# the next returns NULL, which is how package:base is represented.
pos.to.env(length(search()))
}
\keyword{utilities}
\eof
\name{postscript}
\alias{postscript}
\alias{ps.options}
\alias{.PostScript.Options}
\alias{.ps.prolog}
\title{PostScript Graphics}
\description{
  \code{postscript} starts the graphics device driver for producing
  PostScript graphics.

  The auxiliary function \code{ps.options} can be used to set and view
  (if called without arguments) default values for the arguments to
  \code{postscript}.
}
\synopsis{
postscript(file = ifelse(onefile, "Rplots.ps", "Rplot\%03d.ps"),
           onefile = TRUE, family, title = "R Graphics Output", \dots)
ps.options(\dots, reset = FALSE, override.check = FALSE)
}
%% The definitive doc is the source :-)
%% 	../../../main/devices.c  &   ../../../unix/devPS.c
\usage{
postscript(file = ifelse(onefile, "Rplots.ps", "Rplot\%03d.ps"),
           onefile = TRUE,
           paper, family, encoding, bg, fg,
           width, height, horizontal, pointsize,
           pagecentre, print.it, command, title = "R Graphics Output")

% paper, horizontal, width, height, family, pointsize, bg, fg)
ps.options(paper, horizontal, width, height, family, encoding,
           pointsize, bg, fg,
           onefile = TRUE, print.it = FALSE, append = FALSE,
           reset = FALSE, override.check = FALSE)
.PostScript.Options
}
\arguments{
  \item{file}{a character string giving the name of the file.  If it is
    \code{""}, the output is piped to the command given by
    the argument \code{command}.
#ifdef unix
    If it is \code{"|cmd"}, the output is piped to the command given
    by \file{cmd}.
#endif

    For use with \code{onefile=FALSE} give a \code{printf} format such
    as \code{"Rplot\%03d.ps"} (the default in that case).
  }
%  \item{\dots}{further options for \code{postscript()}.}
  \item{paper}{the size of paper in the printer.  The choices are
    \code{"a4"}, \code{"letter"}, \code{"legal"} and
    \code{"executive"} (and these can be capitalized).
    Also, \code{"special"} can be used, when the \code{width}
    and \code{height} specify the paper size.  A further choice is
    \code{"default"}, which is the default.  If this is selected, the
    papersize is taken from the option \code{"papersize"}
    if that is set and to \code{"a4"} if it is unset or empty.}
  \item{horizontal}{the orientation of the printed image, a
    logical. Defaults to true, that is landscape orientation.}
  \item{width, height}{the width and height of the graphics region in
    inches.  The default is to use the entire page less a 0.25 inch
    border on each side.}
  \item{family}{the font family to be used.  EITHER a single character
    string OR a character vector of length
    four or five.  See the section \sQuote{Families}.}
  \item{encoding}{the name of an encoding file. Defaults to
#ifdef unix
"ISOLatin1.enc"
#endif
#ifdef windows
"WinAnsi.enc"
#endif
    in the \file{R\_HOME/afm} directory, which is used
    if the path does not contain a path separator.  An extension
    \code{".enc"} can be omitted.}
  \item{pointsize}{the default point size to be used.}
  \item{bg}{the default background color to be used.
    If \code{"transparent"} (or an equivalent specification), no
    background is painted.}
  \item{fg}{the default foreground color to be used.}
  \item{onefile}{logical: if true (the default) allow multiple figures
    in one file.  If false, generate a file name containing the page
    number and use an EPSF header and no \code{DocumentMedia} comment.}
  \item{pagecentre}{logical: should the device region be centred on the
    page: defaults to true.}
  \item{print.it}{logical: should the file be printed when the device is
    closed?  (This only applies if \code{file} is a real file name.)}
  \item{command}{the command to be used for \dQuote{printing}.  Defaults to
    option \code{"printcmd"}; this can also be selected as
    \code{"default"}.}
  \item{append}{logical; currently \bold{disregarded}; just there for
    compatibility reasons.}
  \item{reset, override.check}{logical arguments passed to
    \code{\link{check.options}}.  See the Examples.}
  \item{title}{title string to embed in the file.}
}
\details{
  \code{postscript} opens the file \code{file} and the PostScript
  commands needed to plot any graphics requested are stored in that
  file.  This file can then be printed on a suitable device to obtain
  hard copy.

  A postscript plot can be printed via \code{postscript} in two ways.
  \enumerate{
    \item Setting \code{print.it = TRUE} causes the command given in
    argument \code{command} to be called with argument \code{"file"}
    when the device is closed.
    Note that the plot file is not deleted unless \code{command} arranges to
    delete it.

    \item \code{file=""} or \code{file="|cmd"} can be used to print
    using a pipe on systems that support \file{popen}.  Failure to open the
    command will probably be reported to the terminal but not to
    \file{popen}, in which case close the device by \code{dev.off}
    immediately.
  }
#ifdef windows
  Only the first of these will work on Windows, and the default
  \code{"printcmd"} is empty and will give an error if \code{print.it=TRUE}
  is used.  Suitable commands to spool a PostScript file to a printer
  can be found in \file{RedMon} suite available from
  \url{http://www.cs.wisc.edu/~ghost/index.html}.  The command will be run
  in a minimized window.   GSView 4.x provides
  \file{gsprint.exe} which may be even more convenient (it requires
  GhostScript version 6.0 or later).
#endif

  The postscript produced by \R is EPS (\emph{Encapsulated PostScript})
  compatible, and can be included into other documents, e.g., into
  LaTeX, using \code{\includegraphics{<filename>}}.  For use in this way
  you will probably want to set \code{horizontal = FALSE, onefile = FALSE,
    paper = "special"}.

  Most of the PostScript prologue used is taken from the \R character
  vector \code{.ps.prolog}.  This is marked in the output, and can be
  changed by changing that vector.  (This is only advisable for
  PostScript experts.)

  \code{ps.options} needs to be called before calling \code{postscript},
  and the default values it sets can be overridden by supplying
  arguments to \code{postscript}.
}

\section{Families}{
  The argument \code{family} specifies the font family to be used.
  In normal use it is one of \code{"AvantGarde"},
  \code{"Bookman"}, \code{"Courier"}, \code{"Helvetica"},
  \code{"Helvetica-Narrow"}, \code{"NewCenturySchoolbook"},
  \code{"Palatino"} or \code{"Times"}, and refers to the standard
  Adobe PostScript fonts of those names which are included (or cloned)
  in all common PostScript devices.

  Many PostScript emulators (including those based on
  \code{ghostscript}) use the URW equivalents of these fonts, which are
  \code{"URWGothic"}, \code{"URWBookman"}, \code{"NimbusMon"},
  \code{"NimbusSan"}, \code{"NimbusSanCond"}, \code{"CenturySch"},
  \code{"URWPalladio"} and \code{"NimbusRom"} respectively.  If your
  PostScript device is using URW fonts, you will obtain access to more
  characters and more approriate metrics by using these names.  To make
  these easier to remember, \code{"URWHelvetica" == "NimbusSan"} and
  \code{"URWTimes" == "NimbusRom"} are also supported.

  It is also possible to specify \code{family="ComputerModern"}. This
  is intended to use with the Type 1 versions of the TeX CM fonts.  It
  will normally be possible to include such output in TeX or LaTeX
  provided it is processed with \code{dvips -Ppfb -j0} or the equivalent
  on your system. (\code{-j0} turns off font subsetting.)
  
  If the second form of argument \code{"family"} is used, it should be a
  character vector of four or five paths to Adobe Font Metric files for
  the regular, bold, italic, bold italic and (optionally) symbol fonts to
  be used.  If these paths do not contain the file separator, they are
  taken to refer to files in the \R directory \file{R\_HOME/afm}.  Thus the
  default Helvetica family can be specified by \code{family =
    c("hv______.afm",
    "hvb_____.afm", "hvo_____.afm", "hvbo____.afm", "sy______.afm")}.
  It is the user's responsibility to check that suitable fonts are made
  available, and that they contain the needed characters when
  re-encoded.  The fontnames used are taken from the \code{FontName}
  fields of the afm files.  The software including the PostScript plot
  file should either embed the font outlines (usually from \file{.pfb}
  or \file{.pfa} files) or use DSC comments to instruct the print
  spooler to do so.
}

\section{Encodings}{
  Encodings describe which glyphs are used to display the character codes
  (in the range 0--255).  By default \R uses ISOLatin1 encoding, and
  the examples for \code{\link{text}} are in that encoding.  However,
  the encoding used on machines running \R may well be different, and by
  using the \code{encoding} argument the glyphs can be matched to
  encoding in use.

  None of this will matter if only ASCII characters (codes 32--126) are
  used as all the encodings agree over that range.  Some encodings are
  supersets of ISOLatin1, too.  However, if accented and special
  characters do not come out as you expect, you may need to change the
  encoding.  Three other encodings are supplied with \R:
  \code{"WinAnsi.enc"} and \code{"MacRoman.enc"} correspond to the
  encodings normally used on Windows and MacOS (at least by Adobe), and
  \code{"PDFDoc.enc"} is the first 256 characters of the Unicode
  encoding, the standard for PDF.

  If you change the encoding, it is your responsibility to ensure that
  the PostScript font contains the glyphs used.  One issue here is the Euro
  symbol which is in the WinAnsi and MacRoman encodings but may well not
  be in the PostScript fonts.  (It is in the URW variants; it is not in
  the supplied Adobe Font Metric files.)

  There is one exception.  Character 45 (\code{"-"}) is always set
  as minus (its value in Adobe ISOLatin1) even though it is hyphen in
  the other encodings.  Hyphen is available as character 173 (octal
  0255) in ISOLatin1.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{Devices}},
  {\code{\link{check.options}} which is called from both
    \code{ps.options} and \code{postscript}}.
}
\author{
  Support for Computer Modern fonts is based on a contribution by
  Brian D'Urso \email{durso@hussle.harvard.edu}.
}
\examples{
\dontrun{
# open the file "foo.ps" for graphics output
postscript("foo.ps")
# produce the desired graph(s)
dev.off()              # turn off the postscript device
#ifdef unix
postscript("|lp -dlw")
# produce the desired graph(s)
dev.off()              # plot will appear on printer
#endif
#ifdef windows
options(printcmd='redpr -P"\\\\markov\\lw"')
postscript(file=tempfile("Rps."), print.it=TRUE)
# produce the desired graph(s)
dev.off()              # send plot file to the printer
#endif

# for URW PostScript devices
postscript("foo.ps", family = "NimbusSan")

## for inclusion in Computer Modern TeX documents, perhaps
postscript("cm_test.eps", width = 4.0, height = 3.0,
           horizontal = FALSE, onefile = FALSE, paper = "special",
           family = "ComputerModern")
## The resultant postscript file can be used by dvips -Ppfb -j0.

## To test out encodings, you can use
TestChars <- function(encoding="ISOLatin1", family="URWHelvetica")
{
    postscript(encoding=encoding, family=family)
    par(pty="s")
    plot(c(0,15), c(0,15), type="n", xlab="", ylab="")
    title(paste("Centred chars in encoding", encoding))
    grid(15, 15, lty=1)
    for(i in c(32:255)) {
	x <- i %% 16
	y <- i %/% 16
	points(x, y, pch=i)
    }
    dev.off()
}
## there will be many warnings. We use URW to get a complete enough
## set of font metrics.
TestChars()
TestChars("ISOLatin2")
TestChars("WinAnsi")
}
\dontshow{
xx <- seq(0, 7, length=701)
yy <- sin(xx)/xx; yy[1] <- 1
plot(xx,yy)                     # produce the desired graph(s)
}

stopifnot(unlist(ps.options()) == unlist(.PostScript.Options))
ps.options(bg = "pink")
str(ps.options(reset = TRUE))

### ---- error checking of arguments: ----
ps.options(width=0:12, onefile=0, bg=pi)
# override the check for 'onefile', but not the others:
str(ps.options(width=0:12, onefile=1, bg=pi,
               override.check = c(FALSE,TRUE,FALSE)))
}
\keyword{device}
\eof
\name{power}
\alias{power}
\title{Create a Power Link Object}
\usage{
power(lambda = 1)
}
\arguments{
    \item{lambda}{a real number.}
}
\description{
    Creates a link object based on the link function \eqn{\eta = \mu ^
        \lambda}{eta = mu^lambda}.
}
\details{
    If \code{lambda} is non-negative, it is taken as zero, and the log
    link is obtained.  The default \code{lambda = 1} gives the identity
    link.
}
\value{
    A list with components \code{linkfun}, \code{linkinv},
    \code{mu.eta}, and \code{valideta}.
    See \code{\link{make.link}} for information on their meaning.
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S.}
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{make.link}},
  \code{\link{family}}

  To raise a number to a power, see \code{\link{Arithmetic}}.

  To calculate the power of a test, see various functions in the 
  \pkg{ctest} package, e.g., \code{\link[ctest]{power.t.test}}.
}
\examples{
power()
quasi(link=power(1/3))[c("linkfun", "linkinv")]
}
\keyword{models}
\eof
\name{ppoints}
\title{Ordinates for Probability Plotting}
\usage{
ppoints(n, a = ifelse(n <= 10, 3/8, 1/2))
}
\alias{ppoints}
\arguments{
  \item{n}{either the number of points generate or a vector of
    observations.}
  \item{a}{the offset fraction to be used; typically in \eqn{(0,1)}.}
}
\description{
  Generates the sequence of \dQuote{probability} points
  \code{(1:m - a)/(m + (1-a)-a)}
  where \code{m} is either \code{n}, if \code{length(n)==1}, or
  \code{length(n)}.
}
\details{
 If \eqn{0 < a < 1}, the resulting values are within \eqn{(0,1)}
 (excluding boundaries).
 In any case, the resulting sequence is symmetric in \eqn{[0,1]}, i.e.,
 \code{p + rev(p) == 1}.

 \code{ppoints()} is used in \code{qqplot} and \code{qqnorm} to generate
 the set of probabilities at which to evaluate the inverse distribution.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
\code{\link{qqplot}}, \code{\link{qqnorm}}.
}
\examples{
ppoints(4) # the same as  ppoints(1:4)
ppoints(10)
ppoints(10, a=1/2)
}
\keyword{dplot}
\keyword{arith}
\keyword{distribution}
\eof
\name{precip}
\docType{data}
\alias{precip}
\title{Annual Precipitation in US Cities}
\description{
  The average amount of precipitation (rainfall) in inches for each of
  70 United States (and Puerto Rico) cities.
}
\usage{data(precip)}
\format{
  A named vector of length 70.
}
\source{
  Statistical Abstracts of the United States, 1975.
}
\references{
  McNeil, D. R. (1977)
  \emph{Interactive Data Analysis}.
  New York: Wiley.
}
\examples{
data(precip)
dotchart(precip[order(precip)], main = "precip data")
title(sub = "Average annual precipitation (in.)")
}
\keyword{datasets}
\eof
\name{predict}
\title{Model Predictions}
\usage{
predict (object, \dots)
}
\alias{predict}
\arguments{
  \item{object}{a model object for which prediction is desired.}
  \item{\dots}{additional arguments affecting the predictions produced.}
}
\description{
  \code{predict} is a generic function for predictions from the results of
  various model fitting functions.  The function invokes particular
  \emph{methods} which depend on the \code{\link[base]{class}} of
  the first argument.

  The function \code{\link{predict.lm}} makes predictions based on the
  results produced by \code{\link{lm}}.
}
\value{
  The form of the value returned by \code{predict} depends on the
  class of its argument.  See the documentation of the
  particular methods for details of what is produced by that method.
}
\seealso{\code{\link{predict.lm}}.
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S}.
  Wadsworth \& Brooks/Cole.
}
\examples{
## All the "predict" methods visible in your current search() path.
## NB most of the methods in the base packages are hidden.
for(fn in methods("predict"))
   try(cat(fn,":\n\t",deparse(args(get(fn))),"\n"), silent = TRUE)
}
\keyword{methods}
\eof
\name{predict.glm}
\title{Predict Method for GLM Fits}
\usage{
\method{predict}{glm}(object, newdata = NULL,
            type = c("link", "response", "terms"),
            se.fit = FALSE, dispersion = NULL, terms = NULL,
            na.action = na.pass, \dots)
}
\alias{predict.glm}
\arguments{
  \item{object}{a fitted object of class inheriting from \code{"glm"}.}
  \item{newdata}{optionally, a new data frame from which to make the
    predictions.  If omitted, the fitted linear predictors are used.}
  \item{type}{the type of prediction required.  The default is on the
    scale of the linear predictors; the alternative \code{"response"}
    is on the scale of the response variable.  Thus for a default
    binomial model the default predictions are of log-odds (probabilities
    on logit scale) and \code{type = "response"} gives the predicted
    probabilities.  The \code{"terms"} option returns a matrix giving the
    fitted values of each term in the model formula on the linear predictor
    scale.

    The value of this argument can be abbreviated.
  }
  \item{se.fit}{logical switch indicating if standard errors are required.}
  \item{dispersion}{the dispersion of the GLM fit to be assumed in
    computing the standard errors.  If omitted, that returned by
    \code{summary} applied to the object is used.}
  \item{terms}{with \code{type="terms"} by default all terms are returned.
    A character vector specifies which terms are to be returned}
  \item{na.action}{function determining what should be done with missing
    values in \code{newdata}.  The default is to predict \code{NA}.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\description{
  Obtains predictions and optionally estimates standard errors of those
  predictions from a fitted generalized linear model object.
}
\value{
  If \code{se = FALSE}, a vector or matrix of predictions.  If \code{se
    = TRUE}, a list with components
  \item{fit}{Predictions}
  \item{se.fit}{Estimated standard errors}
  \item{residual.scale}{A scalar giving the square root of the
    dispersion used in computing the standard errors.}
}

\seealso{
  \code{\link{glm}}, \code{\link{SafePrediction}}
}

\examples{
## example from Venables and Ripley (2002, pp. 190-2.)
ldose <- rep(0:5, 2)
numdead <- c(1, 4, 9, 13, 18, 20, 0, 2, 6, 10, 12, 16)
sex <- factor(rep(c("M", "F"), c(6, 6)))
SF <- cbind(numdead, numalive=20-numdead)
budworm.lg <- glm(SF ~ sex*ldose, family=binomial)
summary(budworm.lg)

plot(c(1,32), c(0,1), type = "n", xlab = "dose",
     ylab = "prob", log = "x")
text(2^ldose, numdead/20, as.character(sex))
ld <- seq(0, 5, 0.1)
lines(2^ld, predict(budworm.lg, data.frame(ldose=ld,
   sex=factor(rep("M", length(ld)), levels=levels(sex))),
   type = "response"))
lines(2^ld, predict(budworm.lg, data.frame(ldose=ld,
   sex=factor(rep("F", length(ld)), levels=levels(sex))),
   type = "response"))
}
\keyword{models}
\keyword{regression}
\eof
\name{predict.lm}
\title{Predict method for Linear Model Fits}
\alias{predict.lm}
\alias{predict.mlm}
\description{
  Predicted values based on linear model object
}
\usage{
\method{predict}{lm}(object, newdata, se.fit = FALSE, scale = NULL, df = Inf, 
        interval = c("none", "confidence", "prediction"),
        level = 0.95, type = c("response", "terms"),
        terms = NULL, na.action = na.pass, \dots)
}
\arguments{
  \item{object}{Object of class inheriting from \code{"lm"}}
  \item{newdata}{Data frame in which to predict}
  \item{se.fit}{A switch indicating if standard errors are required.}
  \item{scale}{Scale parameter for std.err. calculation}
  \item{df}{Degrees of freedom for scale}
  \item{interval}{Type of interval calculation}
  \item{level}{Tolerance/confidence level}
  \item{type}{Type of prediction (response or model term)}
  \item{terms}{If \code{type="terms"}, which terms (default is all terms)}
  \item{na.action}{function determining what should be done with missing
    values in \code{newdata}.  The default is to predict \code{NA}.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\details{
  \code{predict.lm} produces predicted values, obtained by evaluating
  the regression function in the frame \code{newdata} (which defaults to
  \code{model.frame(object)}.  If the logical \code{se.fit} is
  \code{TRUE}, standard errors of the predictions are calculated.  If
  the numeric argument \code{scale} is set (with optional \code{df}), it
  is used as the residual standard deviation in the computation of the
  standard errors, otherwise this is extracted from the model fit.
  Setting \code{intervals} specifies computation of confidence or
  prediction (tolerance) intervals at the specified \code{level}.

  If the fit is rank-deficient, some of the columns of the design matrix
  will have been dropped.  Prediction from such a fit only makes sense
  if \code{newdata} is contained in the same subspace as the original
  data. That cannot be checked accurately, so a warning is issued.
}
\value{
  \code{predict.lm} produces a vector of predictions or a matrix of
  predictions and bounds with column names \code{fit}, \code{lwr}, and
  \code{upr} if \code{interval} is set.  If \code{se.fit} is
  \code{TRUE}, a list with the following components is returned: 
  \item{fit}{vector or matrix as above}
  \item{se.fit}{standard error of predictions}
  \item{residual.scale}{residual standard deviations}
  \item{df}{degrees of freedom for residual}
}
\note{
  Offsets specified by \code{offset} in the fit by \code{\link{lm}}
  will not be included in predictions, whereas those specified by an
  offset term in the formula will be.
}
\seealso{
  The model fitting function \code{\link{lm}}, \code{\link{predict}},
  \code{\link{SafePrediction}}
}
\examples{
## Predictions
x <- rnorm(15)
y <- x + rnorm(15)
predict(lm(y ~ x))
new <- data.frame(x = seq(-3, 3, 0.5))
predict(lm(y ~ x), new, se.fit = TRUE)
pred.w.plim <- predict(lm(y ~ x), new, interval="prediction")
pred.w.clim <- predict(lm(y ~ x), new, interval="confidence")
matplot(new$x,cbind(pred.w.clim, pred.w.plim[,-1]),
        lty=c(1,2,2,3,3), type="l", ylab="predicted y")
}
\keyword{regression}

\eof
\name{preplot}
\alias{preplot}
\title{Pre-computations for a Plotting Objeect}
\description{
    Compute an object to be used for plots relating to the given model object.
}
\usage{
preplot(object, \dots)
}
\arguments{
 \item{object}{a fitted model object.}
 \item{\dots}{additional arguments for specific methods.}
}
\details{
    Only the generic function is currently provided in base \R, but some
    add-on packages have methods. Principally here for S compatibility. 
}
\value{
    An object set up to make a plot that describes \code{object}.
}
\keyword{models}
\eof
\name{presidents}
\docType{data}
\alias{presidents}
\title{Quarterly Approval Ratings of US Presidents}
\description{
  The (approximately) quarterly approval rating for the President of the
  United states from the first quarter of 1945 to the last quarter of
  1974.
}
\usage{data(presidents)}
\format{
  A time series of 120 values.
}
\source{
  The Gallup Organisation.
}
\details{
  The data are actually a fudged version of the approval ratings.  See
  McNeil's book for details.
}
\references{
  McNeil, D. R. (1977)
  \emph{Interactive Data Analysis}.
  New York: Wiley.
}
\examples{
data(presidents)
plot(presidents, las = 1, ylab = "Approval rating (\%)",
     main = "presidents data")
}
\keyword{datasets}
\eof
\name{pressure}
\docType{data}
\alias{pressure}
\title{Vapor Pressure of Mercury as a Function of Temperature}
\description{
  Data on the relation between temperature in degrees Celsius and vapor
  pressure of mercury in millimeters (of mercury).
}
\usage{data(pressure)}
\format{
  A data frame with 19 observations on 2 variables.
  \tabular{rlll}{
    [, 1] \tab temperature \tab numeric \tab temperature (deg C)\cr
    [, 2] \tab pressure    \tab numeric \tab pressure (mm)
  }
}
\source{
  Weast, R. C., ed. (1973)
  \emph{Handbook of Chemistry and Physics}.
  CRC Press.
}
\references{
  McNeil, D. R. (1977)
  \emph{Interactive Data Analysis}.
  New York: Wiley.
}
\examples{
data(pressure)
plot(pressure, xlab = "Temperature (deg C)",
     ylab = "Pressure (mm of Hg)",
     main = "pressure data: Vapor Pressure of Mercury")
plot(pressure, xlab = "Temperature (deg C)",  log = "y",
     ylab = "Pressure (mm of Hg)",
     main = "pressure data: Vapor Pressure of Mercury")
}
\keyword{datasets}
\eof
\name{pretty}
\title{Pretty Breakpoints}
\usage{
pretty(x, n = 5, min.n = n \%/\% 3,  shrink.sml = 0.75,
       high.u.bias = 1.5, u5.bias = .5 + 1.5*high.u.bias,
       eps.correct = 0)
}
\alias{pretty}
\arguments{
\item{x}{numeric vector}
\item{n}{integer giving the \emph{desired} number of
  intervals.  Non-integer values are rounded down.}
\item{min.n}{nonnegative integer giving the \emph{minimal} number of
    intervals.  If \code{min.n == 0}, \code{pretty(.)} may return a
    single value.}
\item{shrink.sml}{positive numeric
  by a which a default scale is shrunk in the case when
  \code{range(x)} is \dQuote{very small} (usually 0).}
\item{high.u.bias}{non-negative numeric, typically \eqn{> 1}.
    The interval unit is determined as \{1,2,5,10\} times \code{b}, a
    power of 10.  Larger \code{high.u.bias} values favor larger units.
}
\item{u5.bias}{non-negative numeric
    multiplier favoring factor 5 over 2.  Default and \dQuote{optimal}:
    \code{u5.bias = .5 + 1.5*high.u.bias}.}
\item{eps.correct}{integer code, one of \{0,1,2\}. If non-0, an
    \dQuote{\emph{epsilon correction}} is made at the boundaries such that
    the result boundaries will be outside \code{range(x)}; in the
    \emph{small} case, the correction is only done if \code{eps.correct >=2}.}
}
\description{
    Compute a  sequence of about \code{n+1} equally spaced nice values which
    cover the range of the values in \code{x}.
    The values are chosen so that they are 1, 2 or 5 times a power of 10.
}
\details{
    Let \code{d <- max(x) - min(x)} \eqn{\ge 0}{>= 0}.
    If \code{d} is not (very close) to 0, we let \code{c <- d/n},
    otherwise more or less \code{c <- max(abs(range(x)))*shrink.sml / min.n}.
    Then, the \emph{10 base} \code{b} is
    \eqn{10^{\lfloor{\log_{10}(c)}\rfloor}}{10^(floor(log10(c)))} such
    that \eqn{b \le c < 10b}.

    Now determine the basic \emph{unit} \eqn{u} as one of
    \eqn{\{1,2,5,10\} b}, depending on \eqn{c/b \in [1,10)} and the two
    \dQuote{\emph{bias}} coefficients, \eqn{h =}\code{high.u.bias} and
    \eqn{f =}\code{u5.bias}.

    \dots\dots\dots
%%-- fixme: give even more details
%%-- fixme: give even more details

}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
pretty(1:15)     # 0  2  4  6  8 10 12 14 16
pretty(1:15, h=2)# 0  5 10 15
pretty(1:15, n=4)# 0  5 10 15
pretty(1:15 * 2) # 0  5 10 15 20 25 30
pretty(1:20)      # 0  5 10 15 20
pretty(1:20, n=2) # 0 10 20
pretty(1:20, n=10)# 0  2  4 ... 20

for(k in 5:11) {
  cat("k=",k,": "); print(diff(range(pretty(100 + c(0, pi*10^-k)))))}

##-- more bizarre, when  min(x) == max(x):
pretty(pi)

add.names <- function(v) { names(v) <- paste(v); v}
str(lapply(add.names(-10:20), pretty))
str(lapply(add.names(0:20),   pretty, min = 0))
sapply(    add.names(0:20),   pretty, min = 4)

pretty(1.234e100)
pretty(1001.1001)
pretty(1001.1001, shrink = .2)
for(k in -7:3)
  cat("shrink=",formatC(2^k,wid=9),":",
      formatC(pretty(1001.1001, shrink = 2^k), wid=6),"\n")
}
\keyword{dplot}
\eof
\name{print}
\title{Print Values}
\usage{
print(x, \dots)

\method{print}{factor}(x, quote = FALSE, max.levels = NULL,
     width = getOption("width"), \dots)

\method{print}{table}(x, digits = getOption("digits"), quote = FALSE,
          na.print = "", zero.print = "0", justify = "none", \dots)
}
\alias{print}
\alias{print.factor}
\alias{print.htest}
\alias{print.listof}
\alias{print.simple.list}
\alias{print.table}
\description{
  \code{print} prints its argument and returns it \emph{invisibly} (via
  \code{\link{invisible}(x)}).  It is a generic function which means that
  new printing methods can be easily added for new
  \code{\link[base]{class}}es.
}
\arguments{
  \item{x}{an object used to select a method.}
  \item{\dots}{further arguments passed to or from other methods.}
  \item{quote}{logical, indicating whether or not strings should be
    printed with surrounding quotes.}
  \item{max.levels}{integer, indicating how many levels should be
    printed for a factor; if \code{0}, no extra "Levels" line will be
    printed.  The default, \code{NULL}, entails chosing \code{max.levels}
    such that the levels print on one line of width \code{width}.}
  \item{width}{only used when \code{max.levels} is NULL, see above.}
  \item{digits}{minimal number of \emph{significant} digits, see
    \code{\link{print.default}}.}
  \item{na.print}{character string (or \code{NULL}) indicating
    \code{\link{NA}} values in printed output, see
    \code{\link{print.default}}.}
  \item{zero.print}{character specifying how zeros (\code{0}) should be
    printed; for sparse tables, using \code{"."} can produce stronger results.}
  \item{justify}{character indicating if strings should left- or
    right-justified or left alone, passed to \code{\link{format}}.}
}
\details{
  The default method, \code{\link{print.default}} has its own help page.
  Use \code{\link{methods}("print")} to get all the methods for the
  \code{print} generic.

  \code{print.factor} allows some customization and is used for printing
  \code{\link{ordered}} factors as well.

  \code{print.table} for printing \code{\link{table}}s allows other
  customization.

  See \code{\link{noquote}} as an example of a class whose main
  purpose is a specific \code{print} method.
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S.}
  Wadsworth \& Brooks/Cole.
}
\seealso{
  The default method \code{\link{print.default}}, and help for the
  methods above; further \code{\link{options}}, \code{\link{noquote}}.

  For more customizable (but cumbersome) printing, see
  \code{\link{cat}}, \code{\link{format}} or also \code{\link{write}}.
}
\examples{
ts(1:20)#-- print is the "Default function" --> print.ts(.) is called
rr <- for(i in 1:3) print(1:i)
rr

## Printing of factors
data(attenu)
attenu$station ## 117 levels -> `max.levels' depending on width

data(esoph) ## ordered : levels  "l1 < l2 < .."
esoph$agegp[1:12]
esoph$alcgp[1:12]

## Printing of sparse (contingency) tables
set.seed(521)
t1 <- round(abs(rt(200, df=1.8)))
t2 <- round(abs(rt(200, df=1.4)))
table(t1,t2) # simple
print(table(t1,t2), zero.print = ".")# nicer to read
}
\keyword{print}
\eof
\name{printCoefmat}
\alias{printCoefmat}
\title{Print Coefficient Matrices}
\description{
  Utility function to be used in \dQuote{higher level} \code{\link{print}}
  methods, such as \code{\link{print.summary.lm}},
  \code{\link{print.summary.glm}} and \code{\link{print.anova}}.  The
  goal is to provide a flexible interface with smart defaults such
  that often, only \code{x} needs to be specified.
}
\usage{
printCoefmat(x, digits=max(3, getOption("digits") - 2),
             signif.stars = getOption("show.signif.stars"),
             dig.tst = max(1, min(5, digits - 1)),
             cs.ind = 1:k, tst.ind = k + 1, zap.ind = integer(0),
             P.values = NULL,
             has.Pvalue = nc >= 4 && substr(colnames(x)[nc],1,3) == "Pr(",
             eps.Pvalue = .Machine$double.eps,
             na.print = "NA", \dots)
}
\arguments{
  \item{x}{a numeric matrix like object, to be printed.}
  \item{digits}{minimum number of significant digits to be used for
    most numbers.}
  \item{signif.stars}{logical; if \code{TRUE}, P-values are additionally
    encoded visually as \dQuote{significance stars} in order to help scanning
    of long coefficient tables.  It defaults to the
    \code{show.signif.stars} slot of \code{\link{options}}.}
  \item{dig.tst}{minimum number of significant digits for the test statistics,
    see \code{tst.ind}.}
  \item{cs.ind}{indices (integer) of column numbers which are (like)
    \bold{c}oefficients and \bold{s}tandard errors to be formatted
    together.}
  \item{tst.ind}{indices (integer) of column numbers for test
    statistics.}
  \item{zap.ind}{indices (integer) of column numbers which should be
    formatted by \code{\link{zapsmall}}, i.e., by \dQuote{zapping} values
    close to 0.}
  \item{P.values}{logical or \code{NULL}; if \code{TRUE}, the last
    column of \code{x} is formatted by \code{\link{format.pval}} as P
    values.  If \code{P.values = NULL}, the default, it is set to
    \code{TRUE} only if \code{link{options}("show.coef.Pvalue")} is
    \code{TRUE} \emph{and} \code{x} has at least 4 columns \emph{and}
    the last column name of \code{x} starts with \code{"Pr("}.}
  \item{has.Pvalue}{logical; if \code{TRUE}, the last column of \code{x}
    contains P values; in that case, it is printed \emph{iff}
    \code{P.values} (above).}
  \item{eps.Pvalue}{number,..}
  \item{na.print}{a character string to code \code{\link{NA}} values in
    printed output.}
 \item{\dots}{further arguments for \code{\link{print}}.}
}
\value{Invisibly returns its argument, \code{x}.}}
\author{Martin Maechler}
\seealso{
  \code{\link{print.summary.lm}},
  \code{\link{format.pval}},
  \code{\link{format}}.
}
\examples{
cmat <- cbind(rnorm(3, 10), sqrt(rchisq(3, 12)))
cmat <- cbind(cmat, cmat[,1]/cmat[,2])
cmat <- cbind(cmat, 2*pnorm(-cmat[,3]))
colnames(cmat) <- c("Estimate", "Std.Err", "Z value", "Pr(>z)")
printCoefmat(cmat[,1:3])
printCoefmat(cmat)
options(show.coef.Pvalues = FALSE)
printCoefmat(cmat, digits=2)
printCoefmat(cmat, digits=2, P.values = TRUE)
options(show.coef.Pvalues = TRUE)# revert
}
\keyword{print}
\eof
\name{print.data.frame}
\title{Printing Data Frames}
\alias{print.data.frame}
\description{
  Print a data frame.
}
\usage{
\method{print}{data.frame}(x, \dots, digits = NULL, quote = FALSE, right = TRUE)
}
\arguments{
  \item{x}{object of class \code{data.frame}.}
  \item{\dots}{optional arguments to \code{print} or \code{plot} methods.}
  \item{digits}{the minimum number of significant digits to be used.}
  \item{quote}{logical, indicating whether or not entries should be
    printed with surrounding quotes.}
  \item{right}{logical, indicating whether or not strings should be
    right-aligned. The default is left-alignment.}
}
\details{
  This calls \code{\link{format}} which formats the data frame
  column-by-column, then converts to a character matrix and dispatches
  to the \code{print} method for matrices.

  When \code{quote = TRUE} only the entries are quoted not the row names
  nor the column names.
}
\seealso{
  \code{\link{data.frame}}.
}
\keyword{print}
\eof
\name{print.default}
\alias{print.default}
\alias{print.matrix}
\description{
  \code{print.default} is the \emph{default} method of the generic
  \code{\link{print}} function which prints its argument.
  \code{print.matrix} is currently identical, but was not prior to
  \code{1.7.0}.
}
\title{Default Printing}
\usage{
\method{print}{default}(x, digits = NULL, quote = TRUE, na.print = NULL,
      print.gap = NULL, right = FALSE, \dots)
}
\arguments{
  \item{x}{the object to be printed.}
  \item{digits}{a non-null value for \code{digits} specifies the minimum
    number of significant digits to be printed in values.  If
    \code{digits} is \code{NULL}, the value of \code{digits} set by
    \code{options} is used.}
  \item{quote}{logical, indicating whether or not strings
    (\code{\link{character}}s) should be printed with surrounding quotes.}
  \item{na.print}{a character string which is used to indicate
    \code{\link{NA}} values in printed output, or \code{NULL} (see Details)}
  \item{print.gap}{an integer, giving the spacing between adjacent columns
    in printed matrices and arrays, or \code{NULL} meaning 1.}
  \item{right}{logical, indicating whether or not strings should be
    right-aligned. The default is left-alignment.}
  \item{\dots}{further arguments to be passed to or from other
    methods. They are ignored in these functions.}
}
\details{
  Prior to \R 1.7.0, \code{print.matrix} did not
  print attributes and did not have a \code{digits} argument.
  
  The default for printing \code{NA}s is to print \code{NA} (without
  quotes) unless this is a character \code{NA} \emph{and} \code{quote =
    FALSE}, when \code{<NA>} is printed.

  The same number of decimal places is used throughout a vector,  This
  means that \code{digits} specifies the minimum number of significant
  digits to be used, and that at least one entry will be printed with
  that minimum number.

  As from \R 1.7.0 attributes are printed respecting their class(es),
  using the values of \code{digits} to \code{print.default}, but using the
  default values (for the methods called) of the other arguments.

  When the \pkg{methods} package is attached, \code{print} will call
  \code{\link[methods]{show}} for methods with formal classes if called
  with no optional arguments.
}
\seealso{The generic \code{\link{print}}, \code{\link{options}}.
  The \code{"\link{noquote}"} class and print method.
}
\examples{
pi
print(pi, digits = 16)
LETTERS[1:16]
print(LETTERS, quote = FALSE)
}
\keyword{print}
\eof
\name{prmatrix}
\alias{prmatrix}
\title{Print Matrices, Old-style}
\usage{
prmatrix(x, rowlab =, collab =,
         quote = TRUE, right = FALSE, na.print = NULL, \dots)
}
\arguments{
  \item{x}{numeric or character matrix.}
  \item{rowlab,collab}{(optional) character vectors giving row or column
    names respectively.  By default, these are taken from
    \code{\link{dimnames}(x)}.}
  \item{quote}{logical; if \code{TRUE} and \code{x} is of mode
    \code{"character"}, \emph{quotes} (\code{"}) are used.} %"
  \item{right}{ if \code{TRUE} and \code{x} is of mode
    \code{"character"}, the output columns are \emph{right}-justified.}
  \item{na.print}{how \code{NA}s are printed.  If this is non-null, its
    value is used to represent \code{NA}.}
  \item{\dots}{arguments for \code{print} methods.}
}
\description{
  An earlier method for printing matrices, provided for S compatibility.
}
\details{
  \code{prmatrix} is an earlier form of \code{print.matrix}, and
  is very similar to the S function of the same name.
}
\value{
  Invisibly returns its argument, \code{x}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{print.default}}, and other \code{\link{print}} methods.
}
\examples{
prmatrix(m6 <- diag(6), row = rep("",6), coll=rep("",6))

chm <- matrix(scan(system.file("help", "AnIndex", package = "eda"),
                   what = ""), , 2, byrow = TRUE)
chm  # uses print.matrix()
prmatrix(chm, collab = paste("Column",1:3), right=TRUE, quote=FALSE)
}
\keyword{print}
\eof
\name{print.ts}
\title{Printing Time-Series Objects}
\alias{print.ts}
\description{
  Print method for time series objects.
}
\usage{
\method{print}{ts}(x, calendar, \dots)
}
\arguments{
  \item{x}{a time series object.}
  \item{calendar}{enable/disable the display of information about
    month names, quarter names or year when printing.  The default is
    \code{TRUE} for a frequency of 4 or 12, \code{FALSE} otherwise.}
  \item{\dots}{additional arguments to \code{\link{print}}.}
}
\details{
  This is the \code{\link{print}} methods for objects inheriting from
  class \code{"ts"}.
}
\seealso{
  \code{\link{print}},
  \code{\link{ts}}.
}
\examples{
print(ts(1:10, freq = 7, start = c(12, 2)), calendar = TRUE)
}
\keyword{ts}
\eof
\name{proc.time}
\alias{proc.time}
\title{Running Time of R}
\description{
  \code{proc.time} determines how much time (in seconds) the currently
  running \R process already consumed.
}
\usage{
proc.time()
}
\value{
  A numeric vector of length 5, containing the user, system, and total
  elapsed times for the currently running \R process, and the cumulative
  sum of user and system times of any child processes spawned by it.

  The resolution of the times will be system-specific; it is common for
  them to be recorded to of the order of 1/100 second, and elapsed
  time is rounded to the nearest 1/100.

  It is most useful for \dQuote{timing} the evaluation of \R expressions,
  which can be done conveniently with \code{\link{system.time}}.
}
\note{
#ifdef unix
  It is possible to compile \R without support for \code{proc.time},
  when the function will not exist.
#endif
#ifdef windows
  CPU times will be returned as \code{NA} on Windows 9x/ME systems, but
  are genuine times on NT4/2000/XP systems. Times of child processes are
  not available and will always be given as \code{NA}.
#endif
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{system.time}} for timing a valid \R expression,
  \code{\link{gc.time}} for how much of the time was spent in garbage
  collection.
}
\examples{\dontrun{
## a way to time an R expression: system.time is preferred
ptm <- proc.time()
for (i in 1:50) mad(runif(500))
proc.time() - ptm
}}
\keyword{utilities}
\eof
\name{prod}
\title{Product of Vector Elements}
\usage{
prod(\dots, na.rm = FALSE)
}
\alias{prod}
\description{
  \code{prod} returns the product of all the values
  present in its arguments.
}
\arguments{
  \item{\dots}{numeric vectors.}
  \item{na.rm}{logical. Should missing values be removed?}
}
\details{
  If \code{na.rm} is \code{FALSE} an \code{NA}
  value in any of the arguments will cause
  a value of \code{NA} to be returned, otherwise
  \code{NA} values are ignored.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
\code{\link{sum}},
\code{\link{cumprod}},
\code{\link{cumsum}}.
}
\examples{
print(prod(1:7)) == print(gamma(8))
}
\keyword{arith}
\eof
\name{profile}
\alias{profile}
\title{Generic Function for Profiling Models}
\usage{
profile(fitted, \dots)
}
\arguments{
  \item{fitted}{the original fitted model object.}
  \item{\dots}{additional parameters. See documentation on individual
    methods.}
}
\description{
  Investigates behavior of objective function near the solution
  represented by \code{fitted}.

  See documentation on method functions for further details.
}
\value{
  A list with an element for each parameter being profiled. See the
  individual methods for further details.
}
\seealso{
  \code{\link[nls]{profile.nls}} in package \pkg{nls},
  \code{\link[MASS:confint]{profile.glm}} in package \pkg{MASS},
  \ldots

  For profiling code, see \code{\link{Rprof}}.
}
\keyword{models}
\eof
\name{proj}
\title{Projections of Models}
\usage{
proj(object, \dots)  

\method{proj}{aov}(object, onedf = FALSE, unweighted.scale = FALSE, \dots)  

\method{proj}{aovlist}(object, onedf = FALSE, unweighted.scale = FALSE, \dots)  

\method{proj}{default}(object, onedf = TRUE, \dots)  

\method{proj}{lm}(object, onedf = FALSE, unweighted.scale = FALSE, \dots)  
}
\alias{proj}
\alias{proj.default}
\alias{proj.lm}
\alias{proj.aov}
\alias{proj.aovlist}
\arguments{
 \item{object}{An object of class \code{"lm"} or a class inheriting from
   it, or an object with a similar structure including in particular
   components \code{qr} and \code{effects}.}
 \item{onedf}{A logical flag. If \code{TRUE}, a projection is returned for all
   the columns of the model matrix. If \code{FALSE}, the single-column
   projections are collapsed by terms of the model (as represented in
   the analysis of variance table).}
 \item{unweighted.scale}{If the fit producing \code{object} used
   weights, this determines if the projections correspond to weighted or
   unweighted observations.}
 \item{\dots}{Swallow and ignore any other arguments.}
}
\description{
 \code{proj} returns a matrix or list of matrices giving the projections
 of the data onto the terms of a linear model.  It is most frequently
 used for \code{\link{aov}} models.
}
\details{
 A projection is given for each stratum of the object, so for \code{aov}
 models with an \code{Error} term the result is a list of projections.
}
\value{
  A projection matrix or (for multi-stratum objects) a list of
  projection matrices.

  Each projection is a matrix with a row for each observations and
  either a column for each term (\code{onedf = FALSE}) or for each
  coefficient (\code{onedf = TRUE}). Projection matrices from the
  default method have orthogonal columns representing the projection of
  the response onto the column space of the Q matrix from the QR
  decomposition.  The fitted values are the sum of the projections, and
  the sum of squares for each column is the reduction in sum of squares
  from fitting that column (after those to the left of it).

  The methods for \code{lm} and \code{aov} models add a column to the
  projection matrix giving the residuals (the projection of the data
  onto the orthogonal complement of the model space).

  Strictly, when \code{onedf = FALSE} the result is not a projection,
  but the columns represent sums of projections onto the columns of the
  model matrix corresponding to that term. In this case the matrix does
  not depend on the coding used.
}
\references{
  Chambers, J. M., Freeny, A and Heiberger, R. M. (1992)
  \emph{Analysis of variance; designed experiments.}
  Chapter 5 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\author{
  The design was inspired by the S function of the same name described
  in Chambers \emph{et al.} (1992).
}
\seealso{\code{\link{aov}}, \code{\link{lm}}, \code{\link{model.tables}}
}
\examples{
N <- c(0,1,0,1,1,1,0,0,0,1,1,0,1,1,0,0,1,0,1,0,1,1,0,0)
P <- c(1,1,0,0,0,1,0,1,1,1,0,0,0,1,0,1,1,0,0,1,0,1,1,0)
K <- c(1,0,0,1,0,1,1,0,0,1,0,1,0,1,1,0,0,0,1,1,1,0,1,0)
yield <- c(49.5,62.8,46.8,57.0,59.8,58.5,55.5,56.0,62.8,55.8,69.5,
55.0, 62.0,48.8,45.5,44.2,52.0,51.5,49.8,48.8,57.2,59.0,53.2,56.0)

npk <- data.frame(block=gl(6,4), N=factor(N), P=factor(P),
                  K=factor(K), yield=yield)
npk.aov <- aov(yield ~ block + N*P*K, npk)
proj(npk.aov)

## as a test, not particularly sensible
options(contrasts=c("contr.helmert", "contr.treatment"))
npk.aovE <- aov(yield ~  N*P*K + Error(block), npk)
proj(npk.aovE)
}
\keyword{models}
\eof
\name{prompt}
\title{Produce Prototype of an R Documentation File}
\alias{prompt}
\alias{prompt.default}
\alias{prompt.data.frame}
\description{
  Facilitate the constructing of files documenting \R objects.
}
\usage{
prompt(object, filename = NULL, name = NULL, \dots)
\method{prompt}{default}(object, filename = NULL, name = NULL,
       force.function = FALSE, \dots)
\method{prompt}{data.frame}(object, filename = NULL, name = NULL, \dots)
}
\arguments{
  \item{object}{an \R object, typically a function for the default
    method.}
  \item{filename}{usually, a connection or a character string giving the
    name of the file to which the documentation shell should be written.
    The default corresponds to a file whose name is \code{name} followed
    by \code{".Rd"}.  Can also be \code{NA} (see below).}
  \item{name}{a character string specifying the name of the object.}
  \item{force.function}{a logical.  If \code{TRUE}, treat \code{object}
    as function in any case.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\value{
  If \code{filename} is \code{NA}, a list-style representation of the
  documentation shell.  Otherwise, the name of the file written to is
  returned invisibly.
}
\details{
  Unless \code{filename} is \code{NA}, a documentation shell for
  \code{object} is written to the file specified by \code{filename}, and
  a message about this is given.  For function objects, this shell
  contains the proper function and argument names.  R documentation
  files thus created still need to be edited and moved into the
  \file{man} subdirectory of the package containing the object to be
  documented.

  If \code{filename} is \code{NA}, a list-style representation of the
  documentation shell is created and returned.  Writing the shell to a
  file amounts to \code{cat(unlist(x), file = filename, sep = "\\n")},
  where \code{x} is the list-style representation.

  When \code{prompt} is used in \code{\link{for}} loops or scripts, the
  explicit \code{name} specification will be useful.
}
\note{
  The documentation file produced by \code{prompt.data.frame} does not
  have the same format as many of the data frame documentation files in
  the \pkg{base} package.  We are trying to settle on a preferred
  format for the documentation.
}
\section{Warning}{
  Currently, calling \code{prompt} on a non-function object assumes that
  the object is in fact a data set and hence documents it as such.  This
  may change in future versions of \R.  Use \code{\link{promptData}} to
  create documentation skeletons for data sets.
}
\seealso{
  \code{\link{promptData}}, \code{\link{help}} and the chapter on
  \dQuote{Writing \R documentation} in \dQuote{Writing \R Extensions}
  (see the \file{doc/manual} subdirectory of the \R source tree).

  To prompt the user for input, see \code{\link{readline}}.
}
\author{Douglas Bates for \code{prompt.data.frame}}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
prompt(plot.default)
prompt(interactive, force.function = TRUE)
unlink("plot.default.Rd")
unlink("interactive.Rd")

data(women) # data.frame
prompt(women)
unlink("women.Rd")

data(sunspots) # non-data.frame data
prompt(sunspots)
unlink("sunspots.Rd")
}
\keyword{documentation}
\eof
\name{promptData}
\alias{promptData}
\title{Generate a Shell for Documentation of Data Sets}
\description{
  Generates a shell of documentation for a data set.
}
\usage{
promptData(object, filename = NULL, name = NULL)
}
\arguments{
  \item{object}{an \R object to be documented as a data set.}
  \item{filename}{usually, a connection or a character string giving the
    name of the file to which the documentation shell should be written.
    The default corresponds to a file whose name is \code{name} followed
    by \code{".Rd"}.  Can also be \code{NA} (see below).}
  \item{name}{a character string specifying the name of the object.}
}
\value{
  If \code{filename} is \code{NA}, a list-style representation of the
  documentation shell.  Otherwise, the name of the file written to is
  returned invisibly.
}
\details{
  Unless \code{filename} is \code{NA}, a documentation shell for
  \code{object} is written to the file specified by \code{filename}, and
  a message about this is given.

  If \code{filename} is \code{NA}, a list-style representation of the
  documentation shell is created and returned.  Writing the shell to a
  file amounts to \code{cat(unlist(x), file = filename, sep = "\\n")},
  where \code{x} is the list-style representation.
  
  Currently, only data frames are handled explicitly by the code.
}
\section{Warning}{
  This function is still experimental.  Both interface and value might
  change in future versions.  In particular, it may be preferable to use
  a character string naming the data set and optionally a specification
  of where to look for it instead of using \code{object}/\code{name} as
  we currently do.  This would be different from \code{\link{prompt}},
  but consistent with other prompt-style functions in package
  \pkg{methods}, and also allow prompting for data set documentation
  without explicitly having to load the data set.
}
\seealso{\code{\link{prompt}}}
\examples{
data(sunspots)
promptData(sunspots)
unlink("sunspots.Rd")
}
\keyword{documentation}
\eof
\name{prop.table}
\title{Express table entries as fraction of marginal table}
\usage{
prop.table(x, margin=NULL)
}
\alias{prop.table}
\arguments{
 \item{x}{ table }
 \item{margin}{ index, or vector of indices to generate margin for}
}

\description{ This is really \code{sweep(x, margin, margin.table(x,
margin), "/")} for newbies, except that if \code{margin} has length
zero, then one gets \code{x/sum(x)}.  }

\value{
  Table like \code{x} expressed relative to \code{margin} 
}
\author{ Peter Dalgaard }

\seealso{\code{\link{margin.table}}}

\examples{
m<-matrix(1:4,2)
m
prop.table(m,1)
}
\keyword{ array }
\eof
\name{pushBack}
\alias{pushBack}
\alias{pushBackLength}
\title{Push Text Back on to a Connection}
\description{
  Functions to push back text lines onto a connection, and to enquire
  how many lines are currently pushed back.
}
\usage{
pushBack(data, connection, newLine = TRUE)
pushBackLength(connection)
}
\arguments{
  \item{data}{a character vector.}
  \item{connection}{A connection.}
  \item{newLine}{logical. If true, a newline is appended to each string
    pushed back.}
}
\details{
  Several character strings can be pushed back on one or more occasions.
  The occasions form a stack, so the first line to be retrieved will be
  the first string from the last call to \code{pushBack}.  Lines which
  are pushed back are read prior to the normal input from the
  connection, by the normal text-reading functions such as
  \code{\link{readLines}} and \code{\link{scan}}.

  Pushback is only allowed for readable connections.

  Not all uses of connections respect pushbacks, in particular the input
  connection is still wired directly, so for example parsing
  commands from the console and \code{\link{scan}("")} ignore pushbacks on
  \code{\link{stdin}}.
}
\value{
  \code{pushBack} returns nothing.

  \code{pushBackLength} returns number of lines currently pushed back.
}
\seealso{\code{\link{connections}}, \code{\link{readLines}}.}

\examples{
zz <- textConnection(LETTERS)
readLines(zz, 2)
pushBack(c("aa", "bb"), zz)
pushBackLength(zz)
readLines(zz, 1)
pushBackLength(zz)
readLines(zz, 1)
readLines(zz, 1)
close(zz)
}
\keyword{connection}
\eof
\name{Sys.putenv}
\title{Set Environment Variables}
\usage{
Sys.putenv(\dots)
}
\alias{Sys.putenv}
\arguments{
  \item{\dots}{arguments in \code{name=value} form, with \code{value}
    coercible to a character string.}
}
\description{
  \code{putenv} sets environment variables (for other processes called
  from within \R or future calls to \code{\link{Sys.getenv}} from this
  \R process).
}
\value{
  A logical vector of the same length as \code{x}, with elements being
  true if setting the corresponding variable succeeded.
}
\details{
  Non-standard \R names must be quoted: see the Examples section.
}
\note{
  Not all systems need support \code{Sys.putenv}.
}
\seealso{
  \code{\link{Sys.getenv}},
  \code{\link{setwd}} for the working directory.
}
\examples{
print(Sys.putenv("R_TEST"="testit", ABC=123))
Sys.getenv("R_TEST")
}
\keyword{environment}
\keyword{utilities}
\eof
\name{qqnorm}
\title{Quantile-Quantile Plots}
\usage{
qqnorm(y, \dots)
\method{qqnorm}{default}(y, ylim, main = "Normal Q-Q Plot",
       xlab = "Theoretical Quantiles",
       ylab = "Sample Quantiles", plot.it = TRUE, datax = FALSE,
       \dots)
qqline(y, datax = FALSE, \dots)
qqplot(x, y, plot.it = TRUE, xlab = deparse(substitute(x)),
       ylab = deparse(substitute(y)), \dots)
}
\alias{qqnorm}
\alias{qqnorm.default}
\alias{qqplot}
\alias{qqline}

\arguments{
  \item{x}{The first sample for \code{qqplot}.}
  \item{y}{The second or only data sample.}
  \item{xlab, ylab, main}{plot labels.}
  \item{plot.it}{logical. Should the result be plotted?}
  \item{datax}{logical. Should data values be on the x-axis?}
  \item{ylim, \dots}{graphical parameters.}
}
\description{
  \code{qqnorm} is a generic functions the default method of which
  produces a normal QQ plot of the values in \code{y}.
  \code{qqline} adds a line to a normal quantile-quantile plot which
  passes through the first and third quartiles.

  \code{qqplot} produces a QQ plot of two datasets.

  Graphical parameters may be given as arguments to \code{qqnorm},
  \code{qqplot} and \code{qqline}.
}
\value{
  For \code{qqnorm} and \code{qqplot}, a list with components
  \item{x}{The x coordinates of the points that were/would be plotted}
  \item{y}{The original \code{y} vector, i.e., the corresponding y
    coordinates \emph{including \code{\link{NA}}s}.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
\code{\link{ppoints}}.
}
\examples{
y <- rt(200, df = 5)
qqnorm(y); qqline(y, col = 2)
qqplot(y, rt(300, df = 5))
data(precip)
qqnorm(precip, ylab = "Precipitation [in/yr] for 70 US cities")
}
\keyword{hplot}
\keyword{distribution}
\eof
\name{qr}
\alias{qr}
\alias{qr.coef}
\alias{qr.qy}
\alias{qr.qty}
\alias{qr.resid}
\alias{qr.fitted}
\alias{qr.solve}
\alias{is.qr}
\alias{as.qr}
\alias{solve.qr}
\title{The QR Decomposition of a Matrix}
\usage{
qr(x, tol = 1e-07 , LAPACK = FALSE)
qr.coef(qr, y)
qr.qy(qr, y)
qr.qty(qr, y)
qr.resid(qr, y)
qr.fitted(qr, y, k = qr$rank)
qr.solve(a, b, tol = 1e-7)
\method{solve}{qr}(a, b, \dots)

is.qr(x)
as.qr(x)
}
\arguments{
  \item{x}{a matrix whose QR decomposition is to be computed.}
  \item{tol}{the tolerance for detecting linear dependencies in the
    columns of \code{x}. Only used in \code{LINPACK} is true.}
  \item{qr}{a QR decomposition of the type computed by \code{qr}.}
  \item{y, b}{a vector or matrix of right-hand sides of equations.}
  \item{a}{A QR decomposition or (\code{qr.solve} only) a rectangular matrix.}
  \item{k}{effective rank.}
  \item{LAPACK}{logical. For real \code{x}, if true use LAPACK
    otherwise use LINPACK.}
  \item{\dots}{further arguments passed to or from other methods}
}
\description{
  \code{qr} computes the QR decomposition of a matrix.  It provides an
  interface to the techniques used in the LINPACK routine DQRDC 
  or the LAPACK routines DGEQP3 and (for complex matrices) ZGEQP3.
}
\details{
  The QR decomposition plays an important role in many
  statistical techniques.  In particular it can be used to solve the
  equation \eqn{\bold{Ax} = \bold{b}} for given matrix \eqn{\bold{A}},
  and vector \eqn{\bold{b}}.  It is useful for computing regression
  coefficients and in applying the Newton-Raphson algorithm.

  The functions \code{qr.coef}, \code{qr.resid}, and \code{qr.fitted}
  return the coefficients, residuals and fitted values obtained when
  fitting \code{y} to the matrix with QR decomposition \code{qr}.
  \code{qr.qy} and \code{qr.qty} return \code{Q \%*\% y} and
  \code{t(Q) \%*\% y}, where \code{Q} is the \eqn{\bold{Q}} matrix.

  All the above functions keep \code{dimnames} (and \code{names}) of
  \code{x} and \code{y} if there are.

  \code{solve.qr} is the method for \code{solve} for \code{qr} objects.
  \code{qr.solve} solves systems of equations via the QR decomposition:
  if \code{a} is a QR decomposition it is the same as \code{solve.qr},
  but if \code{a} is a rectangular matrix the QR decomposition is
  computed first.  Either will handle over- and under-determined
  systems, providing a minimal-length solution or a least-squares fit
  if appropriate.

  \code{is.qr} returns \code{TRUE} if \code{x} is a \code{\link{list}}
  with components named \code{qr}, \code{rank} and \code{qraux} and
  \code{FALSE} otherwise.

  It is not possible to coerce objects to mode \code{"qr"}.  Objects
  either are QR decompositions or they are not.
}
\value{
  The QR decomposition of the matrix as computed by LINPACK or LAPACK.
  The components in the returned value correspond directly
  to the values returned by DQRDC/DGEQP3/ZGEQP3.
  \item{qr}{a matrix with the same dimensions as \code{x}.
    The upper triangle contains the \eqn{\bold{R}} of the decomposition
    and the lower triangle contains information on the \eqn{\bold{Q}} of
    the decomposition (stored in compact form).  Note that the storage
    used by DQRDC and DGEQP3 differs.}
  \item{qraux}{a vector of length \code{ncol(x)} which contains
    additional information on \eqn{\bold{Q}}.}
  \item{rank}{the rank of \code{x} as computed by the decomposition:
    always full rank in the LAPACK case.}
  \item{pivot}{information on the pivoting strategy used during
    the decomposition.}

  Non-complex QR objects computed by LAPACK have the attribute
  \code{"useLAPACK"} with value \code{TRUE}.
}
\note{
  To compute the determinant of a matrix (do you \emph{really} need it?),
  the QR decomposition is much more efficient than using Eigen values
  (\code{\link{eigen}}).  See \code{\link{det}}.

  Using LAPACK (including in the complex case) uses column pivoting and
  does not attempt to detect rank-deficient matrices.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Dongarra, J. J., Bunch, J. R., Moler, C. B. and Stewart, G. W. (1978)
  \emph{LINPACK Users Guide.}  Philadelphia: SIAM Publications.

  Anderson. E. and ten others (1999)
  \emph{LAPACK Users' Guide}. Third Edition. SIAM.\cr
  Available on-line at
  \url{http://www.netlib.org/lapack/lug/lapack_lug.html}.
}
\seealso{
  \code{\link{qr.Q}},  \code{\link{qr.R}},  \code{\link{qr.X}} for
  reconstruction of the matrices.
  \code{\link{solve.qr}},  \code{\link{lsfit}},
  \code{\link{eigen}}, \code{\link{svd}}.

  \code{\link{det}} (using \code{qr}) to compute the determinant of a matrix.
}
\examples{
hilbert <- function(n) { i <- 1:n; 1 / outer(i - 1, i, "+") }
h9 <- hilbert(9); h9
qr(h9)$rank           #--> only 7
qrh9 <- qr(h9, tol = 1e-10)
qrh9$rank             #--> 9
##-- Solve linear equation system  H \%*\% x = y :
y <- 1:9/10
x <- qr.solve(h9, y, tol = 1e-10) # or equivalently :
x <- qr.coef(qrh9, y) #-- is == but much better than
                      #-- solve(h9) \%*\% y
h9 \%*\% x              # = y
}
\keyword{algebra}
\keyword{array}
\keyword{regression}
\eof
\name{QR.Auxiliaries}
\title{Reconstruct the Q, R, or X Matrices from a QR Object}
\usage{
qr.X(qr, complete = FALSE, ncol =)
qr.Q(qr, complete = FALSE, Dvec =)
qr.R(qr, complete = FALSE)
}
\alias{qr.X}
\alias{qr.Q}
\alias{qr.R}
\arguments{
  \item{qr}{object representing a QR decomposition.  This will
    typically have come from a previous call to \code{\link{qr}} or
    \code{\link{lsfit}}.}
  \item{complete}{logical expression of length 1.  Indicates whether an
    arbitrary  orthogonal completion of the \eqn{\bold{Q}} or
    \eqn{\bold{X}} matrices is to be made, or whether the \eqn{\bold{R}}
    matrix is to be completed  by binding zero-value rows beneath the
    square upper triangle.}
  \item{ncol}{integer in the range \code{1:nrow(qr$qr)}.  The number
    of columns to be in the reconstructed \eqn{\bold{X}}.  The default
    when \code{complete} is \code{FALSE} is the first
    \code{min(ncol(X), nrow(X))} columns of the original \eqn{\bold{X}}
    from which the qr object was constructed.  The default when
    \code{complete} is \code{TRUE} is a square matrix with the original
    \eqn{\bold{X}} in the first \code{ncol(X)} columns and an arbitrary
    orthogonal completion (unitary completion in the complex case) in
    the remaining columns.}
  \item{Dvec}{vector (not matrix) of diagonal values.  Each column of
    the returned \eqn{\bold{Q}} will be multiplied by the corresponding
    diagonal value.  Defaults to all \code{1}s.}
}
\description{
  Returns the original matrix from which the object was constructed or
  the components of the decomposition.
}
\value{
  \code{qr.X} returns \eqn{\bold{X}}, the original matrix from
  which the qr object was constructed, provided \code{ncol(X) <= nrow(X)}.
  If \code{complete} is \code{TRUE} or the argument \code{ncol} is greater than
  \code{ncol(X)}, additional columns from an arbitrary orthogonal
  (unitary) completion of \code{X} are returned.

  \code{qr.Q} returns \bold{Q}, the order-nrow(X) orthogonal (unitary)
  transformation represented by \code{qr}.  If \code{complete} is
  \code{TRUE}, \bold{Q} has \code{nrow(X)} columns.  If \code{complete}
  is \code{FALSE}, \bold{Q} has \code{ncol(X)} columns.  When
  \code{Dvec} is specified, each column of \bold{Q} is multiplied by the
  corresponding value in \code{Dvec}.

  \code{qr.R} returns \bold{R}, the upper triangular matrix such that
  \code{X == Q \%*\% R}.  The number of rows of \bold{R} is
  \code{nrow(X)} or \code{ncol(X)}, depending on whether \code{complete}
  is \code{TRUE} or \code{FALSE}.
}
\seealso{
  \code{\link{qr}},
  \code{\link{qr.qy}}.
}
\examples{
data(LifeCycleSavings)
p <- ncol(x <- LifeCycleSavings[,-1]) # not the 'sr'
qrstr <- qr(x)   # dim(x) == c(n,p)
qrstr $ rank # = 4 = p
Q <- qr.Q(qrstr) # dim(Q) == dim(x)
R <- qr.R(qrstr) # dim(R) == ncol(x)
X <- qr.X(qrstr) # X == x
range(X - as.matrix(x))# ~ < 6e-12
## X == Q \%*\% R :
Q \%*\% R
}
\keyword{algebra}
\keyword{array}
\eof
\name{quakes}
\docType{data}
\alias{quakes}
\title{Locations of Earthquakes off Fiji}
\description{
  The data set give the locations of 1000 seismic events of MB > 4.0.
  The events occurred in a cube near Fiji since 1964.
}
\usage{data(quakes)}
\format{
  A data frame with 1000 observations on 5 variables.
  \tabular{rlll}{
    [,1] \tab lat      \tab numeric \tab Latitude of event\cr
    [,2] \tab long     \tab numeric \tab Longitude\cr
    [,3] \tab depth    \tab numeric \tab Depth (km)\cr
    [,4] \tab mag      \tab numeric \tab Richter Magnitude\cr
    [,5] \tab stations \tab numeric \tab Number of stations reporting
  }
}
\source{
  This is one of the Harvard PRIM-H project data sets.  They in turn
  obtained it from Dr. John Woodhouse, Dept. of Geophysics, Harvard
  University.
}
\details{
  There are two clear planes of seismic activity.  One is a major plate
  junction; the other is the Tonga trench off New Zealand.  These data
  constitute a subsample from a larger dataset of containing 5000
  observations.
}
\examples{
data(quakes)
pairs(quakes, main = "Fiji Earthquakes, N = 1000", cex.main=1.2, pch=".")
}
\keyword{datasets}
\eof
\name{quantile}
\title{Sample Quantiles}
\alias{quantile}
\alias{quantile.default}
\description{
  The generic function \code{quantile} produces sample quantiles
  corresponding to the given probabilities.
  The smallest observation corresponds to a probability of 0 and the
  largest to a probability of 1.
}
\usage{
quantile(x, \dots)

\method{quantile}{default}(x, probs = seq(0, 1, 0.25), na.rm = FALSE,
         names = TRUE, \dots)
}
\arguments{
  \item{x}{numeric vectors whose sample quantiles are wanted.}
  \item{probs}{numeric vector with values in \eqn{[0,1]}.}
  \item{na.rm}{logical; if true, any \code{\link{NA}} and \code{NaN}'s
    are removed from \code{x} before the quantiles are computed.}
  \item{names}{logical; if true, the result has a \code{\link{names}}
    attribute.  Set to \code{FALSE} for speedup with many \code{probs}.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\details{
  A vector of length \code{length(probs)} is returned;
  if \code{names = TRUE}, it has a \code{\link{names}} attribute.

  \code{quantile(x,p)} as a function of \code{p} linearly interpolates
  the points ( (i-1)/(n-1), ox[i] ), where
  \code{ox <- sort(x)} and \code{n <- length(x)}.

  This gives \code{quantile(x, p) == (1-f)*ox[i] + f*ox[i+1]}, where
  \code{r <- 1 + (n-1)*p}, \code{i <- floor(r)}, \code{f <- r - i}
  \emph{and} \code{ox[n+1] :=  ox[n]}.

  \code{\link{NA}} and \code{\link{NaN}} values in \code{probs} are
  propagated to the result.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link[stepfun]{ecdf}} (in the \pkg{stepfun} package) for
  empirical distributions of which \code{quantile} is the
  \dQuote{inverse};
  \code{\link{boxplot.stats}} and \code{\link{fivenum}} for computing
  \dQuote{versions} of quartiles, etc.
}
\examples{
quantile(x <- rnorm(1001))# Extremes & Quartiles by default
quantile(x,  probs=c(.1,.5,1,2,5,10,50, NA)/100)
}
\keyword{univar}
\eof
\name{quit}
\alias{quit}
\alias{q}
\alias{.Last}
\title{Terminate an R Session}
\usage{
quit(save = "default", status = 0, runLast = TRUE)
   q(save = "default", status = 0, runLast = TRUE)
.Last <- function(x) { \dots\dots }
}
\arguments{
    \item{save}{a character string indicating whether the environment
        (workspace) should be saved, one of \code{"no"}, \code{"yes"},
        \code{"ask"} or \code{"default"}.}
    \item{status}{the (numerical) error status to be returned to the
        operating system, where relevant. Conventionally \code{0}
        indicates successful completion.}
    \item{runLast}{should \code{.Last()} be executed?}
}
\description{
    The function \code{quit} or its alias \code{q} terminate the current
    \R session.
}
\details{
    \code{save} must be one of \code{"no"}, \code{"yes"},
    \code{"ask"} or \code{"default"}.  In the first case the workspace
    is not saved, in the second it is saved and in the third the user is
    prompted and can also decide \emph{not} to quit.  The default is to
    ask in interactive use but may be overridden by command-line
    arguments (which must be supplied in non-interactive use).

    Immediately \emph{before} terminating, the function \code{.Last()}
    is executed if it exists and \code{runLast} is true. If in
    interactive use there are errors in
    the \code{.Last} function, control will be returned to the command
    prompt, so do test the function thoroughly.

    Some error statuses are used by \R itself.  The default error
    handler for non-interactive effectively calls \code{q("no", 1,
      FALSE)} and returns error code 1.  Error status 2 is used for \R
    \sQuote{suicide}, that is a catastrophic failure, and other small
    numbers are used by specific ports for initialization failures.  It
    is recommended that users choose statuses of 10 or more.

    Valid values of \code{status} are system-dependent, but \code{0:255}
    are normally valid.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{\code{\link{.First}} for setting things on startup.
}
\examples{
\dontrun{## Unix-flavour example
.Last <- function() {
  cat("Now sending PostScript graphics to the printer:\n")
  system("lpr Rplots.ps")
  cat("bye bye...\n")
}
quit("yes")}
}
\keyword{environment}
\eof
\name{r2dtable}
\alias{r2dtable}
\title{Random 2-way Tables with Given Marginals}
\description{
  Generate random 2-way tables with given marginals using Patefield's
  algorithm.
}
\usage{
r2dtable(n, r, c)
}
\arguments{
  \item{n}{a non-negative numeric giving the number of tables to be
    drawn.}
  \item{r}{a non-negative vector of length at least 2 giving the row
    totals, to be coerced to \code{integer}.  Must sum to the same as
    \code{c}.}
  \item{c}{a non-negative vector of length at least 2 giving the column
    totals, to be coerced to \code{integer}.}
}
\value{
  A list of length \code{n} containing the generated tables as its
  components.
}
\references{
  Patefield, W. M. (1981)
  Algorithm AS159.  An efficient method of generating r x c tables
  with given row and column totals.
  \emph{Applied Statistics} \bold{30}, 91--97.
} 
\examples{
## Fisher's Tea Drinker data.
TeaTasting <-
matrix(c(3, 1, 1, 3),
       nr = 2,
       dimnames = list(Guess = c("Milk", "Tea"),
                       Truth = c("Milk", "Tea")))
## Simulate permutation test for independence based on the maximum
## Pearson residuals (rather than their sum).
rowTotals <- rowSums(TeaTasting)
colTotals <- colSums(TeaTasting)
nOfCases <- sum(rowTotals)
expected <- outer(rowTotals, colTotals, "*") / nOfCases
maxSqResid <- function(x) max((x - expected) ^ 2 / expected)
simMaxSqResid <-
    sapply(r2dtable(1000, rowTotals, colTotals), maxSqResid)
sum(simMaxSqResid >= maxSqResid(TeaTasting)) / 1000
## Fisher's exact test gives p = 0.4857 ...
}
\keyword{distribution}
\eof
\name{randu}
\docType{data}
\alias{randu}
\title{Random Numbers from Congruential Generator RANDU}
\description{
  400 triples of successive random numbers were taken from the VAX
  FORTRAN function RANDU running under VMS 1.5.
}
\usage{data(randu)}
\details{
  In three dimensional displays it is evident that the triples fall on
  15 parallel planes in 3-space. This can be shown theoretically to be
  true for all triples from the RANDU generator.

  These particular 400 triples start 5 apart in the sequence, that is
  they are ((U[5i+1], U[5i+2], U[5i+3]), i= 0, \dots, 399), and they
  are rounded to 6 decimal places.

  Under VMS versions 2.0 and higher, this problem has been fixed.
}
\format{
  A data frame with 400 observations on 3 variables named \code{x},
  \code{y} and \code{z} which give the first, second and third random
  number in the triple.
}
\source{
  David Donoho
}
\examples{
\dontrun{## We could re-generate the dataset by the following R code
seed <- as.double(1)
RANDU <- function() {
    seed <<- ((2^16 + 3) * seed) \%\% (2^31)
    seed/(2^31)
}
for(i in 1:400) {
    U <- c(RANDU(), RANDU(), RANDU(), RANDU(), RANDU())
    print(round(U[1:3], 6))
}}
}
\keyword{datasets}
\eof
\name{range}
\alias{range}
\alias{range.default}
\title{Range of Values}
\usage{
range(\dots, na.rm = FALSE)

\method{range}{default}(\dots, na.rm = FALSE, finite = FALSE)
}
\arguments{
  \item{\dots}{any \code{\link{numeric}} objects.}
  \item{na.rm}{logical, indicating if \code{\link{NA}}'s should be
    omitted.}
  \item{finite}{logical, indicating if all non-finite elements should
    be omitted.}
}
\description{
  \code{range} returns a vector containing the minimum and maximum of
  all the given arguments.
}
\details{
  This is a generic function; currently, it has only a default method
  (\code{\link{range.default}}).

  It is also a member of the \code{Summary} group of functions, see
  \code{\link[base]{Methods}}.

  If \code{na.rm} is \code{FALSE}, \code{NA}
  and \code{NaN} values in any of the arguments will cause NA values
  to be returned, otherwise \code{NA} values are ignored.

  If \code{finite} is \code{TRUE}, the minimum
  and maximum of all finite values is computed, i.e.,
  \code{finite=TRUE} \emph{includes} \code{na.rm=TRUE}.

  A special situation occurs when there is no (after omission
  of \code{NA}s) nonempty argument left, see \code{\link{min}}.% Extremes.Rd
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{min}},
  \code{\link{max}},
  \code{\link[base]{Methods}}.
}
\examples{
print(r.x <- range(rnorm(100)))
diff(r.x) # the SAMPLE range

x <- c(NA, 1:3, -1:1/0); x
range(x)
range(x, na.rm = TRUE)
range(x, finite = TRUE)
}
\keyword{univar}
\keyword{arith}
\eof
\name{rank}
\alias{rank}
\title{Sample Ranks}
\description{
  Returns the sample ranks of the values in a numeric vector.
  Ties, i.e., equal values, result in ranks being averaged, by default.
}
\usage{
rank(x, na.last = TRUE, ties.method = c("average", "first", "random"))
}
\arguments{
  \item{x}{a numeric vector.}
  \item{na.last}{for controlling the treatment of \code{\link{NA}}s.
    If \code{TRUE}, missing values in the data are put last; if
    \code{FALSE}, they are put first; if \code{NA}, they are removed; if
    \code{"keep"} they are kept.}
  \item{ties.method}{a character string specifying how ties are treated,
    see below; can be abbreviated.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\details{
  If all components are different, the ranks are well defined, with
  values in \code{1:n} where \code{n <- length(x)} and we assume no
  \code{NA}s for the moment.  Otherwise, with some values equal, called
  \sQuote{ties}, the argument \code{ties.method} determines
  the result at the corresponding indices.  The \code{"first"} method
  results in a permutation with increasing values at each index set of
  ties.  The \code{"random"} method puts these in random order whereas the
  default, \code{"average"}, replaces them by their mean.
}
\seealso{\code{\link{order}} and \code{\link{sort}}.}
\examples{
(r1 <- rank(x1 <- c(3, 1, 4, 15, 92)))
x2 <- c(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5)
names(x2) <- letters[1:11]
(r2 <- rank(x2)) # ties are averaged

## rank() is "idempotent": rank(rank(x)) == rank(x) :
stopifnot(rank(r1) == r1, rank(r2) == r2)

## ranks without averaging
rank(x2, ties.method= "first")  # first occurrence wins
rank(x2, ties.method= "random") # ties broken at random
rank(x2, ties.method= "random") # and again
}
\keyword{univar}
\eof
\name{read.00Index}
\alias{read.00Index}
\title{Read 00Index-style Files}
\description{
  Read item/description information from 00Index-style files.  Such
  files are description lists rendered in tabular form, and currently
  used for the object, data and demo indices and \file{TITLE} files of
  add-on packages.
}
\usage{
read.00Index(file)
}
\arguments{
  \item{file}{the name of a file to read data values from.  If the
    specified file is \code{""}, then input is taken from the keyboard
    (in this case input can be terminated by a blank line).
    Alternatively, \code{file} can be a \code{\link{connection}}, which
    will be opened if necessary, and if so closed at the end of the
    function call.}
}
\value{
  a character matrix with 2 columns named \code{"Item"} and
  \code{"Description"} which hold the items and descriptions.
}
\seealso{
  \code{\link{formatDL}} for the inverse operation of creating a
  00Index-style file from items and their descriptions.
}
\keyword{file}
\keyword{connection}
\eof
\name{read.ftable}
\alias{read.ftable}
\alias{write.ftable}
\alias{as.table.ftable}
\title{Manipulate Flat Contingency Tables}
\description{Read, write and coerce \dQuote{flat} contingency tables.}
\usage{
read.ftable(file, sep = "", quote = "\"",
            row.var.names, col.vars, skip = 0)
write.ftable(x, file = "", quote = TRUE, digits = getOption("digits"))

\method{as.table}{ftable}(x, \dots)
}
\arguments{
  \item{file}{either a character string naming a file or a connection
    which the data are to be read from or written to.  \code{""}
    indicates input from the console for reading and output to the
    console for writing.}
  \item{sep}{the field separator string.  Values on each line of the file
    are separated by this string.}
  \item{quote}{a character string giving the set of quoting characters
    for \code{read.ftable}; to disable quoting altogether, use
    \code{quote=""}.  For \code{write.table}, a logical indicating
    whether strings in the data will be surrounded by double quotes.}
  \item{row.var.names}{a character vector with the names of the row
    variables, in case these cannot be determined automatically.}
  \item{col.vars}{a list giving the names and levels of the column
    variables, in case these cannot be determined automatically.}
  \item{skip}{the number of lines of the data file to skip before
    beginning to read data.}
  \item{x}{an object of class \code{"ftable"}.}
  \item{digits}{an integer giving the number of significant digits to
    use for (the cell entries of) \code{x}.}
  \item{\dots}{further arguments to be passed to or from methods.}
}
\details{
  \code{read.ftable} reads in a flat-like contingency table from a
  file.  If the file contains the written representation of a flat
  table (more precisely, a header with all information on names and
  levels of column variables, followed by a line with the names of the
  row variables), no further arguments are needed.  Similarly, flat
  tables with only one column variable the name of which is the only
  entry in the first line are handled automatically.  Other variants can
  be dealt with by skipping all header information using \code{skip},
  and providing the names of the row variables and the names and levels
  of the column variable using \code{row.var.names} and \code{col.vars},
  respectively.  See the examples below.

  Note that flat tables are characterized by their \dQuote{ragged}
  display of row (and maybe also column) labels.  If the full grid of
  levels of the row variables is given, one should instead use
  \code{read.table} to read in the data, and create the contingency
  table from this using \code{\link{xtabs}}.

  \code{write.ftable} writes a flat table to a file, which is useful for
  generating \dQuote{pretty} ASCII representations of contingency tables.

  \code{as.table.ftable} converts a contingency table in flat matrix
  form to one in standard array form.  This is a method for the generic
  function \code{as.table}.
}
\seealso{
  \code{\link{ftable}} for more information on flat contingencty tables.
}
\references{
  Agresti, A.  (1990)
  \emph{Categorical data analysis.}
  New York: Wiley.
}  
\examples{
## Agresti (1990), page 157, Table 5.8.
## Not in ftable standard format, but o.k.
file <- tempfile()
cat("             Intercourse\n",
    "Race  Gender     Yes  No\n",
    "White Male        43 134\n",
    "      Female      26 149\n",
    "Black Male        29  23\n",
    "      Female      22  36\n",
    file = file)
file.show(file)
ft <- read.ftable(file)
ft
unlink(file)

## Agresti (1990), page 297, Table 8.16.
## Almost o.k., but misses the name of the row variable.
file <- tempfile()
cat("                      \"Tonsil Size\"\n",
    "            \"Not Enl.\" \"Enl.\" \"Greatly Enl.\"\n",
    "Noncarriers       497     560           269\n",
    "Carriers           19      29            24\n",
    file = file)
file.show(file)
ft <- read.ftable(file, skip = 2,
                  row.var.names = "Status",
                  col.vars = list("Tonsil Size" =
                      c("Not Enl.", "Enl.", "Greatly Enl.")))
ft
unlink(file)
}
\keyword{category}
\eof
\name{read.fwf}
\alias{read.fwf}
\title{Read Fixed Width Format Files}
\description{
  Read a \dQuote{table} of \bold{f}ixed \bold{w}idth \bold{f}ormatted
  data into a \code{\link{data.frame}}.
}
\usage{
read.fwf(file, widths, header = FALSE, sep = "\t", as.is = FALSE,
         skip = 0, row.names, col.names, n = -1, \dots)
}
\arguments{
  \item{file}{
    the name of the file which the data are to be read from.

    Alternatively, \code{file} can be a \code{\link{connection}}, which
    will be opened if necessary, and if so closed at the end of the
    function call.
  }
  \item{widths}{integer vector, giving the widths of the fixed-width
    fields (of one line).}
  \item{header}{a logical value indicating whether the file contains the
    names of the variables as its first line.}
  \item{sep}{character; the separator used internally; should be a
    character that does not occur in the file.}
  \item{as.is}{see \code{\link{read.table}}.}
  \item{skip}{number of initial lines to skip; see
    \code{\link{read.table}}.}
  \item{row.names}{see \code{\link{read.table}}.}
  \item{col.names}{see \code{\link{read.table}}.}
  \item{n}{the maximum number of records (lines) to be read, defaulting
    to no limit.}
  \item{\dots}{further arguments to be passed to
    \code{\link{read.table}}.}
}
\value{
  A \code{\link{data.frame}} as produced by \code{\link{read.table}}
  which is called internally.
}
\details{
  Fields that are of zero-width or are wholly beyond the end of the line
  in \code{file} are replaced by \code{NA}.
}
\author{
  Brian Ripley for \R version: original \code{Perl} by Kurt Hornik.
}
\seealso{\code{\link{scan}} and \code{\link{read.table}}.}
\examples{
ff <- tempfile()
cat(file=ff, "123456", "987654", sep="\n")
read.fwf(ff, width=c(1,2,3))    #> 1 23 456 \\ 9 87 654
unlink(ff)
cat(file=ff, "123", "987654", sep="\n")
read.fwf(ff, width=c(1,0, 2,3))    #> 1 NA 23 NA \\ 9 NA 87 654
unlink(ff)
}
\keyword{file}
\keyword{connection}
\eof
\name{read.socket}
\title{ Read from or Write to a Socket}
\usage{
read.socket(socket, maxlen=256, loop=FALSE)
write.socket(socket, string)
}
\alias{read.socket}
\alias{write.socket}
\arguments{
    \item{socket}{a socket object}
    \item{maxlen}{maximum length of string to read}
    \item{loop}{wait for ever if there is nothing to read?}
    \item{string}{string to write to socket}
}
\description{
    \code{read.socket} reads a string from the specified socket,
    \code{write.socket} writes to the specified socket.  There is very
    little error checking done by either.
}
\value{
    \code{read.socket} returns the string read.
}
\author{Thomas Lumley}

\seealso{
    \code{\link{close.socket}}, \code{\link{make.socket}}
}

\examples{
finger <- function(user, host = "localhost", port = 79, print = TRUE)
{
    if (!is.character(user))
        stop("user name must be a string")
    user <- paste(user,"\r\n")
    socket <- make.socket(host, port)
    on.exit(close.socket(socket))
    write.socket(socket, user)
    output <- character(0)
    repeat{
        ss <- read.socket(socket)
        if (ss == "") break
        output <- paste(output, ss)
    }
    close.socket(socket)
    if (print) cat(output)
    invisible(output)
}
\dontrun{finger("root")  ## only works if your site provides a finger daemon}
}
\keyword{misc}
\eof
\name{read.table}
\alias{read.table}
\alias{read.csv}
\alias{read.csv2}
\alias{read.delim}
\alias{read.delim2}
\title{Data Input}
\description{
  Reads a file in table format and creates a data frame from it, with
  cases corresponding to lines and variables to fields in the file.
}
\usage{
read.table(file, header = FALSE, sep = "", quote = "\"'", dec = ".",
           row.names, col.names, as.is = FALSE, na.strings = "NA",
           colClasses = NA, nrows = -1,
           skip = 0, check.names = TRUE, fill = !blank.lines.skip,
           strip.white = FALSE, blank.lines.skip = TRUE,
           comment.char = "#")

read.csv(file, header = TRUE, sep = ",", quote="\"", dec=".",
         fill = TRUE, \dots)

read.csv2(file, header = TRUE, sep = ";", quote="\"", dec=",",
         fill = TRUE, \dots)

read.delim(file, header = TRUE, sep = "\t", quote="\"", dec=".",
         fill = TRUE, \dots)

read.delim2(file, header = TRUE, sep = "\t", quote="\"", dec=",",
         fill = TRUE, \dots)
}
\arguments{
  \item{file}{the name of the file which the data are to be read from.
    Each row of the table appears as one line of the file.  If it does
    not contain an \emph{absolute} path, the file name is
    \emph{relative} to the current working directory,
    \code{\link{getwd}()}. Tilde-expansion is performed where supported.

    Alternatively, \code{file} can be a \code{\link{connection}}, which
    will be opened if necessary, and if so closed at the end of the
    function call.  (If \code{stdin()} is used, the prompts for lines
    may be somewhat confusing.  Terminate input with an EOF
    signal, \code{Ctrl-D} on Unix and \code{Ctrl-Z} on Windows.)

    \code{file} can also be a complete URL.
  }

  \item{header}{a logical value indicating whether the file contains the
    names of the variables as its first line.  If missing, the value is
    determined from the file format: \code{header} is set to \code{TRUE}
    if and only if the first row contains one fewer field than the
    number of columns.}

  \item{sep}{the field separator character.  Values on each line of the
    file are separated by this character.  If \code{sep = ""} (the
    default for \code{read.table}) the separator is \dQuote{white space},
    that is one or more spaces, tabs or newlines.}

  \item{quote}{the set of quoting characters. To disable quoting
    altogether, use \code{quote=""}.  See \code{\link{scan}} for the
    behaviour on quotes embedded in quotes.}

  \item{dec}{the character used in the file for decimal points.}

  \item{row.names}{a vector of row names.  This can be a vector giving
    the actual row names, or a single number giving the column of the
    table which contains the row names, or character string giving the
    name of the table column containing the row names.

    If there is a header and the first row contains one fewer field than
    the number of columns, the first column in the input is used for the
    row names.  Otherwise if \code{row.names} is missing, the rows are
    numbered.

    Using \code{row.names = NULL} forces row numbering.
  }

  \item{col.names}{a vector of optional names for the variables.
    The default is to use \code{"V"} followed by the column number.}

  \item{as.is}{the default behavior of \code{read.table} is to convert
    character variables (which are not converted to logical, numeric or
    complex) to factors.  The variable \code{as.is}
    controls this conversion.  Its value is either a vector of logicals
    (values are recycled if necessary), or a vector of numeric or
    character indices which specify which columns should not be
    converted to factors.

    Note: to suppress all conversions including those of numeric
    columns, set \code{colClasses = "character"}.
  }

  \item{na.strings}{a vector of strings which are to be interpreted as
    \code{\link{NA}} values.  Blank fields are also considered to be
    missing values.}

  \item{colClasses}{character.  A vector of classes to be assumed for
    the columns.  Recycled as necessary.  If this is not one of the
    atomic vector classes (logical, integer, numeric, complex and
    character), there needs to be an \code{as} method for
    conversion from \code{"character"} to the specified class, or
    \code{NA} when \code{\link{type.convert}} is used.  NB: \code{as} is
    in package \pkg{methods}.}

  \item{nrows}{the maximum number of rows to read in.  Negative values
    are ignored.}

  \item{skip}{the number of lines of the data file to skip before
    beginning to read data.}

  \item{check.names}{logical.  If \code{TRUE} then the names of the
    variables in the data frame are checked to ensure that they are
    syntactically valid variable names.  If necessary they are adjusted
    (by \code{\link{make.names}}) so that they are, and also to ensure
    that there are no duplicates.}

  \item{fill}{logical. If \code{TRUE} then in case the rows have unequal
    length, blank fields are implicitly added.  See Details.}

  \item{strip.white}{logical. Used only when \code{sep} has
    been specified, and allows the stripping of leading and trailing
    white space from \code{character} fields (\code{numeric} fields
    are always stripped).  See \code{\link{scan}} for further details,
    remembering that the columns may include the row names.}

  \item{blank.lines.skip}{logical: if \code{TRUE} blank lines in the
    input are ignored.}
  
  \item{comment.char}{character: a character vector of length one
    containing a single character or an empty string.  Use \code{""} to
    turn off the interpretation of comments altogether.}

  \item{\dots}{Further arguments to \code{read.table}.}
}
\value{
  A data frame (\code{\link{data.frame}}) containing a representation of
  the data in the file.  Empty input is an error unless \code{col.names}
  is specified, when a 0-row data frame is returned: similarly giving
  just a header line if \code{header = TRUE} results in a 0-row data frame.

  This function is the principal means of reading tabular data into \R.
}
\details{
  If \code{row.names} is not specified and the header line has one less
  entry than the number of columns, the first column is taken to be the
  row names.  This allows data frames to be read in from the format in
  which they are printed.  If \code{row.names} is specified and does
  not refer to the first column, that column is discarded from such files.

  The number of data columns is determined by looking at the first five lines
  of input (or the whole file if it has less than five lines), or from
  the length of \code{col.names} if it is specified and
  is longer.  This could conceivably be wrong if \code{fill} or
  \code{blank.lines.skip} are true.
  
  \code{read.csv} and \code{read.csv2} are identical to
  \code{read.table} except for the defaults.  They are intended for
  reading \dQuote{comma separated value} files (\file{.csv}) or the variant
  used in countries that use a comma as decimal point and a semicolon
  as field separator.  Similarly, \code{read.delim} and
  \code{read.delim2} are for reading delimited files, defaulting to the
  TAB character for the delimiter.  Notice that \code{header = TRUE} and
  \code{fill = TRUE} in these variants.

  Comment characters are allowed unless \code{comment.char = ""}, and
  complete comment lines are allowed provided \code{blank.lines.skip = TRUE}
  However, comment lines prior to the header must have
  the comment character in the first non-blank column.
}
\note{
  The columns referred to in \code{as.is} and \code{colClasses} include
  the column of row names (if any).
  
  Less memory will be used if \code{colClasses} is specified as one of
  the five atomic vector classes.

  Using \code{nrows}, even as a mild over-estimate, will help memory
  usage.

  Using \code{comment.char = ""} will be appreciably faster.

  \code{read.table} is not the right tool for reading large matrices,
  especially those with many columns: it is designed to read
  \emph{data frames} which may have columns of very different classes.
  Use \code{\link{scan}} instead.
}
\seealso{
  The \emph{R Data Import/Export} manual.
  
  \code{\link{scan}}, \code{\link{type.convert}},
  \code{\link{read.fwf}} for reading \emph{f}ixed \emph{w}idth
  \emph{f}ormatted input;
  \code{\link{write.table}};
  \code{\link{data.frame}}.

  \code{\link{count.fields}} can be useful to determine problems with
  reading files which result in reports of incorrect record lengths.
}
\references{
  Chambers, J. M. (1992)
  \emph{Data for models.}
  Chapter 3 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\keyword{file}
\keyword{connection}
\eof
\name{readBin}
\alias{readBin}
\alias{writeBin}
\alias{readChar}
\alias{writeChar}
\title{Transfer Binary Data To and From Connections}
\description{
  Read binary data from a connection, or write binary data to a connection.
}
\usage{
readBin(con, what, n = 1, size = NA, signed = TRUE,
        endian = .Platform$endian)
writeBin(object, con, size = NA, endian = .Platform$endian)

readChar(con, nchars)
writeChar(object, con, nchars = nchar(object), eos = "")
}
\arguments{
  \item{con}{A connection object or a character string.}
  \item{what}{Either an object whose mode will give the mode of the
    vector to be read, or a character vector of length one describing
    the mode: one of \code{"numeric", "double", "integer", "int",
      "logical", "complex", "character"}.}
  \item{n}{integer.  The (maximal) number of records to be
    read. You can use an over-estimate here, but not too large as
    storage is reserved for \code{n} items.}
  \item{size}{integer.  The number of bytes per element in the byte
    stream.  The default, \code{NA}, uses the natural size.  Size changing
    is not supported for complex vectors.}
  \item{signed}{logical. Only used for integers of sizes 1 and 2,
    when it determines if the quantity on file
    should be regarded as a signed or unsigned integer.}
  \item{endian}{The endian-ness (\code{"big"} or \code{"little"} of the
    target system for the file.  Using \code{"swap"} will force swapping
    endian-ness.}
  \item{object}{An \R object to be written to the connection.}
  \item{nchars}{integer, giving the lengths of (unterminated) character
    strings to be read or written.}
  \item{eos}{character. The terminator to be written after each string,
    followed by an ASCII \code{nul}; use \code{NULL} for no terminator
    at all.}
}
\details{
  If the \code{con} is a character string, the functions call
  \code{\link{file}} to obtain an file connection which is opened for
  the duration of the function call.

  If the connection is open it is read/written from its current position.
  If it is not open, it is opened for the duration of the call and then
  closed again.

  If \code{size} is specified and not the natural size of the object,
  each element of the vector is coerced to an appropriate type before
  being written or as it is read.  Possible sizes are 1, 2, 4 and
  possibly 8 for integer or logical vectors, and 4, 8 and possibly 12/16
  for numeric vectors.  (Note that coercion occurs as signed types
  except if \code{signed = FALSE} when reading integers of sizes 1 and 2.)
  Changing sizes is unlikely to preserve \code{NA}s, and the extended
  precision sizes are unlikely to be portable across platforms.

  \code{readBin} and \code{writeBin} read and write C-style
  zero-terminated character strings. Input strings are limited to 10000
  characters.  \code{readChar} and \code{writeChar} allow more
  flexibility, and can also be used on text-mode connections.

  Handling \R's missing and special (\code{Inf}, \code{-Inf} and
  \code{NaN}) values is discussed in the \emph{R Data Import/Export} manual.
}

\note{
  Integer read/writes of size 8 will be available if either C type
  \code{long} is of size 8 bytes or C type \code{long long} exists and
  is of size 8 bytes.

  Real read/writes of size \code{sizeof(long double)} (usually 12 or 16
  bytes) will be available only if that type is available and different
  from \code{double}.

  Note that as \R character strings cannot contain ASCII \code{nul},
  strings read by \code{readChar} which contain such characters will
  appear to be shorter than requested, but the additional bytes are read
  from the file.

  If the character length requested for \code{readChar} is longer than
  the string, as from version 1.4.0 what is available is returned.

  If \code{readBin(what=character())} is used incorrectly on a file which
  does not contain C-style charcter strings, warnings (usually
  many) are  given as from version 1.6.2.  The input will be broken into
  pieces of length 10000 with any final part being discarded.
}

\value{
  For \code{readBin}, a vector of appropriate mode and length the number of
  items read (which might be less than \code{n}).

  For \code{readChar}, a character vector of length the number of
  items read (which might be less than \code{length(nchars)}).

  For \code{writeBin} and \code{writeChar}, none.
}
\seealso{
  The \emph{R Data Import/Export} manual.

  \code{\link{connections}}, \code{\link{readLines}},
  \code{\link{writeLines}}.

  \code{\link{.Machine}} for the sizes of \code{long}, \code{long long}
  and \code{long double}.
}
\examples{
zz <- file("testbin", "wb")
writeBin(1:10, zz)
writeBin(pi, zz, endian="swap")
writeBin(pi, zz, size=4)
writeBin(pi^2, zz, size=4, endian="swap")
writeBin(pi+3i, zz)
writeBin("A test of a connection", zz)
z <- paste("A very long string", 1:100, collapse=" + ")
writeBin(z, zz)
if(.Machine$sizeof.long == 8 || .Machine$sizeof.longlong == 8)
    writeBin(as.integer(5^(1:10)), zz, size = 8)
if((s <-.Machine$sizeof.longdouble) > 8) writeBin((pi/3)^(1:10), zz, size = s)
close(zz)

zz <- file("testbin", "rb")
readBin(zz, integer(), 4)
readBin(zz, integer(), 6)
readBin(zz, numeric(), 1, endian="swap")
readBin(zz, numeric(), size=4)
readBin(zz, numeric(), size=4, endian="swap")
readBin(zz, complex(), 1)
readBin(zz, character(), 1)
z2 <- readBin(zz, character(), 1)
if(.Machine$sizeof.long == 8 || .Machine$sizeof.longlong == 8)
    readBin(zz, integer(), 10,  size = 8)
if((s <-.Machine$sizeof.longdouble) > 8) readBin(zz, numeric(), 10, size = s)
close(zz)
unlink("testbin")
stopifnot(z2 == z)

## test fixed-length strings
zz <- file("testbin", "wb")
x <- c("a", "this will be truncated", "abc")
nc <- c(3, 10, 3)
writeChar(x, zz, nc, eos=NULL)
writeChar(x, zz, eos="\r\n")
close(zz)

zz <- file("testbin", "rb")
readChar(zz, nc)
readChar(zz, nchar(x)+3) # need to read the terminator explicitly
close(zz)
unlink("testbin")

## signed vs unsigned ints
zz <- file("testbin", "wb")
x <- as.integer(seq(0, 255, 32))
writeBin(x, zz, size=1)
writeBin(x, zz, size=1)
x <- as.integer(seq(0, 60000, 10000))
writeBin(x, zz, size=2)
writeBin(x, zz, size=2)
close(zz)
zz <- file("testbin", "rb")
readBin(zz, integer(), 8, size=1)
readBin(zz, integer(), 8, size=1, signed=FALSE)
readBin(zz, integer(), 7, size=2)
readBin(zz, integer(), 7, size=2, signed=FALSE)
close(zz)
unlink("testbin")
}
\keyword{file}
\keyword{connection}
\eof
\name{readLines}
\alias{readLines}
\title{Read Text Lines from a Connection}
\description{
  Read text lines from a connection.
}
\usage{
readLines(con = stdin(), n = -1, ok = TRUE)
}
\arguments{
  \item{con}{A connection object or a character string.}
  \item{n}{integer.  The (maximal) number of lines to
    read. Negative values indicate that one should read up to the end of
    the connection.}
  \item{ok}{logical. Is it OK to reach the end of the connection before
    \code{n > 0} lines are read? If not, an error will be generated.}
}
\details{
  If the \code{con} is a character string, the functions call
  \code{\link{file}} to obtain an file connection which is opened for
  the duration of the function call.

  If the connection is open it is read from its current position.
  If it is not open, it is opened for the duration of the call and then
  closed again.

  If the final line is incomplete (no final EOL marker) the behaviour
  depends on whether the connection is blocking or not. For a blocking
  text-mode connection (or a non-text-mode connection) the line
  will be accepted, with a warning.  For a non-blocking text-mode
  connection the incomplete line is pushed back, silently.
}
\value{
  A character vector of length the number of lines read.
}
\seealso{
  \code{\link{connections}}, \code{\link{writeLines}}, \code{\link{readBin}},
  \code{\link{scan}}}

\examples{
cat("TITLE extra line", "2 3 5 7", "", "11 13 17", file="ex.data",
    sep="\n")
readLines("ex.data", n=-1)
unlink("ex.data") # tidy up

## difference in blocking
cat("123\nabc", file = "test1")
readLines("test1") # line with a warning

con <- file("test1", "r", blocking = FALSE)
readLines(con) # empty
cat(" def\n", file = "test1", append = TRUE)
readLines(con) # gets both
close(con)

unlink("test1") # tidy up
}
\keyword{file}
\keyword{connection}
\eof
\name{readline}
\title{Read a Line from the Terminal}
\usage{
readline(prompt = "")
}
\alias{readline}
\arguments{
  \item{prompt}{the string printed when prompting the user for input.
  Should usually end with a space \code{" "}.}
}
\description{
  \code{readline} reads a line from the terminal
}
\details{
  The prompt string will be truncated to a maximum allowed length,
  normally 256 chars (but can be changed in the source code).
}
\value{
  A character vector of length one.
}
\examples{
fun <- function() {
  ANSWER <- readline("Are you a satisfied R user? ")
  if (substr(ANSWER, 1, 1) == "n")
    cat("This is impossible.  YOU LIED!\n")
  else
    cat("I knew it.\n")
}
fun()
}
\keyword{utilities}
\eof
\name{real}
\title{Real Vectors}
\alias{real}
\alias{as.real}
\alias{is.real}
\usage{
real(length = 0)
as.real(x, \dots)
is.real(x)
}
\description{
  \code{real} creates a double precision vector of the specified
  length. Each element of the vector is equal to \code{0}.

  \code{as.real} attempts to coerce its argument to be of real type.

  \code{is.real} returns \code{TRUE} or \code{FALSE} depending on
  whether its argument is of real type or not.
}
\arguments{
  \item{length}{desired length.}
  \item{x}{object to be coerced or tested.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\note{
  \emph{\R has no single precision data type.
    All real numbers are stored in double precision format}.
}
\keyword{classes}
\eof
\name{recordPlot}
\alias{replayPlot}
\alias{recordPlot}
\alias{print.recordedplot}
\title{Record and Replay Plots}
\description{
  Functions to save the current plot in an \R variable, and to replay it.
}
\usage{
recordPlot()
replayPlot(x)
}
\arguments{
 \item{x}{A saved plot.}
}
\details{
  These functions record and replay the displaylist of the current
  graphics device.  The returned object is of class
  \code{"recordedplot"}, and \code{replayPlot} acts as a \code{print}
  method for that class.

  The format of recorded plots was changed in \R 1.4.0: plots saved in
  earlier versions can still be replayed.
}
\value{
  \code{recordPlot} returns an object of class \code{"recordedplot"}, a
  list with components:
  \item{displaylist}{The saved display list, as a pairlist.}
  \item{gpar}{The graphics state, as an integer vector.}

  \code{replayPlot} has no return value.
}
\keyword{iplot}
\eof
\name{recover}
\alias{recover}
\alias{limitedLabels}
\title{Browsing after an Error}
\description{
  This function allows the user to browse directly on any of the
  currently active function calls, and is suitable as an error option.
  The expression \code{options(error=recover)} will make this
  the error option.
}
\usage{
recover()
}
\details{
  When called, \code{recover} prints the list of current calls, and
  prompts the user to select one of them.  The standard \R
  \code{\link{browser}} is then invoked from the corresponding
  environment; the user can type ordinary S language expressions to be
  evaluated in that environment.

  When finished browsing in this call, type \code{c} to return to
  \code{recover} from the browser.  Type another frame number to browse
  some more, or type \code{0} to exit \code{recover}.

  The use of \code{recover} largely supersedes \code{\link{dump.frames}}
  as an error option, unless you really want to wait to look at the
  error.  If \code{recover} is called in non-interactive mode, it
  behaves like \code{dump.frames}.  For computations involving large
  amounts of data, \code{recover} has the advantage that it does not
  need to copy out all the environments in order to browse in them.  If
  you do decide to quit interactive debugging, call
  \code{\link{dump.frames}} directly while browsing in any frame (see
  the examples).

  \emph{WARNING}: The special \code{Q} command to go directly from the
  browser to the prompt level of the evaluator currently interacts with
  \code{recover} to effectively turn off the error option for the next
  error (on subsequent errors, \code{recover} will be called normally).
}
\value{
  Nothing useful is returned.  However, you \emph{can} invoke
  \code{recover} directly from a function, rather than through the error
  option shown in the examples.  In this case, execution continues
  after you type \code{0} to exit \code{recover}.
}

\section{Compatibility Note}{
  The \R \code{recover} function can be used in the same way as the
  S-Plus function of the same name; therefore, the error option shown is
  a compatible way to specify the error action.  However, the actual
  functions are essentially unrelated and interact quite differently
  with the user.  The navigating commands \code{up} and \code{down} do
  not exist in the \R version; instead, exit the browser and select
  another frame.
}
\references{
  John M. Chambers (1998).
  \emph{Programming with Data}; Springer. \cr
  See the compatibility note above, however.
}
\seealso{
  \code{\link{browser}} for details about the interactive computations;
  \code{\link{options}} for setting the error option;
  \code{\link{dump.frames}} to save the current environments for later
  debugging.
}
\examples{
\dontrun{

options(error = recover) # setting the error option

### Example of interaction

> myFit <- lm(y ~ x, data = xy, weights = w)
Error in lm.wfit(x, y, w, offset = offset, ...) :
        missing or negative weights not allowed

Enter a frame number, or 0 to exit
1:lm(y ~ x, data = xy, weights = w)
2:lm.wfit(x, y, w, offset = offset, ...)
Selection: 2
Called from: eval(expr, envir, enclos)
Browse[1]> objects() # all the objects in this frame
[1] "method" "n"      "ny"     "offset" "tol"    "w"
[7] "x"      "y"
Browse[1]> w
[1] -0.5013844  1.3112515  0.2939348 -0.8983705 -0.1538642
[6] -0.9772989  0.7888790 -0.1919154 -0.3026882
Browse[1]> dump.frames() # save for offline debugging
Browse[1]> c # exit the browser

Enter a frame number, or 0 to exit
1:lm(y ~ x, data = xy, weights = w)
2:lm.wfit(x, y, w, offset = offset, ...)
Selection: 0 # exit recover
>

}%dontrun
}
\keyword{programming}
\keyword{debugging}
\eof
\name{rect}
\title{Draw a Rectangle}
\usage{
rect(xleft, ybottom, xright, ytop, density = NULL, angle = 45,
     col = NULL, border = NULL, lty = NULL, lwd = par("lwd"),
     xpd = NULL, \dots)
}
\alias{rect}
\arguments{
  \item{xleft}{a vector (or scalar) of left x positions.}
  \item{ybottom}{a vector (or scalar) of bottom y positions.}
  \item{xright}{a vector (or scalar) of right x positions.}
  \item{ytop}{a vector (or scalar) of top y positions.}
  \item{density}{the density of shading lines, in lines per inch.
    The default value of \code{NULL} means that no shading lines are drawn.
    A zero value of \code{density} means no shading lines whereas
    negative values (and \code{NA}) suppress shading (and so allow
    color filling).}
  \item{angle}{angle (in degrees) of the shading lines.}
  \item{col}{color(s) to fill or shade the rectangle(s) with.
    The default \code{NULL}, or also \code{\link{NA}} do not fill,
    i.e., draw transparent rectangles, unless \code{density} is specified.}
  \item{border}{color for rectangle border(s).}
  \item{lty}{line type for borders; defaults to \code{"solid"}.}
  \item{lwd}{width for borders.}
  \item{xpd}{logical (\dQuote{e\bold{xp}an\bold{d}}); defaults to
    \code{par("xpd")}.  See \code{\link{par}(xpd= )}.}
  \item{\dots}{other graphical parameters can be given as arguments.}
}
\description{
  \code{rect} draws a rectangle (or sequence of rectangles) with the
  given coordinates, fill and border colors.
}
\details{
  The positions supplied, i.e., \code{xleft, \dots},
  are relative to the current plotting region.  If the x-axis goes from
  100 to 200 then \code{xleft} must be larger than 100 and \code{xright}
  must be less than 200.

  It is a primitive function used in \code{\link{hist}},
  \code{\link{barplot}}, \code{\link{legend}}, etc.
}
\seealso{
  \code{\link{box}} for the \dQuote{standard} box around the plot;
  \code{\link{polygon}} and \code{\link{segments}} for flexible line
  drawing.

  \code{\link{par}} for how to specify colors.
}
\examples{
## set up the plot region:
op <- par(bg = "thistle")
plot(c(100, 250), c(300, 450), type = "n", xlab="", ylab="",
     main = "2 x 11 rectangles; 'rect(100+i,300+i,  150+i,380+i)'")
i <- 4*(0:10)
## draw rectangles with bottom left (100, 300)+i and top right (150, 380)+i
rect(100+i, 300+i, 150+i, 380+i, col=rainbow(11, start=.7,end=.1))
rect(240-i, 320+i, 250-i, 410+i, col=heat.colors(11), lwd=i/5)
## Background alternating  ( transparent / "bg" ) :
j <- 10*(0:5)
rect(125+j, 360+j,   141+j, 405+j/2, col = c(NA,0), border = "gold", lwd = 2)
rect(125+j, 296+j/2, 141+j, 331+j/5, col = c(NA,"midnightblue"))
mtext("+  2 x 6 rect(*, col = c(NA,0)) and  col = c(NA,\"m..blue\"))")

## an example showing colouring and shading
plot(c(100, 200), c(300, 450), type= "n", xlab="", ylab="")
rect(100, 300, 125, 350) # transparent
rect(100, 400, 125, 450, col="green", border="blue") # coloured
rect(115, 375, 150, 425, col=par("bg"), border="transparent")
rect(150, 300, 175, 350, density=10, border="red")
rect(150, 400, 175, 450, density=30, col="blue",
     angle=-30, border="transparent")

legend(180, 450, legend=1:4, fill=c(NA, "green", par("fg"), "blue"),
       density=c(NA, NA, 10, 30), angle=c(NA, NA, 30, -30))

par(op)
}
\keyword{aplot}
\eof
\name{reg.finalizer}
\alias{reg.finalizer}
\title{Finalization of objects}
\description{
  Registers an \R function to be called upon garbage collection of
  object.
}
\usage{
  reg.finalizer(e, f)
}
\arguments{
  \item{e}{Object to finalize. Must be environment or external pointer.}
  \item{f}{Function to call on finalization. Must accept a single argument, 
    which will be the object to finalize.}
}
\value{
  \code{NULL}.
}
\note{
  The purpose of this function is mainly to allow objects that refer to
  external items (a temporary file, say) to perform cleanup actions when
  they are no longer referenced from within \R.  This only makes sense
  for objects that are never copied on assignment, hence the restriction
  to environments and external pointers.
}
\examples{
f <- function(e) print("cleaning....")
g <- function(x){e<-environment(); reg.finalizer(e,f)}
g() 
invisible(gc()) # trigger cleanup
}
\keyword{programming}
\eof
\name{relevel}
\alias{relevel}
\alias{relevel.default}
\alias{relevel.factor}
\alias{relevel.ordered}
\title{Reorder Levels of Factor}
\usage{
relevel(x, ref, \dots)
}
\arguments{
    \item{x}{An unordered factor.}
    \item{ref}{The reference level.}
    \item{\dots}{Additional arguments for future methods.}
}
\description{
    The levels of a factor are re-ordered so that the level specified by
    \code{ref} is first and the others are moved down. This is useful
    for \code{contr.treatment} contrasts which take the first level as
    the reference.
}
\value{
  A factor of the same length as \code{x}.
}

\seealso{\code{\link{factor}}, \code{\link{contr.treatment}}}

\examples{
data(warpbreaks)
warpbreaks$tension <- relevel(warpbreaks$tension, ref="M")
summary(lm(breaks ~ wool + tension, data=warpbreaks))
}
\keyword{utilities}
\keyword{models}
\eof
\name{remove.packages}
\alias{remove.packages}
\title{Remove Installed Packages}
\description{
  Removes installed packages and updates index information as necessary.
}
\usage{
remove.packages(pkgs, lib, version)
}
\arguments{
  \item{pkgs}{a character vector with the names of the packages to be
    removed.}
  \item{lib}{a character string giving the library directory to move the
    packages from.}
  \item{version}{A character string specifying a specific version of the
    package to remove.  If none is provided, the system will remove an
    unversioned install of the package.}
}
\seealso{
#ifdef unix
  \code{\link{REMOVE}} for a command line version;
#endif
  \code{\link{install.packages}} for installing packages.
}
\keyword{utilities}
\eof
\name{rep}
\alias{rep}
\alias{rep.default}
\alias{rep.int}
\alias{rep.POSIXct}
\alias{rep.POSIXlt}
\title{Replicate Elements of Vectors and Lists}
\description{
  \code{rep} replicates the values in \code{x}. It is a generic
  function, and the default method is described here.

  \code{rep.int} is a faster simplified version for the commonest case.
}
\usage{
rep(x, times, \dots)

\method{rep}{default}(x, times, length.out, each, \dots)

rep.int(x, times)
}
\arguments{
  \item{x}{a vector (of any mode including a list) or a pairlist or a
    \code{POSIXct} or \code{POSIXlt} object.}
  \item{times}{non-negative integer.  A vector giving the number of
    times to repeat each element if of length \code{length(x)}, or to
    repeat the whole vector if of length 1.}
  \item{length.out}{integer.  (Optional.)  The desired length of the
    output vector.}
  \item{each}{optional integer. Each element of \code{x} is
    repeated \code{each} times.}
  \item{\dots}{further arguments to be passed to or from other methods.}
}

\details{
  If \code{times} consists of a single integer,
  the result consists of the values in
  \code{x} repeated this many times.
  If \code{times} is a vector of the same length as
  \code{x}, the result consists of \code{x[1]}
  repeated \code{times[1]} times,
  \code{x[2]} repeated \code{times[2]} times and so on.

  \code{length.out} may be given in place of \code{times},
  in which case \code{x} is repeated as many times as is
  necessary to create a vector of this length.  If both
  \code{length.out} and \code{times} are specified, \code{times}
  determines the replication, and \code{length.out} can be used to
  truncate the output vector (or extend it by \code{NA}s).

  Non-integer values of \code{times} will be truncated towards zero.
  If \code{times} is a computed quantity it is prudent to add a small fuzz.
}
\value{
  A vector of the same class as \code{x}.
}
\note{
  If the original vector has names, these are also replicated and so
  will almost always contain duplicates.

  If \code{length.out} is used to extend the vector, the behaviour is
  different from that of S-PLUS, which recycles the existing vector.

  Function \code{rep.int} is a simple case handled by internal code, and
  provided as a separate function purely for S compatibility.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{seq}}, \code{\link{sequence}}.
}
\examples{
rep(1:4, 2)
rep(1:4, each = 2)       # not the same.
rep(1:4, c(2,2,2,2))     # same as second.
rep(1:4, c(2,1,2,1))
rep(1:4, each = 2, len = 4)  # first 4 only.
rep(1:4, each = 2, len = 10)   # 8 integers plus two NAs

rep(1, 40*(1-.8)) # length 7 on most platforms
rep(1, 40*(1-.8)+1e-7) # better

## replicate a list
fred <- list(happy = 1:10, name = "squash")
rep(fred, 5)

# date-time objects
x <- .leap.seconds[1:3]
rep(x, 2)
rep(as.POSIXlt(x), rep(2, 3))
}
\keyword{manip}
\keyword{chron}
\eof
\name{replace}
\title{Replace Values in a Vector}
\usage{
replace(x, list, values)
}
\alias{replace}
\description{
\code{replace} replaces the values in \code{x}
with indexes given in \code{list} by those given in \code{values}.
If necessary, the values in \code{values} are recycled.
}
\arguments{
  \item{x}{vector}
  \item{list}{an index vector}
  \item{values}{replacement values}
}
\value{
  A vector with the values replaced.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\note{
  \code{x} is unchanged: remember to assign the result.
}
\keyword{manip}
\eof
\name{replications}
\title{Number of Replications of Terms}
\usage{
replications(formula, data=NULL, na.action)
}
\alias{replications}
\arguments{
  \item{formula}{a formula or a terms object or a data frame.}
  \item{data}{a data frame used  to  find  the  objects in \code{formula}.}
  \item{na.action}{function for handling missing values.  Defaults to
    a \code{na.action} attribute of \code{data}, then
    a setting of the option \code{na.action}, or \code{na.fail} if that
    is not set.}
}
\description{
  Returns a vector or a list of the number of replicates for
  each term in the formula.
}
\details{
  If \code{formula} is a data frame and \code{data} is missing,
  \code{formula} is used for \code{data} with the formula \code{~ .}.
}
\value{
  A vector or list with one entry for each term in the formula giving
  the number(s) of replications for each level. If all levels are
  balanced (have the same number of replications) the result is a
  vector, otherwise it is a list with a component for each terms,
  as a vector, matrix or array as required.

  A test for balance is \code{!is.list(replications(formula,data))}.
}
\references{
  Chambers, J. M., Freeny, A and Heiberger, R. M. (1992)
  \emph{Analysis of variance; designed experiments.}
  Chapter 5 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\author{
  The design was inspired by the S function of the same name described
  in Chambers \emph{et al.} (1992).
}

\seealso{\code{\link{model.tables}}}

\examples{
## From Venables and Ripley (2002) p.165.
N <- c(0,1,0,1,1,1,0,0,0,1,1,0,1,1,0,0,1,0,1,0,1,1,0,0)
P <- c(1,1,0,0,0,1,0,1,1,1,0,0,0,1,0,1,1,0,0,1,0,1,1,0)
K <- c(1,0,0,1,0,1,1,0,0,1,0,1,0,1,1,0,0,0,1,1,1,0,1,0)
yield <- c(49.5,62.8,46.8,57.0,59.8,58.5,55.5,56.0,62.8,55.8,69.5,
55.0, 62.0,48.8,45.5,44.2,52.0,51.5,49.8,48.8,57.2,59.0,53.2,56.0)

npk <- data.frame(block=gl(6,4), N=factor(N), P=factor(P),
                  K=factor(K), yield=yield)
replications(~ . - yield, npk)
}
\keyword{models}
\eof
\name{reshape}
\alias{reshape}
\title{Reshape Grouped Data}
\description{
  This function reshapes a data frame between \sQuote{wide} format with
  repeated measurements in separate columns of the same record and
  \sQuote{long} format with the repeated measurements in separate
  records.
}
\usage{
reshape(data, varying = NULL, v.names = NULL, timevar = "time",
	idvar = "id", ids = 1:NROW(data),
	times = seq(length = length(varying[[1]])),
	drop = NULL, direction, new.row.names = NULL,
	split = list(regexp="\\.", include=FALSE))
}
\arguments{
  \item{data}{a data frame}
  \item{varying}{names of sets of variables in the wide format that
    correspond to single variables in long format
    (\sQuote{time-varying}).  A list of vectors (or optionally a matrix
    for \code{direction="wide"}).  See below for more details and
    options.}
  \item{v.names}{names of variables in the long format that correspond
    to multiple variables in the wide format.}
  \item{timevar}{the variable in long format that differentiates multiple
    records from the same group or individual.}
  \item{idvar}{the variable in long format that identifies multiple
    records from the same group/individual.  This variable may also be
    present in wide format.}
  \item{ids}{the values to use for a newly created \code{idvar}
    variable in long format.}
  \item{times}{the values to use for a newly created \code{timevar}
    variable in long format.}
  \item{drop}{a vector of names of variables to drop before reshaping}
  \item{direction}{character string, either \code{"wide"} to reshape to
    wide format, or \code{"long"} to reshape to long format.}
  \item{new.row.names}{logical; if \code{TRUE} and \code{direction="wide"},
    create new row names in long format from the values of the id and
    time variables.}
  \item{split}{information for guessing the \code{varying},
    \code{v.names}, and \code{times} arguments.  See below for details.}
}
\details{
  The arguments to this function are described in terms of longitudinal
  data, as that is the application motivating the functions.  A \sQuote{wide}
  longitudinal dataset will have one record for each individual with
  some time-constant variables that occupy single columns and some
  time-varying variables that occupy a column for each time point.  In
  \sQuote{long} format there will be multiple records for each individual, with
  some variables being constant across these records and others varying
  across the records.  A \sQuote{long} format dataset also needs a \sQuote{time}
  variable identifying which time point each record comes from and an
  \sQuote{id} variable showing which records refer to the same person.

  If the data frame resulted from a previous \code{reshape} then the
  operation can be reversed by specifying just the \code{direction}
  argument.  The other arguments are stored as attributes on the data frame.

  If \code{direction="long"} and no \code{varying} or \code{v.names}
  arguments are supplied it is assumed that all variables except
  \code{idvar} and \code{timevar} are time-varying. They are all
  expanded into multiple variables in wide format.

  If \code{direction="wide"} the \code{varying} argument can be a vector
  of column names or column numbers (converted to column names). The
  function will attempt to guess the \code{v.names} and \code{times} from
  these names.  The default is variable names like \code{x.1},
  \code{x.2},where \code{split=list(regexp="\\.",include=FALSE)} to
  specifies to split at the dot and drop it from the name. To have alphabetic
  followed by numeric times use
  \code{split=list(regexp="[A-Za-z][0-9]",include=TRUE)}. This splits
  between the alphabetic and numeric parts of the name and does not drop
  the regular expression.

}
\value{
  The reshaped data frame with added attributes to simplify reshaping
  back to the original form.
}
\seealso{\code{\link{stack}}, \code{\link{aperm}}}

\examples{
data(Indometh,package="nls")
summary(Indometh)
wide <- reshape(Indometh, v.names="conc", idvar="Subject",
                timevar="time", direction="wide")
wide

reshape(wide, direction="long")
reshape(wide, idvar="Subject", varying=list(names(wide)[2:12]),
        v.names="conc", direction="long")

## times need not be numeric
df <- data.frame(id=rep(1:4,rep(2,4)), visit=I(rep(c("Before","After"),4)),
              x=rnorm(4), y=runif(4))
df
reshape(df, timevar="visit", idvar="id", direction="wide")
## warns that y is really varying
reshape(df, timevar="visit", idvar="id", direction="wide", v.names="x")


##  unbalanced 'long' data leads to NA fill in 'wide' form
df2 <- df[1:7,]
df2
reshape(df2, timevar="visit", idvar="id", direction="wide")

## Alternative regular expressions for guessing names
df3 <- data.frame(id=1:4, age=c(40,50,60,50), dose1=c(1,2,1,2),
                  dose2=c(2,1,2,1), dose4=c(3,3,3,3))
reshape(df3, direction="long", varying=3:5,
        split=list(regexp="[a-z][0-9]", include=TRUE))


## an example that isn't longitudinal data
data(state)
state.x77 <- as.data.frame(state.x77)
long <- reshape(state.x77, idvar="state", ids=row.names(state.x77),
                times=names(state.x77), timevar="Characteristic",
                varying=list(names(state.x77)), direction="long")

reshape(long, direction="wide")

reshape(long, direction="wide", new.row.names=unique(long$state))
}
\keyword{manip}

\eof
\name{residuals}
\title{Extract Model Residuals}
\usage{
residuals(object, \dots)
resid(object, \dots)
}
\alias{residuals}
\alias{resid}
\alias{residuals.default}
\arguments{
  \item{object}{an object for which the extraction of model residuals is
    meaningful.}
  \item{\dots}{other arguments.}
}
\value{
  Residuals extracted from the object \code{object}.
}
\description{
  \code{residuals} is a generic function which extracts model residuals
  from objects returned by modeling functions.

  The abbreviated form \code{resid} is an alias for \code{residuals}.
  It is intended to encourage users to access object components through
  an accessor function rather than by directly referencing an object
  slot.

  All object classes which are returned by model fitting functions
  should provide a \code{residuals} method.  (Note that the method is
  \samp{residuals} and not \samp{resid}.)

  Methods can make use of \code{\link{naresid}} methods to compensate
  for the omission of missing values.  The default method does.
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{coefficients}}, \code{\link{fitted.values}},
  \code{\link{glm}}, \code{\link{lm}}.
}
\keyword{models}
\keyword{regression}
\eof
\name{rev}
\alias{rev}
\alias{rev.default}
\title{Reverse Elements}
\usage{
rev(x)
\method{rev}{default}(x)
}
\arguments{
  \item{x}{a vector or another object for which reversion is defined.}
}
\description{
  \code{rev} provides a reversed version of its argument.  It is generic
  function with a default method for vectors and one for
  \code{\link[mva]{dendrogram}}s.

  Note that this is no longer needed (nor efficient) for obtaining
  vectors sorted into descending order, since that is now rather more
  directly achievable by \code{\link{sort}(x, decreasing=TRUE)}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{\code{\link{seq}}, \code{\link{sort}}.}
\examples{
x <- c(1:5,5:3)
## sort into descending order; first more efficiently:
stopifnot(sort(x, decreasing = TRUE) == rev(sort(x)))
stopifnot(rev(1:7) == 7:1)#- don't need 'rev' here
}
\keyword{manip}
\eof
\name{rgb}
\title{RGB Color Specification}
\usage{
rgb(red, green, blue, names=NULL, maxColorValue = 1)
}
\alias{rgb}
\description{
  This function creates \dQuote{colors} corresponding to the given
  intensities (between 0 and \code{max}) of the red, green and blue
  primaries.  The names argument may be used to provide names for the
  colors.

  The values returned by \code{rgb} can be used with a
  \code{col=} specification in graphics functions or in \code{\link{par}}.
}
\arguments{
  \item{red, blue, green}{vectors of same length with values in \eqn{[0, M]}
    where \eqn{M} is \code{maxColorValue}. When this is \code{255}, the
    \code{red}, \code{blue} and \code{green} values are coerced to
    integers in \code{0:255} and the result is computed most efficiently.}
  \item{names}{character. The names for the resulting vector.}
  \item{maxColorValue}{number giving the maximum of the color values
    range, see above.}
}
\seealso{
  \code{\link{col2rgb}} the \dQuote{inverse} for translating \R colors
  to RGB vectors;
  \code{\link{rainbow}}, \code{\link{hsv}}, \code{\link{gray}}.
}
\examples{
rgb(0,1,0)
(u01 <- seq(0,1, length=11))
stopifnot(rgb(u01,u01,u01) == gray(u01))
reds <- rgb((0:15)/15, g=0,b=0, names=paste("red",0:15,sep="."))
reds

rgb(0, 0:12, 0, max = 255)# integer input
}
\keyword{color}
\eof
\name{rivers}
\docType{data}
\alias{rivers}
\title{Lengths of Major North American Rivers}
\description{
  This data set gives the lengths (in miles) of 141 \dQuote{major}
  rivers in North America, as compiled by the US Geological Survey.
}
\usage{data(rivers)}
\format{A vector containing 141 observations.}
\source{World Almanac and Book of Facts, 1975, page 406.}
\references{
  McNeil, D. R. (1977) \emph{Interactive Data Analysis}.
  New York: Wiley.
}
\keyword{datasets}
\eof
\name{rle}
\title{Run Length Encoding}
\alias{rle}
\alias{inverse.rle}
\alias{print.rle}
\description{
  Compute the lengths and values of runs of equal values in a vector
  -- or the reverse operation.
}
\usage{
rle(x)
inverse.rle(x, \dots)
}
\arguments{
  \item{x}{a simple vector for \code{rle()} or an object of class
    \code{"rle"} for \code{inverse.rle()}.}
  \item{\dots}{further arguments which are ignored in \R.}
}
\value{
  \code{rle()} returns an object of class \code{"rle"} which is a list
  with components
  \item{lengths}{an integer vector containing the length of each run.}
  \item{values}{a vector of the same length as \code{lengths} with the
    corresponding values.}

  \code{inverse.rle()} is the inverse function of \code{rle()}.
}
\examples{
x <- rev(rep(6:10, 1:5))
rle(x)
## lengths [1:5]  5 4 3 2 1
## values  [1:5] 10 9 8 7 6

z <- c(TRUE,TRUE,FALSE,FALSE,TRUE,FALSE,TRUE,TRUE,TRUE)
rle(z)
rle(as.character(z))

stopifnot(x == inverse.rle(rle(x)),
          z == inverse.rle(rle(z)))
}
\keyword{manip}
\eof
\name{remove}
\title{Remove Objects from a Specified Environment}
\usage{
remove(\dots, list = character(0), pos = -1, envir = as.environment(pos),
       inherits = FALSE)
rm    (\dots, list = character(0), pos = -1, envir = as.environment(pos),
       inherits = FALSE)
}
\alias{rm}
\alias{remove}
\arguments{
  \item{\dots}{the objects to be removed, supplied individually and/or as a
    character vector}
  \item{list}{a character vector naming objects to be removed.}
  \item{pos}{where to do the removal.  By default, uses the
    current environment.  See the details for other possibilities.}
  \item{envir}{the \code{\link{environment}} to use. See the details section.}
  \item{inherits}{should the enclosing frames of the environment be
    inspected?}
}
\description{
  \code{remove} and \code{rm} can be used to remove objects.  These can
  be specified successively as character strings, or in the character
  vector \code{list}, or through a combination of both.  All objects
  thus specified will be removed.

  If \code{envir} is NULL then the the currently active environment is
  searched first.

  If \code{inherits} is \code{TRUE} then parents of the supplied
  directory are searched until a variable with the given name is
  encountered.  A warning is printed for each variable that is not
  found.
}
\details{
  The \code{pos} argument can specify the  environment from which to remove
  the objects in any of several ways:
  as an integer (the position in the \code{\link{search}} list); as
  the character string name of an element in the search list; or as an
  \code{\link{environment}} (including using \code{\link{sys.frame}} to
  access the currently active function calls).
  The \code{envir} argument is an alternative way to specify an
  environment, but is primarily there for back compatibility.
   }
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{ls}}, \code{\link{objects}}
}
\examples{
tmp <- 1:4
## work with tmp  and cleanup
rm(tmp)

\dontrun{
## remove (almost) everything in the working environment.
## You will get no warning, so don't do this unless you are really sure.
rm(list = ls())
}}
\keyword{environment}
\eof
\name{round.POSIXt}
\alias{round.POSIXt}
\alias{trunc.POSIXt}
\title{Round / Truncate Data-Time Objects}
\description{
  Round or truncate date-time objects.
}
\usage{
\method{round}{POSIXt}(x, units=c("secs", "mins", "hours", "days"))
\method{trunc}{POSIXt}(x, units=c("secs", "mins", "hours", "days"))
}
\arguments{
  \item{x}{an object inheriting from \code{"POSIXt"}.}
  \item{units}{one of the units listed.  Can be abbreviated.}
}
\details{
  The time is rounded or truncated to the second, minute, hour or day.
  Timezones are only relevant to days, when midnight in the current
  timezone is used.
}
\value{
  An object of class \code{"POSIXlt"}.
}
\seealso{\code{\link{DateTimeClasses}}}

\examples{
round(.leap.seconds + 1000, "hour")
trunc.POSIXt(Sys.time(), "day")
}
\keyword{chron}
\eof
\name{row}
\alias{row}
\title{Row Indexes}
\description{
  Returns a matrix of integers indicating their row number in the
  matrix.
}
\usage{
row(x, as.factor = FALSE)
}
\arguments{
  \item{x}{a matrix.}
  \item{as.factor}{a logical value indicating whether the value should
    be returned as a factor rather than as numeric.}
}
\value{
  An integer matrix with the same dimensions as \code{x} and whose
  \code{ij}-th element is equal to \code{i}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{col}} to get columns.
}
\examples{
x <- matrix(1:12, 3, 4)
# extract the diagonal of a matrix
dx <- x[row(x) == col(x)]
dx

# create an identity 5-by-5 matrix
x <- matrix(0, nr = 5, nc = 5)
x[row(x) == col(x)] <- 1
x
}
\keyword{array}
\eof
\name{row.names}
\title{Get and Set Row Names for Data Frames}
\alias{row.names}
\alias{row.names.data.frame}
\alias{row.names.default}
\alias{row.names<-}
\alias{row.names<-.data.frame}
\alias{row.names<-.default}
\description{
  All data frames have a row names attribute, a character vector of
  length the number of rows with no duplicates nor missing values.

  For convenience, these are generic functions for which users can write
  other methods, and there are default methods for arrays.  The
  description here is for the \code{data.frame} method.
}
\usage{
row.names(x)
row.names(x) <- value
}
\arguments{
  \item{x}{object of class \code{"data.frame"}, or any other class for
    which a method has been defined.}
  \item{value}{a vector with the same length as the number of rows of
    \code{x}, to be coerced to character.  Duplicated or missing values
    are not allowed.}
}
\value{
  \code{row.names} returns a character vector.

  \code{row.names<-} returns a data frame with the row names changed.
}
\note{
  \code{row.names} is similar to \code{\link{rownames}} for arrays, and
  it has a method that calls \code{rownames} for an array argument.
}
\references{
  Chambers, J. M. (1992)
  \emph{Data for models.}
  Chapter 3 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{data.frame}}, \code{\link{rownames}}.
}
\keyword{classes}
\keyword{methods}
\eof
\name{rowsum}
\alias{rowsum}
\alias{rowsum.default}
\alias{rowsum.data.frame}
\title{
Give row sums of a matrix or data frame, based on a grouping variable
}
\description{
  Compute sums across rows of a matrix-like object for each level of a grouping
  variable. \code{rowsum} is generic, with methods for matrices and data
  frames.
}
\usage{
rowsum(x, group, reorder = TRUE, \dots)
}
\arguments{
  \item{x}{a matrix, data frame or vector of numeric data.  Missing
  values are    allowed.}
  \item{group}{a vector giving the grouping, with one element per row of
    \code{x}.  Missing values will be treated as another group and a
    warning will be given}
  \item{reorder}{if \code{TRUE}, then the result will be in order of
    \code{sort(unique(group))}, if \code{FALSE}, it will be in the order
    that rows were encountered. }
  \item{\dots}{other arguments for future methods}
}
\value{
  a matrix or data frame containing the sums.  There will be one row per
  unique value  of \code{group}.
}

\details{
  The default is to reorder the rows to agree with \code{tapply} as in
  the example below. Reordering should not add noticeably to the time
  except when there are very many distinct values of \code{group} and
  \code{x} has few columns.

  The original function was written by Terry Therneau, but this is a
  new implementation using hashing that is much faster for large matrices.

  To add all the rows of a matrix (ie, a single \code{group}) use
  \code{\link{rowSums}}, which should be even faster.
}

\seealso{
  \code{\link{tapply}}, \code{\link{aggregate}},\code{\link{rowSums}}
}
\examples{
x <- matrix(runif(100), ncol=5)
group <- sample(1:8, 20, TRUE)
xsum <- rowsum(x, group)
## Slower versions
xsum2 <- tapply(x, list(group[row(x)], col(x)), sum)
xsum3<- aggregate(x,list(group),sum)

}
\keyword{manip}

\eof
\name{rug}
\title{Add a Rug to a Plot}
\alias{rug}
\usage{
rug(x, ticksize=0.03, side=1, lwd=0.5, col,
    quiet = getOption("warn") < 0, \dots)
}
\arguments{
 \item{x}{A numeric vector}
 \item{ticksize}{The length of the ticks making up the \sQuote{rug}.
   Positive lengths give inwards ticks.}
 \item{side}{On which side of the plot box the rug will be
   plotted. Normally 1 (bottom) or 3 (top).}
 \item{lwd}{The line width of the ticks.}
 \item{col}{The colour the ticks are plotted in, default is black.}
 \item{quiet}{logical indicating if there should be a warning about
   clipped values.}
 \item{\dots}{further arguments, passed to \code{\link{axis}(...)}, such
   as \code{line} or \code{pos} for specifying the location of the rug.}
}
\description{
  Adds a \emph{rug} representation (1-d plot) of the data to the plot.
}
\details{
  Because of the way \code{rug} is implemented, only values of \code{x}
  that fall within the plot region are included.  There will be a
  warning if any finite values are omitted, but non-finite values are
  omitted silently.

  Because of the way colours are done the axis itself is coloured the
  same as the ticks.  You can always replot the box in black if you don't
  like this feature.
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S.}
  Wadsworth \& Brooks/Cole.
}
\seealso{\code{\link{jitter}} which you may want for ties in \code{x}.}
\examples{
data(faithful)
with(faithful, {
    plot(density(eruptions, bw=0.15))
    rug(eruptions)
    rug(jitter(eruptions, amount = .01), side = 3, col = "light blue")
})
}
\keyword{aplot}
\eof
\name{sQuote}
\alias{sQuote}
\alias{dQuote}
\title{Quote Text}
\description{
  Single or double quote text by combining with appropriate single or
  double left and right quotation marks.
}
\usage{
sQuote(x)
dQuote(x)
}
\arguments{
  \item{x}{an \R object, to be coerced to a character vector.}
}
\details{
  The purpose of the functions is to provide a simple means of markup
  for quoting text to be used in the R output, e.g., in warnings or
  error messages.

  The choice of the appropriate quotation marks depends on both the
  locale and the available character sets.  Older Unix/X11 fonts
  displayed the grave accent (0x60) and the apostrophe (0x27) in a way
  that they could also be used as matching open and close single
  quotation marks.  Using modern fonts, or non-Unix systems, these
  characters no longer produce matching glyphs.  Unicode provides left
  and right single quotation mark characters (U+2018 and U+2019); if
  Unicode cannot be assumed, it seems reasonable to use the apostrophe
  as an undirectional single quotation mark.

  Similarly, Unicode has left and right double quotation mark characters
  (U+201C and U+201D); if only ASCII's typewriter characteristics can be
  employed, than the ASCII quotation mark (0x22) should be used as both
  the left and right double quotation mark.

  \code{sQuote} and \code{dQuote} currently only provide undirectional
  ASCII quotation style, but may be enhanced in the future.
}
\references{
  Markus Kuhn, \dQuote{ASCII and Unicode quotation marks}.
  \url{http://www.cl.cam.ac.uk/~mgk25/ucs/quotes.html}
}
\examples{
paste("argument", sQuote("x"), "must be non-zero")
}
\keyword{character}
\eof
\name{sample}
\alias{sample}
\title{Random Samples and Permutations}
\description{
  \code{sample} takes a sample of the specified size from the elements
  of \code{x} using either with or without replacement.
}
\usage{
sample(x, size, replace = FALSE, prob = NULL)
}
\arguments{
  \item{x}{Either a (numeric, complex, character or logical) vector of
    more than one element from which to choose, or a positive integer.}
  \item{size}{non-negative integer giving the number of items to choose.}
  \item{replace}{Should sampling be with replacement?}
  \item{prob}{A vector of probability weights for obtaining the elements
    of the vector being sampled.}
}
\details{
  If \code{x} has length 1, sampling takes place from
  \code{1:x}.  \emph{Note} that this convenience feature may lead to
  undesired behaviour when \code{x} is of varying length
  \code{sample(x)}.  See the \code{resample()} example below.

  By default \code{size} is equal to \code{length(x)}
  so that \code{sample(x)} generates a random permutation
  of the elements of \code{x} (or \code{1:x}).

  The optional \code{prob} argument can be used to give a vector
  of weights for obtaining the elements of the vector being
  sampled. They need not sum to one, but they should be nonnegative
  and not all zero.
  If \code{replace} is false, these probabilities are applied
  sequentially, that is the probability of choosing the next item is
  proportional to the probabilities amongst the remaining items. The number
  of nonzero weights must be at least \code{size} in this case.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
x <- 1:12
# a random permutation
sample(x)
# bootstrap sampling -- only if length(x) > 1 !
sample(x,replace=TRUE)

# 100 Bernoulli trials
sample(c(0,1), 100, replace = TRUE)

## More careful bootstrapping --  Consider this when using sample()
## programmatically (i.e., in your function or simulation)!

# sample()'s surprise -- example
x <- 1:10
    sample(x[x >  8]) # length 2
    sample(x[x >  9]) # oops -- length 10!
try(sample(x[x > 10]))# error!

## This is safer:
resample <- function(x, size, ...)
  if(length(x) <= 1) { if(!missing(size) && size == 0) x[FALSE] else x
  } else sample(x, size, ...)

resample(x[x >  8])# length 2
resample(x[x >  9])# length 1
resample(x[x > 10])# length 0
}
\keyword{distribution}
\eof
\name{save}
\alias{save}
\alias{save.image}
\alias{sys.save.image}
\alias{sys.load.image}
\title{Save R Objects}
\description{
  \code{save} writes a external representation of \R objects to the
  specified file.  The objects can be read back from the file at a later
  date by using the function \code{load} (or \code{data} in some cases).

  \code{save.image()} is just a short-cut for \dQuote{save my current
    environment},
  i.e., \code{save(list = ls(all=TRUE), file = ".RData")}. It is what also
  happens with \code{\link{q}("yes")}.
}
\usage{
save(\dots, list = character(0), file = stop("'file' must be specified"),
     ascii = FALSE, version = NULL, envir = parent.frame(), 
     compress = FALSE)
save.image(file = ".RData", version = NULL, ascii = FALSE,
           compress = FALSE, safe = TRUE)

sys.load.image(name, quiet)
sys.save.image(name)
}
\arguments{
  \item{\dots}{the names of the objects to be saved.}
  \item{list}{A character vector containing the names of objects to be
    saved.}
  \item{file}{a connection or the name of the file where the data will be
    saved.  Must be a file name for workspace format version 1.}
  \item{ascii}{if \code{TRUE}, an ASCII representation of the data is
    written.  This is useful for transporting data between machines of
    different types.  The default value of \code{ascii} is \code{FALSE}
    which leads to a more compact binary file being written.}
  \item{version}{the workspace format version to use.  \code{NULL}
    specifies the current default format.  The version used from \R
    0.99.0 to \R 1.3.1 was version 1.  The default format as from \R
    1.4.0 is version 2.}
  \item{envir}{environment to search for objects to be saved.}
  \item{compress}{logical specifying whether saving to a named file is to
    use compression. Ignored when \code{file} is a connection and for
    workspace format version 1.}
  \item{safe}{logical.  If \code{TRUE}, a temporary file is used for
    creating the saved workspace.  The temporary file is renamed to
    \code{file} if the save succeeds.  This preserves an existing
    workspace \code{file} if the save fails, but at the cost of using
    extra disk space during the save.}
  \item{name}{name of image file to save or load.}
  \item{quiet}{logical specifying whether a message should be printed.}
  }
}
\details{
  All \R platforms use the XDR representation of binary objects in
  binary save-d files, and these are portable across all \R platforms.

  Default values for \code{save.image} options can be modified with
  the \code{save.image.defaults} option.  This mechanism is experimental
  and subject to change.

  \code{sys.save.image} is a system function that is called by \code{q()}
  and its GUI analogs; \code{sys.load.image} is called by the startup code.
  These functions should not be called directly and are subject to change.

  \code{sys.save.image} closes all connections first, to ensure that it
  is able to open a connection to save the image.  This is appropriate
  when called from \code{q()} and allies, but reinforces the warning
  that it should not be called directly.
}
\section{Warning}{
  The \code{\dots} arguments only give the \emph{names} of the objects
  to be saved: they are searched for in the environment given by the
  \code{envir} argument, and the actual objects given as arguments need
  not be those found.  
}
\seealso{
  \code{\link{dput}}, \code{\link{dump}}, \code{\link{load}},
  \code{\link{data}}.
}
\examples{
x <- runif(20)
y <- list(a = 1, b = TRUE, c = "oops")
save(x, y, file = "xy.Rdata")
save.image()
unlink("xy.Rdata")
unlink(".RData")

# set save.image defaults using option:
options(save.image.defaults=list(ascii=TRUE, safe=FALSE))
save.image()
unlink(".RData")
}
\keyword{file}
\eof
\name{savehistory}
\alias{loadhistory}
\alias{savehistory}
\alias{history}
\title{Load or Save or Display the Commands History}
\description{
  Load or save or display the commands history.
}
\usage{
loadhistory(file = ".Rhistory")
savehistory(file = ".Rhistory")
history(max.show = 25, reverse = FALSE)
}
\arguments{
  \item{file}{The name of the file in which to save the history, or
    from which to load it. The path is relative to the current
    working directory.}
  \item{max.show}{The maximum number of lines to show. \code{Inf} will
    give all of the currently available history.}
  \item{reverse}{logical. If true, the lines are shown in reverse
    order. Note: this is not useful when there are continuation lines.}
}
\details{
#ifdef windows
  This works in Rgui and interactive Rterm but not in batch use of Rterm
  nor in embedded/DCOM versions.
#endif
#ifdef unix
  This works under the \code{readline} and GNOME interfaces, but not if
  \code{readline} is not available (for example, in batch use).
#endif
}
\note{
  If you want to save the history (almost) every session, you can put a
  call to \code{savehistory()} in \code{\link{.Last}}.
}
\examples{\dontrun{
.Last <- function()
    if(interactive()) try(savehistory("~/.Rhistory"))
}}
\keyword{utilities}
\eof
\name{scale}
\alias{scale}
\alias{scale.default}
\title{Scaling and Centering of Matrix-like Objects}
\description{
  \code{scale} is generic function whose default method centers and/or
  scales the columns of a numeric matrix.
}
\usage{
scale(x, center = TRUE, scale = TRUE)
}
\arguments{
  \item{x}{a numeric matrix(like object).}
  \item{center}{either a logical value or a numeric vector of length
    equal to the number of columns of \code{x}.}
  \item{scale}{either a logical value or a numeric vector of length
    equal to the number of columns of \code{x}.}
}
\value{
  For \code{scale.default}, the centered, scaled matrix. The numeric
  centering and scalings used (if any) are returned as attributes
  \code{"scaled:center"} and \code{"scaled:scale"}
}
\details{
  The value of \code{center} determines how column centering is
  performed.
  If \code{center} is a numeric vector with length equal to the number
  of columns of \code{x}, then each column of \code{x} has the
  corresponding value from \code{center} subtracted from it.
  If \code{center} is \code{TRUE} then centering is done by subtracting
  the column means (omitting \code{NA}s) of \code{x} from their
  corresponding columns, and if \code{center} is \code{FALSE},
  no centering is done.

  The value of \code{scale} determines how column scaling is performed
  (after centering).
  If \code{scale} is a numeric vector with length equal to the number of
  columns of \code{x}, then each column of \code{x} is divided by the
  corresponding value from \code{scale}.
  If \code{scale} is \code{TRUE} then scaling is done by dividing the
  (centered) columns of \code{x} by their root-mean-square, and if
  \code{scale} is \code{FALSE}, no scaling is done.

  The root-mean-square for a column is obtained by computing the
  square-root of the sum-of-squares of the non-missing values in the
  column divided by the number of non-missing values minus one.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{sweep}} which allows centering (and scaling) with
  arbitrary statistics.

  For working with the scale of a plot, see \code{\link{par}}.
}
\examples{
x <- matrix(1:10, nc=2)
(centered.x <- scale(x, scale=FALSE))
cov(centered.scaled.x <- scale(x))# all 1
}
\keyword{array}
\eof
\name{scan}
\title{Read Data Values}
\alias{scan}
\description{
  Read data into a vector or list from the console or file.
}
\usage{
scan(file = "", what = double(0), nmax = -1, n = -1, sep = "",
     quote = if (sep=="\n") "" else "'\"", dec = ".",
     skip = 0, nlines = 0, na.strings = "NA",
     flush = FALSE, fill = FALSE, strip.white = FALSE, quiet = FALSE,
     blank.lines.skip = TRUE, multi.line = TRUE, comment.char = "")
}
\arguments{
  \item{file}{the name of a file to read data values from.  If the
    specified file is \code{""}, then input is taken from the keyboard
    (in this case input can be terminated by a blank line or an EOF
    signal, \code{Ctrl-D} on Unix and \code{Ctrl-Z} on Windows.).

    Otherwise, the file name is interpreted \emph{relative} to the
    current working directory (given by \code{\link{getwd}()}),
    unless it specifies an \emph{absolute} path.
    Tilde-expansion is performed where supported.

    Alternatively, \code{file} can be a \code{\link{connection}}, which
    will be opened if necessary, and if so closed at the end of the
    function call.

    \code{file} can also be a complete URL.
  }
  \item{what}{the type of \code{what} gives the type of data to be
    read.  If \code{what} is a list, it is assumed that the lines of the
    data file are records each containing \code{length(what)} items
    (\dQuote{fields}).  The supported types are \code{logical},
    \code{integer}, \code{numeric}, \code{complex}, \code{character} and
    \code{list}: \code{list} values should have elements which are one
    of the first five types listed or \code{NULL}.}

  \item{nmax}{the maximum number of data values to be read, or if
    \code{what} is a list, the maximum number of records to be read.  If
    omitted (and \code{nlines} is not set to a positive value),
    \code{scan} will read to the end of \code{file}.}

  \item{n}{the maximum number of data values to be read, defaulting to
    no limit.}

  \item{sep}{by default, scan expects to read white-space delimited
    input fields.  Alternatively, \code{sep} can be used to specify a
    character which delimits fields.  A field is always delimited by a
    newline unless it is quoted.} 

  \item{quote}{the set of quoting characters as a single character
    string.}

  \item{dec}{decimal point character.}

  \item{skip}{the number of  lines of the input file to skip before
    beginning to read data values.}

  \item{nlines}{the maximum number of lines of data to be read.}

  \item{na.strings}{character vector.  Elements of this vector are to be
    interpeted as missing (\code{\link{NA}}) values.}

  \item{flush}{logical: if \code{TRUE}, \code{scan} will flush to the
    end of the line after reading the last of the fields requested.
    This allows putting comments after the last field, but precludes
    putting more that one record on a line.}
  
  \item{fill}{logical: if \code{TRUE}, \code{scan} will implicitly add
    empty fields to any lines with fewer fields than implied by
    \code{what}.}
  
  \item{strip.white}{vector of logical value(s) corresponding to items
    in the \code{what} argument. It is used only when \code{sep} has
    been specified, and allows the stripping of leading and trailing
    white space from \code{character} fields (\code{numeric} fields
    are always stripped).

    If \code{strip.white} is of length 1, it applies to all fields;
    otherwise, if \code{strip.white[i]} is \code{TRUE} \emph{and} the
    \code{i}-th field is of mode character (because \code{what[i]} is)
    then the leading and trailing white space from field \code{i} is
    stripped.}
  
  \item{quiet}{logical: if \code{FALSE} (default), scan() will print a
    line, saying how many items have been read.}

  \item{blank.lines.skip}{logical: if \code{TRUE} blank lines in the
    input are ignored, except when counting \code{skip} and \code{nlines}.}

  \item{multi.line}{logical. Only used if \code{what} is a list.
    If \code{FALSE}, all of a record must appear on one line (but more
    than one record can appear on a single line).  Note that using
    \code{fill = TRUE} implies that a record will terminated at the end
    of a line.}
  
  \item{comment.char}{character: a character vector of length one
    containing a single character or an empty string.  Use \code{""} to
    turn off the interpretation of comments altogether (the default).}
}
\details{
  The value of \code{what} can be a list of types, in which case
  \code{scan} returns a list of vectors with the types given by the
  types of the elements in \code{what}.  This provides a way of reading
  columnar data.  If any of the types is \code{NULL}, the corresponding
  field is skipped (but a \code{NULL} component appears in the result).

  The type of \code{what} or its components can be one of the five
  atomic types or \code{NULL},

  Empty numeric fields are always regarded as missing values.
  Empty character fields are scanned as empty character vectors, unless
  \code{na.strings} contains \code{""} when they are regarded as missing
  values.
  
  If \code{sep} is the default (\code{""}), the character \code{\\}
  in a quoted string escapes the following character, so quotes may
  included in the string by escaping them.
  
  If \code{sep} is non-default, the fields may be quoted in the style of
  \file{.csv} files where separators inside quotes (\code{''} or 
  \code{""}) are ignored and quotes may be put inside strings by
  doubling them.  However, if \code{sep = "\\n"} it is assumed
  by default that one wants to read entire lines verbatim.

  Quoting is only interpreted in character fields, and as from \R 1.8.0
  in \code{NULL} fields (which might be skipping character fields).

  Note that since \code{sep} is a separator and not a terminator,
  reading a file by \code{scan("foo", sep="\\n", blank.lines.skip=FALSE)}
  will give an empty file line if the file ends in a linefeed and not if
  it does not.  This might not be what you expected; see also
  \code{\link{readLines}}.

  If \code{comment.char} occurs (except inside a quoted character
  field), it signals that the rest of the line
  should be regarded as a comment and be discarded.  Lines beginning
  with a comment character (possibly after white space) are treated
  as blank lines. 
}
\value{
  if \code{what} is a list, a list of the same length and same names (as
  any) as \code{what}.

  Otherwise, a vector of the type of \code{what}.
}
\note{
  The default for \code{multi.line} differs from S.  To read one record
  per line, use \code{flush = TRUE} and \code{multi.line = FALSE}.
  
  If number of items is not specified, the internal
  mechanism re-allocates memory in powers of two and so could use up
  to three times as much memory as needed.  (It needs both old and new
  copies.)  If you can, specify either \code{n} or \code{nmax} whenever
  inputting a large vector, and \code{nmax} or \code{nlines} when
  inputting a large list.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{read.table}} for more user-friendly reading of data
  matrices;
  \code{\link{readLines}} to read a file a line at a time.
  \code{\link{write}}.
}
\examples{
cat("TITLE extra line", "2 3 5 7", "11 13 17", file="ex.data", sep="\n")
pp <- scan("ex.data", skip = 1, quiet= TRUE)
    scan("ex.data", skip = 1)
    scan("ex.data", skip = 1, nlines=1)# only 1 line after the skipped one
str(scan("ex.data", what = list("","",""))) # flush is F -> read "7"
str(scan("ex.data", what = list("","",""), flush = TRUE))
unlink("ex.data") # tidy up
}
\keyword{file}
\keyword{connection}
\eof
\name{screen}
\title{Creating and Controlling Multiple Screens on a Single Device}
\usage{
split.screen(figs, screen = , erase = TRUE)
screen(n = , new = TRUE)
erase.screen(n = )
close.screen(n, all.screens = FALSE)
}
\alias{screen}
\alias{split.screen}
\alias{erase.screen}
\alias{close.screen}
\arguments{
  \item{figs}{A two-element vector describing the number of rows and the
    number of columns in a screen matrix \emph{or} a matrix with 4 columns.
    If a matrix, then each row describes a screen with values for the left,
    right, bottom, and top of the screen (in that order) in NDC units.}
  \item{screen}{A number giving the screen to be split.}
  \item{erase}{logical: should be selected screen be cleared?}
  \item{n}{A number indicating which screen to prepare for drawing
    (\code{screen}), erase (\code{erase.screen}), or close
    (\code{close.screen}).}
  \item{new}{A logical value indicating whether the screen should be
    erased as part of the preparation for drawing in the screen.}
  \item{all.screens}{A logical value indicating whether all of the
    screens should be closed.}
}
\description{
  \code{split.screen} defines a number of regions within the current
  device which can, to some extent, be treated as separate graphics
  devices.  It is useful for generating multiple plots on a single
  device.  Screens can themselves be split, allowing for quite complex
  arrangements of plots.

  \code{screen} is used to select which screen to draw in.

  \code{erase.screen} is used to clear a single screen, which it
  does by filling with the background colour.

  \code{close.screen} removes the specified screen definition(s).
}
\details{
  The first call to \code{split.screen} places \R into split-screen
  mode.  The other split-screen functions only work within this mode.
  While in this mode, certain other commands should be avoided (see WARNINGS
  below).  Split-screen mode is exited by the command
  \code{close.screen(all = TRUE)}
}
\value{
  \code{split.screen} returns a vector of screen numbers for the
  newly-created screens.  With no arguments, \code{split.screen} returns
  a vector of valid screen numbers.

  \code{screen} invisibly returns the number of the selected screen.
  With no arguments, \code{screen} returns the number of the current
  screen.

  \code{close.screen} returns a vector of valid screen numbers.

  \code{screen}, \code{erase.screen}, and \code{close.screen} all return
  \code{FALSE} if \R is not in split-screen mode.
}

\section{Warning}{
  The recommended way to use these functions is to
  completely draw a plot and all
  additions (ie. points and lines) to the base plot, prior to selecting
  and plotting on another screen. The behavior associated with returning
  to a screen to add to an existing plot is unpredictable and may result
  in problems that are not readily visible.

  These functions are totally incompatible with the
  other mechanisms for arranging plots on a device:  \code{par(mfrow)},
  \code{par(mfcol)}, and \code{layout()}.

  The functions are also incompatible with some plotting functions,
  such as \code{coplot}, which make use of these other mechanisms.

  The functions should not be used with multiple devices.

  \code{erase.screen} will appear not to work if the background colour
  is transparent (as it is by default on most devices).
}

\seealso{
  \code{\link{par}}, \code{\link{layout}}, \code{\link{Devices}},
  \code{dev.*}
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S}.
  Wadsworth \& Brooks/Cole.
}

\examples{
if (interactive()) {
par(bg = "white")           # default is likely to be transparent
split.screen(c(2,1))        # split display into two screens
split.screen(c(1,3), screen = 2) # now split the bottom half into 3
screen(1) # prepare screen 1 for output
plot(10:1)
screen(4) # prepare screen 4 for output
plot(10:1)
close.screen(all = TRUE)    # exit split-screen mode

split.screen(c(2,1))        # split display into two screens
split.screen(c(1,2),2)      # split bottom half in two
plot(1:10)                  # screen 3 is active, draw plot
erase.screen()              # forgot label, erase and redraw
plot(1:10, ylab= "ylab 3")
screen(1)                   # prepare screen 1 for output
plot(1:10)
screen(4)                   # prepare screen 4 for output
plot(1:10, ylab="ylab 4")
screen(1, FALSE)            # return to screen 1, but do not clear
plot(10:1, axes=FALSE, lty=2, ylab="")  # overlay second plot
axis(4)                     # add tic marks to right-hand axis
title("Plot 1")
close.screen(all = TRUE)    # exit split-screen mode
}
}
\keyword{aplot}
\keyword{dplot}
\keyword{device}
\eof
\name{sd}
\alias{sd}
\title{Standard Deviation}
\description{
  This function computes the standard deviation of the values in
  \code{x}.
  If \code{na.rm} is \code{TRUE} then missing values are removed before
  computation proceeds.
  If \code{x} is a matrix or a data frame, a vector of the standard
  deviation of the columns is returned.
}
\usage{
sd(x, na.rm = FALSE)
}
\arguments{
  \item{x}{a numeric vector, matrix or data frame.}
  \item{na.rm}{logical. Should missing values be removed?}
}
\seealso{
  \code{\link{var}} for its square, and \code{\link{mad}}, the most
  robust alternative.
}
\examples{
sd(1:2) ^ 2
}
\keyword{univar}
\eof
\name{se.aov}
\alias{se.aov}
\alias{se.aovlist}
\title{Internal Functions Used by model.tables}
\usage{
se.aov(object, n, type = "means")
se.aovlist(object, dn.proj, dn.strata, factors, mf, efficiency,
           n, type = "diff.means", \dots)
}
\description{
  Internal function for use by \code{\link{model.tables}}.
}
\seealso{\code{\link{model.tables}}}

\keyword{internal}
\eof
\name{se.contrast}
\alias{se.contrast}
\alias{se.contrast.aov}
\alias{se.contrast.aovlist}
\title{Standard Errors for Contrasts in Model Terms}
\usage{
se.contrast(object, \dots)
\method{se.contrast}{aov}(object, contrast.obj,
           coef = contr.helmert(ncol(contrast))[, 1],
           data = NULL, \dots)
}
\arguments{
 \item{object}{A suitable fit, usually from \code{aov}.}
 \item{contrast.obj}{The contrasts for which standard errors are
   requested.  This can be specified via a list or via a matrix.  A
   single contrast can be specified by a list of logical vectors giving
   the cells to be contrasted.  Multiple contrasts should be specified
   by a matrix, each column of which is a numerical contrast vector
   (summing to zero).
   }
 \item{coef}{used when \code{contrast.obj} is a list; it should be a
   vector of the same length as the list with zero sum.  The default
   value is the first Helmert contrast, which contrasts the first and
   second cell means specified by the list.}
 \item{data}{The data frame used to evaluate \code{contrast.obj}.}
 \item{\dots}{further arguments passed to or from other methods.}
}
\description{
  Returns the standard errors for one or more contrasts in an \code{aov}
  object.
}
\details{
  Contrasts are usually used to test if certain means are
  significantly different; it can be easier to use \code{se.contrast}
  than compute them directly from the coefficients.

  In multistratum models, the contrasts can appear in more than one
  stratum; the contrast and standard error are computed in the lowest
  stratum and adjusted for efficiencies and comparisons between strata.

  Suitable matrices for use with \code{coef} can be found by
  calling \code{\link{contrasts}} and indexing the columns by a factor.
}
 \value{
  A vector giving the standard errors for each contrast.
}

\seealso{
  \code{\link{contrasts}},
  \code{\link{model.tables}}
}
\examples{
## From Venables and Ripley (2002) p.165.
N <- c(0,1,0,1,1,1,0,0,0,1,1,0,1,1,0,0,1,0,1,0,1,1,0,0)
P <- c(1,1,0,0,0,1,0,1,1,1,0,0,0,1,0,1,1,0,0,1,0,1,1,0)
K <- c(1,0,0,1,0,1,1,0,0,1,0,1,0,1,1,0,0,0,1,1,1,0,1,0)
yield <- c(49.5,62.8,46.8,57.0,59.8,58.5,55.5,56.0,62.8,55.8,69.5,
55.0, 62.0,48.8,45.5,44.2,52.0,51.5,49.8,48.8,57.2,59.0,53.2,56.0)

npk <- data.frame(block = gl(6,4), N = factor(N), P = factor(P),
                  K = factor(K), yield = yield)
options(contrasts=c("contr.treatment", "contr.poly"))
npk.aov1 <- aov(yield ~ block + N + K, npk)
se.contrast(npk.aov1, list(N=="0", N=="1"), data=npk)
# or via a matrix
cont <- matrix(c(-1,1), 2, 1, dimnames=list(NULL, "N"))
se.contrast(npk.aov1, cont[N, , drop=FALSE]/12, data=npk)

## test a multi-stratum model
npk.aov2 <- aov(yield ~ N + K + Error(block/(N + K)), npk)
se.contrast(npk.aov2, list(N == "0", N == "1"))
}
\keyword{models}
\eof
\name{search}
\title{Give Search Path for R Objects}
\usage{
search()
searchpaths()
}
\alias{search}
\alias{searchpaths}
\description{
  Gives a list of \code{\link{attach}}ed \emph{packages}
  (see \code{\link{library}}), and \R objects, usually
  \code{\link{data.frame}s}.
}
\value{
  A character vector, starting with \code{"\link{.GlobalEnv}"}, and
  ending with \code{"package:base"} which is \R's \pkg{base} package
  required always.

  \code{searchpaths} gives a similar character vector, with the
  entries for packages being the path to the package used to load the
  code.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole. (\code{search}.)

  Chambers, J. M. (1998)
  \emph{Programming with Data. A Guide to the S Language}.
  Springer. (\code{searchPaths}.)
}
\seealso{\code{\link{attach}} and \code{\link{detach}} to change the
  search \dQuote{path}, \code{\link{objects}} to find \R objects in there.
}
\examples{
search()
searchpaths()
}
\keyword{data}

\eof
\name{seek}
\alias{seek}
\alias{seek.connection}
\alias{truncate}
\alias{truncate.connection}
\alias{isSeekable}
\title{Functions to Reposition Connections}
\description{
  Functions to re-position connections.
}
\usage{
seek(con, \dots)
\method{seek}{connection}(con, where = NA, origin = "start", rw = "", \dots)

isSeekable(con)

truncate(con, \dots)
}
\arguments{
  \item{con}{a connection.}
  \item{where}{integer.  A file position (relative to the origin
    specified by \code{origin}), or \code{NA}.}
  \item{rw}{character.  Empty or \code{"read"} or \code{"write"},
    partial matches allowed.}
  \item{origin}{character.  One of \code{"start"}, \code{"current"},
    \code{"end"}.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\details{
  \code{seek} with \code{where = NA} returns the current byte offset
  of a connection (from the beginning), and with a non-missing \code{where}
  argument the connection is re-positioned (if possible) to the
  specified position. \code{isSeekable} returns whether the connection
  in principle supports \code{seek}: currently only (possibly
  compressed) file connections do.
#ifdef windows
  The value returned by \code{seek(where=NA)} appears to be unreliable
  on Windows systems, at least for text files.  Clipboard connections
  can seek too.
#endif
  
  File connections can be open for both writing/appending, in which case
  \R keeps separate positions for reading and writing. Which \code{seek}
  refers to can be set by its \code{rw} argument: the default is the
  last mode (reading or writing) which was used.  Most files are
  only opened for reading or writing and so default to that state.
  If a file is open for reading and writing but has not been used, the
  default is to give the reading position (0).

  The initial file position for reading is always at the beginning.
  The initial position for writing is at the beginning of the file
  for modes \code{"r+"} and \code{"r+b"}, otherwise at the end of the
  file.  Some platforms only allow writing at the end of the file in
  the append modes.

  \code{truncate} truncates a file opened for writing at its current
  position.  It works only for \code{file} connections, and is not
  implemented on all platforms.
}
\value{
  \code{seek} returns the current position (before any move),
  as a byte offset, if relevant, or \code{0} if not.

  \code{truncate} returns \code{NULL}: it stops with an error if
  it fails (or is not implemented).

  \code{isSeekable} returns a logical value, whether the connection is
  support \code{seek}.
}
\seealso{
  \code{\link{connections}}
}
\keyword{file}
\keyword{connection}
\eof
\name{segments}
\alias{segments}
\title{Add Line Segments to a Plot}
\description{
  Draw line segments between pairs of points.
}
\usage{
segments(x0, y0, x1, y1,
       col = par("fg"), lty = par("lty"), lwd = par("lwd"), \dots)
}
\arguments{
  \item{x0,y0}{coordinates of points \bold{from} which to draw.}
  \item{x1,y1}{coordinates of points \bold{to} which to draw.}
  \item{col, lty, lwd}{usual graphical parameters as in
    \code{\link{par}}.}
  \item{\dots}{further graphical parameters (from \code{\link{par}}).}
}
\details{
  For each \code{i}, a line segment is drawn between the point
  \code{(x0[i], y0[i])} and the point \code{(x1[i],y1[i])}.

  The graphical parameters \code{col} and \code{lty} can be used to
  specify a color and line texture for the line segments (\code{col}
  may be a vector).
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{arrows}}, 
  \code{\link{polygon}} for slightly easier and less flexible line
  drawing, and
  \code{\link{lines}} for the usual polygons.
}
\examples{
x <- runif(12); y <- rnorm(12)
i <- order(x,y); x <- x[i]; y <- y[i]
plot(x,y, main="arrows(.) and segments(.)")
## draw arrows from point to point :
s <- seq(length(x)-1)# one shorter than data
arrows(x[s], y[s], x[s+1], y[s+1], col= 1:3)
s <- s[-length(s)]
segments(x[s], y[s], x[s+2], y[s+2], col= 'pink')
}
\keyword{aplot}
\eof
\name{seq.POSIXt}
\alias{seq.POSIXt}
\title{Generate Regular Sequences of Dates}
\description{
  The method for \code{\link{seq}} for data-time classes.
}
\usage{
\method{seq}{POSIXt}(from, to, by, length.out=NULL, along.with=NULL, \dots)
}
\arguments{
  \item{from}{starting date. Required}
  \item{to}{end date. Optional. If supplied must be after \code{from}.}
  \item{by}{increment of the sequence. Optional. See Details.}
  \item{length.out}{integer, optional. desired length of the sequence.}
  \item{along.with}{take the length from the length of this argument.}
  \item{\dots}{arguments passed to or from other methods.}
}
\details{
  \code{by} can be specified in several ways.
  \itemize{
    \item A number, taken to be in seconds.
    \item A object of class \code{\link{difftime}}
    \item A character string, containing one of \code{"sec"},
    \code{"min"}, \code{"hour"}, \code{"day"}, \code{"DSTday"},
    \code{"week"}, \code{"month"} or \code{"year"}.  This can optionally be
    preceded by an integer and a space, or followed by \code{"s"}.
  }
  The difference between \code{"day"} and \code{"DSTday"} is that the
  former ignores changes to/from daylight savings time and the latter takes
  the same clock time each day.  (\code{"week"} ignores DST, but
  \code{"7 DSTdays"}) can be used as an alternative.  \code{"month"} and
  \code{"year"} allow for DST as from \R 1.5.0.)
}
\value{
  A vector of class \code{"POSIXct"}.
}
\seealso{\code{\link{DateTimeClasses}}}

\examples{
## first days of years
seq(ISOdate(1910,1,1), ISOdate(1999,1,1), "years")
## by month
seq(ISOdate(2000,1,1), by="month", length=12)
## quarters
seq(ISOdate(1990,1,1), ISOdate(2000,1,1), by="3 months")
## days vs DSTdays
seq(ISOdate(2000,3,20), by="day", length = 10)
seq(ISOdate(2000,3,20), by="DSTday", length = 10)
seq(ISOdate(2000,3,20), by="7 DSTdays", length = 4)
}
\keyword{manip}
\keyword{chron}
\eof
\name{seq}
\title{Sequence Generation}
\alias{seq}
\alias{seq.default}
\alias{:}
\description{
  Generate regular sequences.
}
\synopsis{
seq(...)
seq.default(from = 1, to = 1, by = ((to - from)/(length.out - 1)),
            length.out = NULL, along.with = NULL, ...)
}
\usage{
from:to
seq(from, to)
seq(from, to, by=)
seq(from, to, length=)
seq(along)
}
\arguments{
  \item{from}{starting value of sequence.}
  \item{to}{(maximal) end value of the sequence.}
  \item{by}{increment of the sequence.}
  \item{length}{desired length of the sequence.}
  \item{along}{take the length from the length of this argument.}
}
\details{
  The interpretation of the unnamed arguments of \code{seq} is
  \emph{not} standard, and it is recommended to always name the
  arguments when programming.
 
  The operator \code{:} and the first \code{seq(.)} form generate the
  sequence \code{from, from+1}, \ldots, \code{to}.
  \code{seq} is a generic function.

  The second form generates \code{from, from+by}, \ldots, \code{to}.

  The third generates a sequence of \code{length} equally spaced values
  from \code{from} to \code{to}.

  The last generates the sequence \code{1, 2}, \ldots,
  \code{length(along)}, unless the argument is of length 1 when it is
  interpreted as a \code{length} argument.

  If \code{from} and \code{to} are factors of the same length, then
  \code{from : to} returns the \dQuote{cross} of the two.

  Very small sequences (with \code{from - to} of the order of 1e-14
  times the larger of the ends) will return \code{from}.
}
\value{
  The result is of \code{mode} \code{"integer"} if \code{from} is
  (numerically equal to an) integer and \code{by} is not specified.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{rep}},
  \code{\link{sequence}},
  \code{\link{row}},
  \code{\link{col}}.
}
\examples{
1:4
pi:6 # float
6:pi # integer

seq(0,1, length=11)
str(seq(rnorm(20)))
seq(1,9, by = 2) # match
seq(1,9, by = pi)# stay below
seq(1,6, by = 3)
seq(1.575, 5.125, by=0.05)
seq(17) # same as 1:17

for (x in list(NULL, letters[1:6], list(1,pi)))
  cat("x=",deparse(x),";  seq(along = x):",seq(along = x),"\n")

f1 <- gl(2,3); f1
f2 <- gl(3,2); f2
f1:f2 # a factor, the "cross"  f1 x f2
}
\keyword{manip}
\eof
\name{sequence}
\title{Create A Vector of Sequences}
\usage{
sequence(nvec)
}
\alias{sequence}
\arguments{
\item{nvec}{an integer vector each element of which specifies the upper
bound of a sequence.}
}
\description{
For each element of \code{nvec} the sequence \code{seq(nvec[i])}
is created. These are appended and the result returned.
}
\seealso{
\code{\link{gl}}, \code{\link{seq}}, \code{\link{rep}}.
}
\examples{
sequence(c(3,2))# the concatenated sequences 1:3 and 1:2.
#> [1] 1 2 3 1 2
}
\keyword{manip}
\eof
\name{serialize}
\alias{.readRDS}
\alias{.saveRDS}
\alias{serialize}
\alias{unserialize}
\title{Simple Serialization Interface}
\description{
  A simple low level interface for serializing to connections.
}
\usage{
serialize(object, connection, ascii = FALSE, refhook = NULL)
unserialize(connection, refhook = NULL)
.saveRDS(object, file = "", ascii = FALSE, version = NULL,
         compress = FALSE, refhook = NULL)
.readRDS(file, refhook = NULL)
}
\arguments{
  \item{object}{\R object to serialize.}
  \item{file}{a connection or the name of the file where the R object
    is saved to or read from.}
  \item{ascii}{a logical.  If \code{TRUE}, an ASCII representation is
    written; otherwise (default), a more compact binary one is used.}
  \item{version}{the workspace format version to use.  \code{NULL}
    specifies the current default format.  The version used from \R
    0.99.0 to \R 1.3.1 was version 1.  The default format as from \R
    1.4.0 is version 2.}
  \item{compress}{a logical specifying whether saving to a named file is
    to use compression.  Ignored when \code{file} is a connection and for
    workspace format version 1.}
  \item{connection}{an open connection.}
  \item{refhook}{a hook function for handling reference objects.}
}
\details{
  The function \code{serialize} writes \code{object} to the specified
  connection.  Sharing of reference objects is preserved within the
  object but not across separate calls to serialize.  If
  \code{connection} is \code{NULL} then \code{object} is serialized to a
  scaler string, which is returned as the result of \code{serialize}.
  For a text mode connection, the default value of \code{ascii} is set
  to \code{TRUE}.

  \code{unserialize} reads an object from \code{connection}.
  \code{connection} may also be a scaler string.

  The \code{refhook} functions can be used to customize handling of
  non-system reference objects (all external pointers and weak
  references, and all environments other than name space and package
  environments and \code{.GlobalEnv}).  The hook function for
  \code{serialize} should return a character vector for references it
  wants to handle; otherwise it should return \code{NULL}.  The hook for
  \code{unserialize} will be called with character vectors supplied to
  \code{serialize} and should return an appropriate object.
}
\section{Warning}{
  These functions are still experimental.  Both names, interfaces and
  values might change in future versions.  \code{.saveRDS} and
  \code{.readRDS} are intended for internal use.
}
\examples{
x<-serialize(list(1,2,3),NULL)
unserialize(x)
}
\keyword{internal}
\keyword{file}
\eof
\name{sets}
\alias{union}
\alias{intersect}
\alias{setdiff}
\alias{is.element}
\alias{setequal}
\title{Set Operations}
\usage{
union(x, y)
intersect(x, y)
setdiff(x, y)
setequal(x, y)
is.element(el, set)
}
\arguments{
  \item{x, y, el, set}{vectors (of the same mode) containing a sequence
    of items (conceptually) with no duplicated values.}
}
\description{
  Performs \bold{set} union, intersection, (asymmetric!) difference,
  equality and membership on two vectors.
}
\details{
  Each of \code{union}, \code{intersect} and \code{setdiff} will remove
  any duplicated values in the arguments.

  \code{is.element(x, y)} is identical to \code{x \%in\% y}.
}
\value{
  A vector of the same \code{\link{mode}} as \code{x} or \code{y} for
  \code{setdiff} and \code{intersect}, respectively, and
  of a common mode for \code{union}.

  A logical scalar for \code{setequal} and a logical of the same
  length as \code{x} for \code{is.element}.
}
\seealso{\code{\link{\%in\%}}}

\examples{
(x <- c(sort(sample(1:20, 9)),NA))
(y <- c(sort(sample(3:23, 7)),NA))
union(x, y)
intersect(x, y)
setdiff(x, y)
setdiff(y, x)
setequal(x, y)

## True for all possible x & y :
setequal( union(x,y),
          c(setdiff(x,y), intersect(x,y), setdiff(y,x)))

is.element(x, y)# length 10
is.element(y, x)# length  8
}
\keyword{misc}
\eof
\name{showConnections}
\alias{showConnections}
\alias{getConnection}
\alias{getAllConnections}
\alias{closeAllConnections}
\alias{stdin}
\alias{stdout}
\alias{stderr}
\title{Display Connections}
\description{
  Display aspects of connections.
}
\usage{
showConnections(all=FALSE)
getConnection(what)
closeAllConnections()

stdin()
stdout()
stderr()
}
\arguments{
  \item{all}{logical: if true all connections, including closed ones
    and the standard ones are displayed. If false only open user-created
    connections are included.}

  \item{what}{integer: a row number of the table given by
    \code{showConnections}.}
}
\details{
  \code{stdin()}, \code{stdout()} and \code{stderr()} are standard
  connections corresponding to input, output and error on the console
  respectively (and not necessarily to file streams).  They are text-mode
  connections of class \code{"terminal"} which cannot be opened or
  closed, and are read-only, write-only and write-only respectively.
  The \code{stdout()} and \code{stderr()} connections can be
  re-directed by \code{\link{sink}}.

  \code{showConnections} returns a matrix of information.  If a
  connection object has been lost or forgotten, \code{getConnection}
  will take a row number from the table and return a connection object
  for that connection, which can be used to close the connection,
  for example.

  \code{closeAllConnections} closes (and destroys) all open user
  connections, restoring all \code{\link{sink}} diversions as it does so.
}
\value{
  \code{stdin()}, \code{stdout()} and \code{stderr()} return connection
  objects.

  \code{showConnections} returns a character matrix of information with
  a row for each connection, by default only for open non-standard connections.

  \code{getConnection} returns a connection object, or \code{NULL}.
}
\seealso{\code{\link{connections}}}

\examples{
showConnections(all = TRUE)

textConnection(letters)
# oops, I forgot to record that one
showConnections()
#  class     description      mode text   isopen   can read can write
#3 "letters" "textConnection" "r"  "text" "opened" "yes"    "no"     
\dontrun{close(getConnection(3))}
\dontshow{r <- as.numeric(row.names(showConnections()))
close(getConnection(r))}
showConnections()
}
\keyword{connection}
\eof
\name{sign}
\title{Sign Function}
\usage{
sign(x)
}
\alias{sign}
\arguments{
  \item{x}{a numeric vector}
}
\description{
  \code{sign} returns a vector with the signs of the corresponding
  elements of \code{x} (the sign of a real number is 1, 0, or \eqn{-1}
  if the number is positive, zero, or negative, respectively).

  Note that \code{sign} does not operate on complex vectors.
}
\seealso{
  \code{\link{abs}}
}
\examples{
sign(pi) # == 1
sign(-2:3)# -1 -1 0 1 1 1
}
\keyword{arith}

\eof
\name{sink}
\alias{sink}
\alias{sink.number}
\title{Send R Output to a File}
\usage{
sink(file = NULL, append = FALSE, type = c("output", "message"))
sink.number(type = c("output", "message"))
}
\arguments{
  \item{file}{a connection or a character string naming the
    file to write to, or \code{NULL} to stop sink-ing.}
  \item{append}{logical. If \code{TRUE}, output will be appended to
    \code{file}; otherwise, it will overwrite the contents of
    \code{file}.}
  \item{type}{character. Either the output stream or the messages stream.}
}
\description{
  \code{sink} diverts \R output to a connection.

  \code{sink.number()} reports how many diversions are in use.

  \code{sink.number(type = "message")} reports the number of the
  connection currently being used for error messages.
}
\details{
  \code{sink} diverts \R output to a connection. If \code{file} is a
  character string, a file connection with that name will be established
  for the duration of the diversion.

  Normal \R output is diverted by the default \code{type = "output"}.
  Only prompts and warning/error messages continue to appear on the terminal.
  The latter can diverted by \code{type = "message"} (see below).

  \code{sink()} or \code{sink(file=NULL)} ends the last diversion (of
  the specified type).  As from \R version 1.3.0 there is a stack of
  diversions for normal output, so output reverts to the previous
  diversion (if there was one).  The stack is of up to 21 connections
  (20 diversions).

  If \code{file} is a connection if will be opened if necessary.

  Sink-ing the messages stream should be done only with great care.
  For that stream \code{file} must be an already open connection, and
  there is no stack of connections.
}
\value{
  For \code{sink}.

  For \code{sink.number()} the number (0, 1, 2, \dots) of diversions of
  output in place.

  For \code{sink.number("message")} the connection number used for
  messages, 2 if no diversion has been used.
}
\section{Warning}{
  Don't use a connection that is open for \code{sink} for any other
  purpose.  The software will stop you closing one such inadvertently.

  Do not sink the messages stream unless you understand the source code
  implementing it and hence the pitfalls.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Chambers, J. M. (1998)
  \emph{Programming with Data. A Guide to the S Language}.
  Springer.
}
\seealso{\code{\link{capture.output}}}
\examples{
sink("sink-examp.txt")
i <- 1:10
outer(i, i, "*")
sink()
unlink("sink-examp.txt")
\dontrun{
## capture all the output to a file.
zz <- file("all.Rout", open="wt")
sink(zz)
sink(zz, type="message")
try(log("a"))
## back to the console
sink(type="message")
sink()
try(log("a"))
}}
\keyword{file}
\keyword{connection}
\eof
\name{sleep}
\docType{data}
\alias{sleep}
\title{Student's Sleep Data}
\description{
  Data which show the effect of two soporific drugs (increase in hours
  of sleep) on groups consisting of 10 patients each.
}
\usage{data(sleep)}
\format{
  A data frame with 20 observations on 2 variables.
  \tabular{rlll}{
    [, 1] \tab extra \tab numeric \tab increase in hours of sleep\cr
    [, 2] \tab group \tab factor  \tab patient group
  }
}
\source{
  Student (1908)
  The probable error of the mean.
  \emph{Biometrika}, \bold{6}, 20.
}
\references{
  Scheffé, Henry (1959)
  \emph{The Analysis of Variance}.
  New York, NY: Wiley.
}
\examples{
data(sleep)
## ANOVA
anova(lm(extra ~ group, data = sleep))
}
\keyword{datasets}
\eof
\name{slice.index}
\alias{slice.index}
\title{Slice Indexes in an Array}
\description{
  Returns a matrix of integers indicating the number of their slice in a
  given array.
}
\usage{
slice.index(x, MARGIN)
}
\arguments{
  \item{x}{an array.  If \code{x} has no dimensiion attribute, it is
    considered a one-dimensional array.}
  \item{MARGIN}{an integer giving the dimension number to slice by.}
}
\value{
  An integer array \code{y} with dimensions corresponding to those of
  \code{x} such that all elements of slice number \code{i} with respect
  to dimension \code{MARGIN} have value \code{i}.
}
\seealso{
  \code{\link{row}} and \code{\link{col}} for determining row and column
  indexes; in fact, these are special cases of \code{slice.index}
  corresponding to \code{MARGIN} equal to 1 and 2, respectively.
}
\examples{
x <- array(1 : 24, c(2, 3, 4))
slice.index(x, 2)
}
\keyword{array}
\eof
\name{slotOp}
\title{Extract Slots}
\alias{@}
\description{
  Extract tbe contents of a slot in a object with a formal class
  structure.
}
\usage{
object@name
}
\arguments{
  \item{object}{An object from a formally defined class.}
  \item{name}{The character-string name of the slot.}
}
\details{
  These operators support the formal classes of package \pkg{methods}.
  See \code{\link[methods]{slot}} for further details.
  Currently there is no checking that the object is an instance of a
  class.
}
\seealso{
  \code{\link{Extract}},
  \code{\link[methods]{slot}}
}
\keyword{manip}
\eof
\name{socketSelect}
\alias{socketSelect}
\title{Wait on Socket Connections}
\usage{
socketSelect(socklist, write = FALSE, timeout = NULL)
}
\arguments{
  \item{socklist}{list of open socket connections}
  \item{write}{logical. If \code{TRUE} wait for corresponding socket to
               become available for writing; otherwise wait for it to become
               available for reading.}
  \item{timeout}{numeric or \code{NULL}. Time in seconds to wait for a
                 socket to become available; \code{NULL} means wait
                 indefinitely.}
}
\description{
  Waits for the first of several socket connections to become available.  
}
\value{Logical the same length as \code{socklist} indicating
  whether the corresponding socket connection is available for
  output or input, depending on the corresponding value of \code{write}.
}
\details{
  The values in \code{write} are recycled if necessary to make up a
  logical vector the same length as \code{socklist}. Socket connections
  can appear more than once in \code{socklist}; this can be useful if
  you want to determine whether a socket is available for reading or
  writing.
}
\examples{
\dontrun{
## test whether socket connection s is available for writing or reading
socketSelect(list(s,s),c(TRUE,FALSE),timeout=0)
}
}
\keyword{connection}
\eof
\name{solve}
\title{Solve a System of Equations}
\usage{
solve(a, b, \dots)

\method{solve}{default}(a, b, tol = 1e-7, LINPACK = FALSE, \dots)
}
\alias{solve}
\alias{solve.default}
\arguments{
  \item{a}{a square numeric or complex matrix containing the coefficients of
    the linear system.}
  \item{b}{a numeric or complex vector or matrix giving the right-hand
    side(s) of the linear system.  If missing, \code{b} is taken to be
    an identity matrix and \code{solve} will return the inverse of \code{a}.}
  \item{tol}{the tolerance for detecting linear dependencies in the
    columns of \code{a}, if LINPACK is used.}
  \item{LINPACK}{logical. Should LINPACK be used (for compatibility with
    \R < 1.7.0)?}
  \item{\dots}{further arguments passed to or from other methods}
}
\description{
  This generic function solves the equation \code{a \%*\% x = b} for \code{x},
  where \code{b} can be either a vector or a matrix.
}
\details{
  As from \R 1.3.0, \code{a} or \code{b} can be complex, in
  which case LAPACK routine \code{ZESV} is used.
  This uses double complex arithmetic which might not be available on all
  platforms.

  The row and column names of the result are taken from the column
  names of \code{a} and of \code{b} respectively.  As from \R 1.7.0
  if \code{b} is missing the column names of the result are the row
  names of \code{a}.  No check is made that the column names of \code{a}
  and the row names of \code{b} are equal.

  For back-compatibility \code{a} can be a (real) QR decomposition,
  although \code{\link{qr.solve}} should be called in that case.
  \code{\link{qr.solve}} can handle non-square systems.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{solve.qr}} for the \code{qr} method,
  \code{\link{backsolve}}, \code{\link{qr.solve}}.
}
\examples{
hilbert <- function(n) { i <- 1:n; 1 / outer(i - 1, i, "+") }
h8 <- hilbert(8); h8
sh8 <- solve(h8)
round(sh8 \%*\% h8, 3)

A <- hilbert(4)
A[] <- as.complex(A)
## might not be supported on all platforms
try(solve(A))
}
\keyword{algebra}
\eof
\name{sort}
\alias{sort}
\alias{is.unsorted}
\title{Sorting or Ordering Vectors}
\description{
  Sort (or \emph{order}) a numeric or complex vector (partially) into
  ascending (or descending) order.
}
\usage{
sort(x, partial = NULL, na.last = NA, decreasing = FALSE,
     method = c("shell", "quick"), index.return = FALSE)
is.unsorted(x, na.rm = FALSE)
}
\arguments{
  \item{x}{a numeric or complex vector.}
  \item{partial}{a vector of indices for partial sorting.}
  \item{na.last}{for controlling the treatment of \code{NA}s.
    If \code{TRUE}, missing values in the data are put last; if
    \code{FALSE}, they are put first; if \code{NA}, they are removed.}
  \item{decreasing}{logical.  Should the sort be increasing or decreasing?}
  \item{method}{character specifying the algorithm used.}
  \item{index.return}{logical indicating if the ordering index vector should
    be returned as well; this is only available for the default
  \code{na.last = NA}.}
  \item{na.rm}{logical.  Should missing values be removed?}
}
\details{
  If \code{partial} is not \code{NULL}, it is taken to contain indices
  of elements of \code{x} which are to be placed in their correct
  positions by partial sorting.  After the sort, the values specified in
  \code{partial} are in their correct position in the sorted array.  Any
  values smaller than these values are guaranteed to have a smaller
  index in the sorted array and any values which are greater are
  guaranteed to have a bigger index in the sorted array.

  The sort order for character vectors will depend on the collating
  sequence of the locale in use: see \code{\link{Comparison}}.

  \code{is.unsorted} returns a logical indicating if \code{x} is sorted
  increasingly, i.e., \code{is.unsorted(x)} is true if \code{any(x !=
    sort(x))} (and there are no \code{NA}s).

  \code{method = "shell"} uses Shellsort (an \eqn{O(n^{4/3})} variant
  from Sedgewick (1996)).  If \code{x} has names a stable sort is used,
  so ties are not reordered.  (This only matters if names are present.)

  Method \code{"quick"} uses Singleton's Quicksort implementation and is
  only available when \code{x} is numeric (double or integer) and
  \code{partial} is \code{NULL}.  It is normally somewhat faster than
  Shellsort (perhaps twice as fast on vectors of length a million) but
  has poor performance in the rare worst case.
  (Peto's modification using a pseudo-random midpoint is used to make
  the worst case rarer.)  This is not a stable sort, and ties may be
  reordered.
}
\value{
  For \code{sort} the sorted vector unless
  \code{index.return} is true, when the result is
  a list with components named \code{x} and \code{ix} containing the
  sorted numbers and the ordering index vector.  In the latter case,
  if \code{method == "quick"} ties may be reversed in the ordering,
  unlike \code{sort.list}, as quicksort is not stable.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Sedgewick, R. (1986)
  A new upper bound for Shell sort.
  \emph{J. Algorithms} \bold{7}, 159--173.

  Singleton, R. C. (1969) An efficient algorithm for sorting with
  minimal storage: Algorithm 347.
  \emph{Communications of the ACM} \bold{12}, 185--187.
}
\seealso{
  \code{\link{order}}, \code{\link{rank}}.
}
\examples{
data(swiss)
x <- swiss$Education[1:25]
x; sort(x); sort(x, partial = c(10, 15))
median # shows you another example for 'partial'

## illustrate 'stable' sorting (of ties):
sort(c(10:3,2:12), method = "sh", index=TRUE) # is stable
## $x : 2  3  3  4  4  5  5  6  6  7  7  8  8  9  9 10 10 11 12
## $ix: 9  8 10  7 11  6 12  5 13  4 14  3 15  2 16  1 17 18 19
sort(c(10:3,2:12), method = "qu", index=TRUE) # is not
## $x : 2  3  3  4  4  5  5  6  6  7  7  8  8  9  9 10 10 11 12
## $ix: 9 10  8  7 11  6 12  5 13  4 14  3 15 16  2 17  1 18 19
##        ^^^^^

\dontrun{## Small speed comparison simulation:
N <- 2000
Sim <- 20
rep <- 50 # << adjust to your CPU
c1 <- c2 <- numeric(Sim)
for(is in 1:Sim){
  x <- rnorm(N)
  gc()  ## sort should not have to pay for gc
  c1[is] <- system.time(for(i in 1:rep) sort(x, method = "shell"))[1]
  c2[is] <- system.time(for(i in 1:rep) sort(x, method = "quick"))[1]
  stopifnot(sort(x, meth = "s") == sort(x, meth = "q"))
}
100 * rbind(ShellSort = c1, QuickSort = c2)
cat("Speedup factor of quick sort():\n")
summary({qq <- c1 / c2; qq[is.finite(qq)]})

## A larger test
x <- rnorm(1e6)
gc()
system.time(x1 <- sort(x, method = "shell"))
gc()
system.time(x2 <- sort(x, method = "quick"))
stopifnot(identical(x1, x2))
}}
\keyword{univar}
\keyword{manip}
\keyword{arith}
\eof
\name{source}
\title{Read R Code from a File or a Connection}
\usage{
source(file, local = FALSE, echo = verbose, print.eval = echo,
       verbose = getOption("verbose"),  prompt.echo = getOption("prompt"),
       max.deparse.length = 150, chdir = FALSE)
}
\alias{source}
\arguments{
  \item{file}{a connection or a character string giving the name
    of the file or URL to read from.}
  \item{local}{if \code{local} is \code{FALSE}, the statements scanned
    are evaluated in the user's workspace (the global environment),
    otherwise in the environment calling \code{source}.}
  \item{echo}{logical; if \code{TRUE}, each expression is printed
    after parsing, before evaluation.}
  \item{print.eval}{logical; if \code{TRUE}, the result of
    \code{eval(i)} is printed for each expression \code{i}; defaults
    to \code{echo}.}
  \item{verbose}{if \code{TRUE}, more diagnostics (than just
    \code{echo = TRUE}) are printed during parsing and evaluation of
    input, including extra info for \bold{each} expression.}
  \item{prompt.echo}{character; gives the prompt to be used if
    \code{echo = TRUE}.}
  \item{max.deparse.length}{integer; is used only if \code{echo} is
    \code{TRUE} and gives the maximal length of the \dQuote{echo} of a
    single expression.}
  \item{chdir}{logical; if \code{TRUE}, the R working directory is
    changed to the directory containing \code{file} for evaluating.}
}
\description{
  \code{source} causes \R to accept its input from the named file (the
  name must be quoted). Input is read from that file until the end of
  the file is reached.   \code{\link{parse}} is used to scan the
  expressions in, they are then evaluated sequentially in the chosen
  environment.
}
\details{
  All versions of \R accept input from a connection with end of line
  marked by LF (as used on Unix), CRLF (as used on DOS/Windows)
  or CR (as used on Mac).  The final line can be incomplete, that
  is missing the final EOL marker.

  If \code{\link{options}}("keep.source") is true (the default), the
  source of functions is kept so they can be listed exactly as input.
  This imposes a limit of 128K chars on the function size and a nesting
  limit of 265.  Use \code{option(keep.source = FALSE)} when these
  limits might take effect: if exceeded they generate an error.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{demo}} which uses \code{source};
  \code{\link{eval}}, \code{\link{parse}} and \code{\link{scan}};
  \code{\link{options}("keep.source")}.
}
\keyword{file}
\keyword{programming}
\keyword{connection}
\eof
\name{splinefun}
\alias{spline}
\alias{splinefun}
\title{Interpolating Splines}
\description{
  Perform cubic spline interpolation of given data points, returning
  either a list of points obtained by the interpolation or a function
  performing the interpolation.
}
\usage{
splinefun(x, y = NULL, method = "fmm")

spline(x, y = NULL, n = 3*length(x), method = "fmm",
       xmin = min(x), xmax = max(x))
}
\arguments{
  \item{x,y}{vectors giving the coordinates of the points to be
    interpolated.  Alternatively a single plotting structure can be
    specified: see \code{\link{xy.coords}.}}
  \item{method}{specifies the type of spline to be used.  Possible
    values are \code{"fmm"}, \code{"natural"} and \code{"periodic"}.}
  \item{n}{interpolation takes place at \code{n} equally spaced points
    spanning the interval [\code{xmin}, \code{xmax}].}
  \item{xmin}{left-hand endpoint of the interpolation interval.}
  \item{xmax}{right-hand endpoint of the interpolation interval.}
}
\details{
  If \code{method = "fmm"}, the spline used is that of Forsythe, Malcolm
  and Moler (an exact cubic is fitted through the four points at each
  end of the data, and this is used to determine the end conditions).
  Natural splines are used when \code{method = "natural"}, and periodic
  splines when \code{method = "periodic"}.

  These interpolation splines can also be used for extrapolation, that is
  prediction at points outside the range of \code{x}.  Extrapolation
  makes little sense for \code{method = "fmm"}; for natural splines it
  is linear using the slope of the interpolating curve at the nearest
  data point.
}
\value{
  \code{spline} returns a list containing components \code{x} and
  \code{y} which give the ordinates where interpolation took place and
  the interpolated values.

  \code{splinefun} returns a function which will perform cubic spline
  interpolation of the given data points.  This is often more useful
  than \code{spline}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Forsythe, G. E., Malcolm, M. A. and Moler, C. B. (1977)
  \emph{Computer Methods for Mathematical Computations}.
}
\seealso{
  \code{\link{approx}} and \code{\link{approxfun}} for constant and
  linear interpolation.

  Package \pkg{splines}, especially \code{\link[splines]{interpSpline}}
  and \code{\link[splines]{periodicSpline}} for interpolation splines.
  That package also generates spline bases that can be used for
  regression splines.

  \code{\link[modreg]{smooth.spline}} in package \pkg{modreg} for
  smoothing splines.
}
\examples{
op <- par(mfrow = c(2,1), mgp = c(2,.8,0), mar = .1+c(3,3,3,1))
n <- 9
x <- 1:n
y <- rnorm(n)
plot(x, y, main = paste("spline[fun](.) through", n, "points"))
lines(spline(x, y))
lines(spline(x, y, n = 201), col = 2)

y <- (x-6)^2
plot(x, y, main = "spline(.) -- 3 methods")
lines(spline(x, y, n = 201), col = 2)
lines(spline(x, y, n = 201, method = "natural"), col = 3)
lines(spline(x, y, n = 201, method = "periodic"), col = 4)
legend(6,25, c("fmm","natural","periodic"), col=2:4, lty=1)

f <- splinefun(x, y)
ls(envir = environment(f))
splinecoef <- eval(expression(z), envir = environment(f))
curve(f(x), 1, 10, col = "green", lwd = 1.5)
points(splinecoef, col = "purple", cex = 2)
par(op)
}
\keyword{math}
\keyword{dplot}
\eof
\name{split}
\title{Divide into Groups}
\alias{split}
\alias{split.default}
\alias{split.data.frame}
\alias{split<-}
\alias{split<-.default}
\alias{split<-.data.frame}
\alias{unsplit}
\description{
  \code{split} divides the data in the vector \code{x} into the groups
  defined by \code{f}.  The assignment forms replace values
  corresponding to such a division.  Unsplit reverses the effect of
  \code{split}.
}
\usage{
split(x, f)
split(x, f) <- value
unsplit(value, f)
}
\arguments{
  \item{x}{vector or data frame containing values to be divided into groups.}
  \item{f}{a \dQuote{factor} such that \code{factor(f)} defines the
    grouping, or a list of such factors in which case their interaction
    is used for the grouping.}
  \item{value}{a list of vectors or data frames compatible with a
    splitting of \code{x}}
}
\details{
  \code{split} and \code{split<-} are generic functions with default and
  \code{data.frame} methods.

  \code{f} is recycled as necessary and if the length of \code{x} is not
  a multiple of the length of \code{f} a warning is printed.
  \code{unsplit} works only with  lists of vectors. The data frame
  method can also be used to split a matrix into a list of matrices,
  and the assignment form likewise, provided they are invoked
  explicitly.
}
\value{
  The value returned from \code{split} is a list of vectors containing
  the values for the
  groups.  The components of the list are named by the factor levels
  given be \code{f}.  If \code{f} is longer than \code{x} some of these
  will be of zero length. The assignment forms return their right hand side.
  \code{unsplit} returns a vector for which \code{split(x, f)} equals
  \code{value}
}
\seealso{
  \code{\link{cut}}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
n <- 10; nn <- 100
g <- factor(round(n * runif(n * nn)))
x <- rnorm(n * nn) + sqrt(as.numeric(g))
xg <- split(x, g)
boxplot(xg, col = "lavender", notch = TRUE, varwidth = TRUE)
sapply(xg, length)
sapply(xg, mean)

## Calculate z-scores by group

z <- unsplit(lapply(split(x, g), scale), g)
tapply(z, g, mean)

# or

z <- x
split(z, g) <- lapply(split(x, g), scale)
tapply(z, g, sd)

## Split a matrix into a list by columns
ma <- cbind(x = 1:10, y = (-4:5)^2)
split(ma, col(ma))

split(1:10, 1:2)
}
\keyword{category}
\eof
\name{sprintf}
\alias{sprintf}
\title{Use C-style String Formatting Commands}
\description{
  A wrapper for the C function \code{sprintf}, that
  returns a character vector of length one containing a formatted
  combination of text and variable values.
}
\usage{
sprintf(fmt, \dots)
}
\arguments{
  \item{fmt}{a format string.}
  \item{\dots}{values to be passed into \code{fmt}. Only logical,
    integer, real and character vectors are accepted, and only the first
    value is read from each vector.}
}
\details{
  This is a wrapper for the system's C call.  Attempts are made to
  check that the mode of the values passed match the format supplied,
  and \R's special values (\code{NA}, \code{Inf}, \code{-Inf} and
  \code{NaN}) are handled correctly.
  
  The following is abstracted from K&R (see References, below).  The
  string \code{fmt} contains normal characters, which are passed through
  to the output string, and also special characters that operate on the
  arguments provided through \code{\dots}.  Special characters start
  with a \code{\%} and terminate with one of the letters in the set
  \code{difeEgGs\%}.  These letters denote the following types:

  \describe{
    \item{\code{d,i}}{Integer value}

    \item{\code{f}}{Double precision value, in decimal notation of the form
      "[-]mmm.ddd".  The number of decimal places is specified by the
      precision: the default is 6; a precision of 0 suppresses the decimal point.}

    \item{\code{e,E}}{Double precision value, in decimal notation of the form
      \code{[-]m.ddde[+-]xx} or \code{[-]m.dddE[+-]xx}}

    \item{\code{g,G}}{Double precision value, in \code{\%e} or
      \code{\%E} format if the exponent is less than -4 or greater than or
      equal to the precision, and \code{\%f} format otherwise}

    \item{\code{s}}{Character string}

    \item{\code{\%}}{Literal \code{\%} (none of the formatting
      characters given below are permitted in this case)}
  }

  In addition, between the initial \code{\%} and the terminating
  conversion character there may be, in any order:

  \describe{
    \item{\code{m.n}}{Two numbers separated by a period, denoting the
      field width (\code{m}) and the precision (\code{n})}
    \item{\code{-}}{Left adjustment of converted argument in its field}
    \item{\code{+}}{Always print number with sign}
    \item{a space}{Prefix a space if the first number is not a sign}
    \item{\code{0}}{For numbers, pad to the field width with leading zeros}
  }
}

\value{
  A character vector of length one.  Character \code{NA}s are converted
  to \code{"NA"}.
}

\references{
  Kernighan, B. W. and Ritchie, D. M. (1988)
  \emph{The C Programming Language.} Second edition, Prentice Hall.
  describes the format options in table B-1 in the Appendix.
}

\author{
  Original code by Jonathan Rougier, \email{J.C.Rougier@durham.ac.uk}
}

\seealso{
  \code{\link{formatC}} for a way of formatting vectors of
  numbers in a similar fashion.

  \code{\link{paste}} for another way of
  creating a vector combining text and values.
}

\examples{
% Escape all the '%' here !
## be careful with the format: most things in R are floats

sprintf("\%s is \%f feet tall\n", "Sven", 7) # OK
try(sprintf("\%s is \%i feet tall\n", "Sven", 7)) # not OK
sprintf("\%s is \%i feet tall\n", "Sven", as.integer(7)) # OK again

## use a literal \% :

sprintf("\%.0f\%\% said yes (out of a sample of size \%.0f)", 66.666, 3)

## various formats of pi :

sprintf("\%f", pi)
sprintf("\%.3f", pi)
sprintf("\%1.0f", pi)
sprintf("\%5.1f", pi)
sprintf("\%05.1f", pi)
sprintf("\%+f", pi)
sprintf("\% f", pi)
sprintf("\%-10f", pi)# left justified
sprintf("\%e", pi)
sprintf("\%E", pi)
sprintf("\%g", pi)
sprintf("\%g",   1e6 * pi) # -> exponential
sprintf("\%.9g", 1e6 * pi) # -> "fixed"
sprintf("\%G", 1e-6 * pi)

## no truncation:
sprintf("\%1.f",101)

## More sophisticated:

lapply(c("a", "ABC", "and an even longer one"),
       function(ch) sprintf("10-string '\%10s'", ch))

sapply(1:18, function(n)
       sprintf(paste("e with \%2d digits = \%.",n,"g",sep=""),
               n, exp(1)))
}
\keyword{print}
\keyword{character}
\eof
\name{stack}
\alias{stack}
\alias{stack.default}
\alias{stack.data.frame}
\alias{unstack}
\alias{unstack.default}
\alias{unstack.data.frame}
\title{Stack or Unstack Vectors from a Data Frame or List}
\description{
  Stacking vectors concatenates multiple vectors into a single vector
  along with a factor indicating where each observation originated.
  Unstacking reverses this operation.
}
\usage{
stack(x, \dots)
\method{stack}{default}(x, \dots)
\method{stack}{data.frame}(x, select, \dots)

unstack(x, \dots)
\method{unstack}{default}(x, form, \dots)
\method{unstack}{data.frame}(x, form = formula(x), \dots)
}
\arguments{
  \item{x}{object to be stacked or unstacked}
  \item{select}{expression, indicating variables to select from a
    data frame}
  \item{form}{a two-sided formula whose left side evaluates to the
    vector to be unstacked and whose right side evaluates to the
    indicator of the groups to create.  Defaults to \code{formula(x)}
    in \code{unstack.data.frame}.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\details{
  The \code{stack} function is used to transform data available as
  separate columns in a data frame or list into a single column that can
  be used in an analysis of variance model or other linear model.  The
  \code{unstack} function reverses this operation. 
}
\value{
  \code{unstack} produces a list of columns according to the formula
  \code{form}.  If all the columns have the same length, the resulting
  list is coerced to a data frame.
  
  \code{stack} produces a data frame with two columns
  \item{values}{the result of concatenating the selected vectors in
    \code{x}}
  \item{ind}{a factor indicating from which vector in \code{x} the
    observation originated}
}
\author{Douglas Bates}
\seealso{
  \code{\link{lm}}, \code{\link{reshape}}
}
\examples{
data(PlantGrowth)
formula(PlantGrowth)         # check the default formula
pg <- unstack(PlantGrowth)   # unstack according to this formula
pg
stack(pg)                    # now put it back together
stack(pg, select = -ctrl)    # omitting one vector
}
\keyword{manip}
\eof
\name{stackloss}
\docType{data}
\alias{stackloss}
\alias{stack.loss}
\alias{stack.x}
\title{Brownlee's Stack Loss Plant Data}
\description{
  Operational data of a plant for the oxidation of ammonia to nitric
  acid.
}
\usage{data(stackloss)}
\format{
  \code{stackloss} is a data frame with 21 observations on 4 variables.

  \tabular{rll}{
    [,1] \tab \code{Air Flow}   \tab Flow of cooling air\cr
    [,2] \tab \code{Water Temp} \tab Cooling Water Inlet
    Temperature\cr
    [,3] \tab  \code{Acid Conc.} \tab Concentration of acid [per
    1000, minus 500]\cr
    [,4] \tab  \code{stack.loss} \tab Stack loss\cr
  }

  For compatibility with S-PLUS, the data sets \code{stack.x}, a matrix
  with the first three (independent) variables of the data frame, and
  \code{stack.loss}, the numeric vector giving the fourth (dependent)
  variable, are provided as well.
}
\source{
  Brownlee, K. A. (1960, 2nd ed. 1965)
  \emph{Statistical Theory and Methodology in Science and Engineering}.
  New York: Wiley. pp. 491--500.
}
\details{
  \dQuote{Obtained from 21 days of operation of a plant for the
    oxidation of ammonia (NH\eqn{_3}{3}) to nitric acid
    (HNO\eqn{_3}{3}).  The nitric oxides produced are absorbed in a
    countercurrent absorption tower}.
  (Brownlee, cited by Dodge, slightly reformatted by MM.)

  \code{Air Flow} represents the rate of operation of the plant.
  \code{Water Temp} is the temperature of cooling water circulated
  through coils in the absorption tower.
  \code{Acid Conc.} is the concentration of the acid circulating, minus
  50, times 10: that is, 89 corresponds to 58.9 per cent acid.
  \code{stack.loss} (the dependent variable) is 10 times the percentage
  of the ingoing ammonia to the plant that escapes from the absorption
  column unabsorbed; that is, an (inverse) measure of the over-all
  efficiency of the plant.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Dodge, Y. (1996)
  The guinea pig of multiple regression. In:
  \emph{Robust Statistics, Data Analysis, and Computer Intensive
    Methods; In Honor of Peter Huber's 60th Birthday}, 1996,
  \emph{Lecture Notes in Statistics} \bold{109}, Springer-Verlag, New York.
}
\examples{
data(stackloss)
summary(lm.stack <- lm(stack.loss ~ stack.x))
}
\keyword{datasets}

\eof
\name{standardGeneric}
\alias{standardGeneric}
\title{Formal Method System Placeholders}
\description{
  Routines which are primitives used with the \pkg{methods} package.
  They should not be used without it and do not need to be called
  directly in any case.
}
\usage{
standardGeneric(f)
}
\details{
  \code{standardGeneric} dispatches the method defined for a generic
  function \code{f}, using the actual arguments in the frame from which
  it is called.
}
\author{ John Chambers }
\keyword{programming}
\keyword{internal}
\eof
\name{stars}
\alias{stars}
\title{Star (Spider/Radar) Plots and Segment Diagrams}
\description{
  Draw star plots or segment diagrams of a multivariate data set.
  With one single location, also draws \dQuote{spider} (or \dQuote{radar}) plots.
}
\usage{
stars(x, full = TRUE, scale = TRUE, radius = TRUE,
      labels = dimnames(x)[[1]], locations = NULL,
      nrow = NULL, ncol = NULL, len = 1,
      key.loc = NULL, key.labels = dimnames(x)[[2]], key.xpd = TRUE,
      xlim = NULL, ylim = NULL, flip.labels = NULL,
      draw.segments = FALSE, col.segments = 1:n.seg, col.stars = NA,
      axes = FALSE, frame.plot = axes,
      main = NULL, sub = NULL, xlab = "", ylab = "",
      cex = 0.8, lwd = 0.25, lty = par("lty"), xpd = FALSE,
      mar = pmin(par("mar"),
                 1.1+ c(2*axes+ (xlab != ""), 2*axes+ (ylab != ""), 1,0)),
      add=FALSE, plot=TRUE, \dots)
}
\arguments{
  \item{x}{matrix or data frame of data.
    One star or segment plot will be produced for each row of \code{x}.
    Missing values (\code{NA}) are allowed, but they are treated as if
    they were 0 (after scaling, if relevant).}
  \item{full}{logical flag: if \code{TRUE}, the segment plots will
    occupy a full circle.  Otherwise, they occupy the (upper) semicircle
    only.}
  \item{scale}{logical flag: if \code{TRUE}, the columns of the data
    matrix are scaled independently so that the maximum value in each
    column is 1 and the minimum is 0.  If \code{FALSE}, the presumption
    is that the data have been scaled by some other algorithm to the
    range \eqn{[0,1]}.}
  \item{radius}{logical flag: in \code{TRUE}, the radii corresponding to
    each variable in the data will be drawn.}
  \item{labels}{vector of character strings for labeling the plots.
    Unlike the S function \code{stars}, no attempt is made to construct
    labels if \code{labels = NULL}.}
  \item{locations}{Either two column matrix with the x and y coordinates used
    to place each of the segment plots; or numeric of length 2 when all
    plots should be superimposed (for a \dQuote{spider plot}).
    By default, \code{locations = NULL}, the segment plots will be
    placed in a rectangular grid.}
  \item{nrow, ncol}{integers giving the number of rows and columns to use when
    \code{locations} is \code{NULL}.  By default, \code{nrow == ncol}, a square
    layout will be used.}
  \item{len}{scale factor for the length of radii or segments.}
  \item{key.loc}{vector with x and y coordinates of the unit key.}
  \item{key.labels}{vector of character strings for labeling the
    segments of the unit key.  If omitted, the second component of
    \code{dimnames(x)} is used, if available.}
  \item{key.xpd}{clipping switch for the unit key (drawing and
    labeling), see \code{\link{par}("xpd")}.}
  \item{xlim}{vector with the range of x coordinates to plot. }
  \item{ylim}{vector with the range of y coordinates to plot.}
  \item{flip.labels}{logical indicating if the label locations should
    flip up and down from diagram to diagram. Defaults to a somewhat
    smart heuristic.}
  \item{draw.segments}{logical. If \code{TRUE} draw a segment diagram.}
  \item{col.segments}{color vector (integer or character, see
    \code{\link{par}}), each specifying a color for one of the segments
    (variables).  Ignored if \code{draw.segments = FALSE}.}
  \item{col.stars}{color vector (integer or character, see
    \code{\link{par}}), each specifying a color for one of the stars
    (cases).  Ignored if \code{draw.segments = TRUE}.}
  \item{axes}{logical flag: if \code{TRUE} axes are added to the plot.}
  \item{frame.plot}{logical flag: if \code{TRUE}, the plot region is framed.}
  \item{main}{a main title for the plot.}
  \item{sub}{a sub title for the plot.}
  \item{xlab}{a label for the x axis.}
  \item{ylab}{a label for the y axis.}
  \item{cex}{character expansion factor for the labels.}
  \item{lwd}{line width used for drawing.}
  \item{lty}{line type used for drawing.}
  \item{xpd}{logical or NA indicating if clipping should be done, see
    \code{\link{par}(xpd = .)}.}
  \item{mar}{argument to \code{\link{par}(mar = *)}, typically chosing
    smaller margings than by default.}
  \item{\dots}{further arguments, passed to the first call of
    \code{plot()}, see \code{\link{plot.default}} and to
    \code{\link{box}()} if \code{frame.plot} is true.}
  \item{add}{logical, if \code{TRUE} \emph{add} stars to current plot.}
  \item{plot}{logical, if \code{FALSE}, nothing is plotted.}
  }
}
\details{
  Missing values are treated as 0.

  Each star plot or segment diagram represents one row of the input
  \code{x}.  Variables (columns) start on the right and wind
  counterclockwise around the circle.  The size of the (scaled) column
  is shown by the distance from the center to the point on the star or
  the radius of the segment representing the variable.

  Only one page of output is produced.
}
\author{Thomas S. Dye}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\note{
  This code started life as spatial star plots by David A. Andrews.
  See \url{http://www.udallas.edu:8080/~andrews/software/software.html}.

  Prior to 1.4.1, scaling only shifted the maximum to 1, although
  documented as here.
}
\examples{
data(mtcars)
stars(mtcars[, 1:7], key.loc = c(14, 2),
      main = "Motor Trend Cars : stars(*, full = F)", full = FALSE)
stars(mtcars[, 1:7], key.loc = c(14, 1.5),
      main = "Motor Trend Cars : full stars()",flip.labels=FALSE)

## 'Spider' or 'Radar' plot:
stars(mtcars[, 1:7], locations = c(0,0), radius = FALSE,
      key.loc=c(0,0), main="Motor Trend Cars", lty = 2)

## Segment Diagrams:
palette(rainbow(12, s = 0.6, v = 0.75))
stars(mtcars[, 1:7], len = 0.8, key.loc = c(12, 1.5),
      main = "Motor Trend Cars", draw.segments = TRUE)
stars(mtcars[, 1:7], len = 0.6, key.loc = c(1.5, 0),
      main = "Motor Trend Cars", draw.segments = TRUE,
      frame.plot=TRUE, nrow = 4, cex = .7)

data(USJudgeRatings)
## scale linearly (not affinely) to [0, 1]
USJudge <- apply(USJudgeRatings, 2, function(x) x/max(x))
Jnam <- case.names(USJudgeRatings)
Snam <- abbreviate(substring(Jnam,1,regexpr("[,.]",Jnam) - 1), 7)
stars(USJudge, labels = Jnam, scale = FALSE,
      key.loc = c(13, 1.5), main = "Judge not ...", len = 0.8)
stars(USJudge, labels = Snam, scale = FALSE,
      key.loc = c(13, 1.5), radius = FALSE)

loc <- stars(USJudge, labels = NULL, scale = FALSE,
             radius = FALSE, frame.plot = TRUE,
             key.loc = c(13, 1.5), main = "Judge not ...", len = 1.2)
text(loc, Snam, col = "blue", cex = 0.8, xpd = TRUE)

## 'Segments':
stars(USJudge, draw.segments = TRUE, scale = FALSE, key.loc = c(13,1.5))

## 'Spider':
stars(USJudgeRatings, locations=c(0,0), scale=FALSE,radius = FALSE,
      col.stars=1:10, key.loc = c(0,0), main="US Judges rated")
## 'Radar-Segments'
stars(USJudgeRatings[1:10,], locations = 0:1, scale=FALSE,
      draw.segments = TRUE, col.segments=0, col.stars=1:10,key.loc= 0:1,
       main="US Judges 1-10 ")
palette("default")
stars(cbind(1:16,10*(16:1)),draw.segments=TRUE,
      main = "A Joke -- do *not* use symbols on 2D data!")
}
\keyword{hplot}
\keyword{multivariate}
\eof
\name{start}
\title{Encode the Terminal Times of Time Series}
\usage{
start(x, \dots)
end(x, \dots)
}
\alias{start}
\alias{end}
\alias{start.default}
\alias{end.default}
\arguments{
    \item{x}{a univariate or multivariate time-series, or a vector or matrix.}
    \item{\dots}{extra arguments for future methods.}
}
\description{
    Extract and encode the times the first and last observations were
    taken. Provided only for compatibility with S version 2.
}
\details{
    These are generic functions, which will use the
    \code{\link{tsp}} attribute of \code{x} if it exists.
    Their default methods decode the start time from the original time
    units, so that for a monthly series \code{1995.5} is represented
    as \code{c(1995, 7)}. For a series of frequency \code{f}, time
    \code{n+i/f} is presented as \code{c(n, i+1)} (even for \code{i = 0}
    and \code{f = 1}).
}
\section{Warning}{
    The representation used by \code{start} and \code{end} has no
    meaning unless the frequency is supplied.
}
\seealso{
  \code{\link{ts}}, \code{\link{time}}, \code{\link{tsp}}.
}
\keyword{ts}
\eof
\name{stat.anova}
\title{GLM Anova Statistics}
\usage{
stat.anova(table, test = c("Chisq", "F", "Cp"), scale, df.scale, n)
}
\alias{stat.anova}
\arguments{
 \item{table}{numeric matrix as results from
   \code{\link{anova.glm}(\dots, test=NULL)}.}
 \item{test}{a character string, matching one of \code{"Chisq"},
   \code{"F"} or \code{"Cp"}.}
 \item{scale}{a weighted residual sum of squares.}
 \item{df.scale}{degrees of freedom corresponding to scale.}
 \item{n}{number of observations.}
}
\description{This is a utility function, used in \code{lm} and
  \code{glm} methods for \code{\link{anova}(\dots, test != NULL)}
  and should not be used by the average user.
}
\value{
  A matrix which is the original \code{table}, augmented by a column
  of test statistics, depending on the \code{test} argument.
}
\references{
  Hastie, T. J. and Pregibon, D. (1992)
  \emph{Generalized linear models.}
  Chapter 6 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\seealso{\code{\link{anova.lm}}, \code{\link{anova.glm}}.}
\examples{
##-- Continued from '?glm':
\dontshow{example("glm", echo = FALSE)}
print(ag <- anova(glm.D93))
stat.anova(ag$table, test = "Cp",
           scale = sum(resid(glm.D93, "pearson")^2)/4, df = 4, n = 9)
}
\keyword{regression}
\keyword{models}
\eof
\name{state}
\docType{data}
\alias{state}
\alias{state.abb}
\alias{state.area}
\alias{state.center}
\alias{state.division}
\alias{state.name}
\alias{state.region}
\alias{state.x77}
\title{US State Facts and Figures}
\description{Data sets related to the 50 states of the United States of
  America.}
\usage{data(state)}
\details{
  \R currently contains the following \dQuote{state} data sets.  Note
  that all data are arranged according to alphabetical order of the
  state names.
  \describe{
    \item{\code{state.abb}:}{character vector of 2-letter abbreviations
      for the state names.}
    \item{\code{state.area}:}{numeric vector of state areas (in square
      miles).}
    \item{\code{state.center}:}{ list with components named \code{x} and
      \code{y} giving the approximate geographic center of each state in
      negative longitude and latitude.  Alaska and Hawaii are placed
      just off the West Coast.}
    \item{\code{state.division}:}{factor giving state divisions (New
      England, Middle Atlantic, South Atlantic, East South Central, West
      South Central, East North Central, West North Central, Mountain,
      and Pacific).}
    \item{\code{state.name}:}{character vector giving the full state
      names.}
    \item{\code{state.region}:}{factor giving the region (Northeast,
      South, North Central, West) that each state belongs to.}
    \item{\code{state.x77}:}{matrix with 50 rows and 8 columns giving
      the following statistics in the respective columns.
      \describe{
      	\item{\code{Population}:}{population estimate as of July 1,
	  1975}
       	\item{\code{Income}:}{per capita income (1974)}
       	\item{\code{Illiteracy}:}{illiteracy (1970, percent of
	  population)}
       	\item{\code{Life Exp}:}{life expectancy in years (1969--71)}
       	\item{\code{Murder}:}{murder and non-negligent manslaughter rate
	  per 100,000 population (1976)}
       	\item{\code{HS Grad}:}{percent high-school graduates (1970)}
       	\item{\code{Frost}:}{mean number of days with minimum
	  temperature below freezing (1931--1960) in capital or large
	  city}
       \item{\code{Area}:}{land area in square miles}
    }}
  }
}
\source{
  U.S. Department of Commerce, Bureau of the Census (1977)
  \emph{Statistical Abstract of the United States}.

  U.S. Department of Commerce, Bureau of the Census (1977)
  \emph{County and City Data Book}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\keyword{datasets}
\eof
\name{stem}
\title{Stem-and-Leaf Plots}
\usage{
stem(x, scale = 1, width = 80, atom = 1e-08)
}
\alias{stem}
\description{
  \code{stem} produces a stem-and-leaf plot of the values in \code{x}.
  The parameter \code{scale} can be used to expand the scale of the
  plot.  A value of \code{scale=2} will cause the plot to be roughly
  twice as long as the default.
}
\arguments{
  \item{x}{a numeric vector.}
  \item{scale}{This controls the plot length.}
  \item{width}{The desired width of plot.}
  \item{atom}{a tolerance.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
data(islands)
stem(islands)
stem(log10(islands))
}
\keyword{univar}
\keyword{distribution}
\eof
\name{step}
\alias{step}
\title{
Choose a model by AIC in a Stepwise Algorithm
}
\description{
  Select a formula-based model by AIC.
}
\usage{
step(object, scope, scale = 0,
     direction = c("both", "backward", "forward"), 
     trace = 1, keep = NULL, steps = 1000, k = 2, \dots)
}
\arguments{
  \item{object}{
    an object representing a model of an appropriate class (mainly
    \code{"lm"} and \code{"glm"}).
    This is used as the initial model in the stepwise search.
  }
  \item{scope}{
    defines the range of models examined in the stepwise search.
    This should be either a single formula, or a list containing
    components \code{upper} and \code{lower}, both formulae.  See the
    details for how to specify the formulae and how they are used.
  }
  \item{scale}{
    used in the definition of the AIC statistic for selecting the models,
    currently only for \code{\link{lm}}, \code{\link{aov}} and
    \code{\link{glm}} models.
  }
  \item{direction}{
    the mode of stepwise search, can be one of \code{"both"},
    \code{"backward"}, or \code{"forward"}, with a default of \code{"both"}. 
    If the \code{scope} argument is missing the default for
    \code{direction} is \code{"backward"}.
  }
  \item{trace}{
    if positive, information is printed during the running of \code{step}.
    Larger values may give more detailed information.
  }
  \item{keep}{
    a filter function whose input is a fitted model object and the 
    associated \code{AIC} statistic, and whose output is arbitrary. 
    Typically \code{keep} will select a subset of the components of 
    the object and return them. The default is not to keep anything.
  }
  \item{steps}{
    the maximum number of steps to be considered.  The default is 1000
    (essentially as many as required).  It is typically used to stop the
    process early.
  }
  \item{k}{
    the multiple of the number of degrees of freedom used for the penalty.
    Only \code{k = 2} gives the genuine AIC: \code{k = log(n)} is sometimes
    referred to as BIC or SBC.
  }
  \item{\dots}{
    any additional arguments to \code{\link{extractAIC}}.
  }
}
\value{
  the stepwise-selected model is returned, with up to two additional
  components.  There is an \code{"anova"} component corresponding to the
  steps taken in the search, as well as a \code{"keep"} component if the
  \code{keep=} argument was supplied in the call. The
  \code{"Resid. Dev"} column of the analysis of deviance table refers
  to a constant minus twice the maximized log likelihood: it will be a
  deviance only in cases where a saturated model is well-defined
  (thus excluding \code{lm}, \code{aov} and \code{survreg} fits,
  for example).
}
\details{
  \code{step} uses \code{\link{add1}} and \code{\link{drop1}}
  repeatedly; it will work for any method for which they work, and that
  is determined by having a valid method for \code{\link{extractAIC}}.
  When the additive constant can be chosen so that AIC is equal to
  Mallows' \eqn{C_p}{Cp}, this is done and the tables are labelled
  appropriately.

  The set of models searched is determined by the \code{scope} argument.
  The right-hand-side of its \code{lower} component is always included
  in the model, and right-hand-side of the model is included in the
  \code{upper} component.  If \code{scope} is a single formula, it
  specifes the \code{upper} component, and the \code{lower} model is
  empty.  If \code{scope} is missing, the initial model is used as the
  \code{upper} model.

  Models specified by \code{scope} can be templates to update
  \code{object} as used by \code{\link{update.formula}}.
  
  There is a potential problem in using \code{\link{glm}} fits with a
  variable \code{scale}, as in that case the deviance is not simply
  related to the maximized log-likelihood. The function
  \code{\link{extractAIC.glm}} makes the
  appropriate adjustment for a \code{gaussian} family, but may need to be
  amended for other cases. (The \code{binomial} and \code{poisson}
  families have fixed \code{scale} by default and do not correspond
  to a particular maximum-likelihood problem for variable \code{scale}.)
}
\note{
  This function differs considerably from the function in S, which uses a
  number of approximations and does not compute the correct AIC.

  This is a minimal implementation. Use \code{\link[MASS]{stepAIC}} for
  a wider range of object classes.
}
\section{Warning}{
  The model fitting must apply the models to the same dataset. This
  may be a problem if there are missing values and \R's default of
  \code{na.action = na.omit} is used.  We suggest you remove the
  missing values first.
}
\seealso{
  \code{\link[MASS]{stepAIC}}, \code{\link{add1}}, \code{\link{drop1}}
}
\references{
  Hastie, T. J. and Pregibon, D. (1992)
  \emph{Generalized linear models.}
  Chapter 6 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.

  Venables, W. N. and Ripley, B. D. (2002)
  \emph{Modern Applied Statistics with S.}
  New York: Springer (4th ed).
}
\author{
  B. D. Ripley: \code{step} is a slightly simplified version of
  \code{\link[MASS]{stepAIC}} in package \pkg{MASS} (Venables \&
  Ripley, 2002 and earlier editions).

  The idea of a \code{step} function follows that described in Hastie \&
  Pregibon (1992); but the implementation in \R is more general.
}
\examples{
example(lm)
step(lm.D9)  

data(swiss)
summary(lm1 <- lm(Fertility ~ ., data = swiss))
slm1 <- step(lm1)
summary(slm1)
slm1$anova
}
\keyword{models}
\eof
\name{stop}
\title{Stop Function Execution}
\usage{
stop(\dots, call. = TRUE)
geterrmessage()
}
\alias{stop}
\alias{geterrmessage}
\arguments{
  \item{\dots}{character vectors (which are pasted together with no
    separator), a condition object, or \code{NULL}.}
  \item{call.}{logical, indicating if the call should become part of the
    error message.}
}
\description{
  \code{stop} stops execution of the current expression and executes
  an error action.

  \code{geterrmessage} gives the last error message.
}
\details{

  The error action is controlled by error handlers established within
  the executing code and by the current default error handler set by
  \code{options(error=)}.  The error is first signaled as if using
  \code{signalCondition}.  If there are no handlers or if all handlers
  return, then the error message is printed (if
  \code{options("show.error.messages")} is true) and the default error
  handler is used.  The default behaviour (the \code{NULL}
  error-handler) in interactive use is to return to the top level
  prompt or the top level browser, and in non-interactive use to
  (effectively) call \code{\link{q}("no", status=1, runLast=FALSE}).
  The default handler stores the error message in a buffer; it can be
  retrieved by \code{geterrmessage}.  It also stores a trace of the
  call stack that can be retrieved by  code{traceback}.

  Errors will be truncated to \code{getOption("warning.length")}
  characters, default 1000.
}
\value{
  \code{geterrmessage} gives the last error message, as character string
  ending in \code{"\\n"}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{warning}}, \code{\link{try}} to catch errors and retry,
  and \code{\link{options}} for setting error handlers.
  \code{\link{stopifnot}} for validity testing.  \code{tryCatch}
  and \code{withCallingHandlers} can be used to establish custom handlers
  while executing an expression.
}
\examples{
options(error = expression(NULL))# don't stop on stop(.)  << Use with CARE! >>

iter <- 12
if(iter > 10) stop("too many iterations")

tst1 <- function(...) stop("dummy error")
tst1(1:10,long,calling,expression)

tst2 <- function(...) stop("dummy error", call. = FALSE)
tst2(1:10,long,calling,expression,but.not.seen.in.Error)

options(error = NULL)# revert to default
}
\keyword{environment}
\keyword{programming}
\keyword{error}
\eof
\name{stopifnot}
\alias{stopifnot}
\title{Ensure the `Truth' of R Expressions}
\description{
  If any of the expressions in \code{\dots} are not \code{\link{all}}
  \code{TRUE}, \code{\link{stop}} is called, producing an error message
  indicating the \emph{first} element of \code{\dots} which was not
  true.
}
\usage{
stopifnot(\dots)
}
\arguments{
  \item{\dots}{any number of (\code{\link{logical}}) \R expressions
    which should evaluate to \code{\link{TRUE}}.}
}
\details{
  \code{stopifnot(A, B)} is conceptually equivalent to
  \code{\{ if(!all(A)) stop(...) ; if(!all(B)) stop(...) \}}.
}
\value{
  (\code{\link{NULL}} if all statements in \code{\dots} are \code{TRUE}.)
}
\seealso{\code{\link{stop}}, \code{\link{warning}}.}
\examples{
stopifnot(1 == 1, all.equal(pi, 3.14159265), 1 < 2) # all TRUE

m <- matrix(c(1,3,3,1), 2,2)
stopifnot(m == t(m), diag(m) == rep(1,2)) # all(.) |=>  TRUE

options(error = expression(NULL))# "disable stop(.)"  << Use with CARE! >>

stopifnot(all.equal(pi, 3.141593),  2 < 2, all(1:10 < 12), "a" < "b")
stopifnot(all.equal(pi, 3.1415927), 2 < 2, all(1:10 < 12), "a" < "b")

options(error = NULL)# revert to default error handler
}
\keyword{environment}
\keyword{programming}
\keyword{error}
\eof
\name{str}
\title{Compactly Display the Structure of an Arbitrary R Object}
\usage{
str(object, \dots)

\method{str}{data.frame}(object, \dots)

\method{str}{default}(object, max.level = 0, vec.len = 4, digits.d = 3,
    nchar.max = 128, give.attr = TRUE, give.length = TRUE,
    wid = getOption("width"), nest.lev = 0,
    indent.str = paste(rep(" ", max(0, nest.lev + 1)), collapse = ".."),
    \dots)

 ls.str(pos = 1, pattern, \dots,  envir = as.environment(pos), mode = "any",
        max.level = 1, give.attr = FALSE)
lsf.str(pos = 1, \dots, envir = as.environment(pos))
}
\alias{str}
\alias{str.default}
\alias{str.data.frame}
\alias{ls.str}
\alias{lsf.str}
\description{
  Compactly display the internal \bold{str}ucture of an \R object, a
  \dQuote{diagnostic} function and an alternative to \code{\link{summary}}
  (and to some extent, \code{\link{dput}}).  Ideally, only one line for
  each \dQuote{basic} structure is displayed.  It is especially well suited
  to compactly display the (abbreviated) contents of (possibly nested)
  lists.  The idea is to give reasonable output for \bold{any} \R
  object.  It calls \code{\link{args}} for (non-primitive) function objects.

  \code{\link{ls.str}} and \code{\link{lsf.str}} are useful \dQuote{versions}
  of \code{\link{ls}}, calling \code{str} on each object.  They are not
  foolproof and should rather not be used for programming, but are
  provided for their usefulness.
}
\arguments{
  \item{object}{any \R object about which you want to have some
    information.}
  \item{max.level}{maximal level of nesting which is applied for
    displaying nested structures, e.g., a list containing sub lists.
    Default 0: Display all nesting levels.}
  \item{vec.len}{numeric (>= 0) indicating how many \dQuote{first few} elements
    are displayed of each vector.  The number is multiplied by different
    factors (from .5 to 3) depending on the kind of vector.  Default 4.}
  \item{digits.d}{number of digits for numerical components (as for
    \code{\link{print}}).}
  \item{nchar.max}{maximal number of characters to show for
    \code{\link{character}} strings.  Longer strings are truncated, see
    \code{longch} example below.}
  \item{give.attr}{logical; if \code{TRUE} (default), show attributes
    as sub structures.}
  \item{give.length}{logical; if \code{TRUE} (default), indicate
    length (as \code{[1:\dots]}).}
  \item{wid}{the page width to be used.  The default is the currently
    active \code{\link{options}("width")}.}
  \item{nest.lev}{current nesting level in the recursive calls to
    \code{str}.}
  \item{indent.str}{the indentation string to use.}
  \item{\dots}{potential further arguments (required for Method/Generic reasons).}

%% The following line is swallowed, unfortunately..  fixme??
  For \code{ls.str} and \code{lsf.str}:

  \item{pos}{integer indicating \code{\link{search}} path position.}
  \item{envir}{environment to use, see \code{\link{ls}}.}
  \item{pattern}{regular expression passed to \code{\link{ls}}.  Only names
          matching \code{pattern} are considered.}
  \item{mode}{character specifying the \code{\link{mode}} of objects to
    consider.  Passed to \code{\link{exists}} and \code{\link{get}}.}
}
\value{
  \code{str} does not return anything, for efficiency reasons.
  The obvious side effect is output to the terminal.

  \code{ls.str} and \code{lsf.str} invisibly return a character vector
  of the matching names, similarly to \code{\link{ls}}.
}
\author{Martin Maechler \email{maechler@stat.math.ethz.ch} since 1990.
}
\seealso{
  \code{\link{summary}}, \code{\link{args}}.
}
\examples{
## The following examples show some of 'str' capabilities
str(1:12)
str(ls)
str(args)#- more useful than  args(args) !
data(freeny); str(freeny)
str(str)
str(.Machine, digits = 20)
str( lsfit(1:9,1:9))
str( lsfit(1:9,1:9),  max =1)
op <- options(); str(op)#- save first; otherwise internal options() is used.
need.dev <- !exists(".Device") || is.null(.Device)
if(need.dev) postscript()
str(par()); if(need.dev) graphics.off()

ch <- letters[1:12]; is.na(ch) <- 3:5
str(ch) # character NA's

nchar(longch <- paste(rep(letters,100), collapse=""))
str(longch)
str(longch, nchar.max = 52)

lsf.str()#- how do the functions look like which I am using?
ls.str(mode = "list")#- what are the structured objects I have defined?
## which base functions have "file" in their name ?
lsf.str(pos = length(search()), pattern = "file")
\dontshow{
 ##-- Some "crazy" objects
 str(array(1:5, dim=20))
 str(factor(character(0)))
 str(as.data.frame(NULL))
}
}
\keyword{print}
\keyword{documentation}
\keyword{utilities}
\eof
\name{stripchart}
\title{1-D Scatter Plots}
\alias{stripchart}
\description{
  \code{stripchart} produces one dimensional scatter plots (or dot
  plots) of the given data.  These plots are a good alternative to
  \code{\link{boxplot}}s when sample sizes are small.
}
\usage{
stripchart(x, method="overplot", jitter=0.1, offset=1/3,
           vertical=FALSE, group.names, add = FALSE, at = NULL,
           xlim=NULL, ylim=NULL, main="", ylab="", xlab="",
           log="", pch=0, col=par("fg"), cex=par("cex"))
}
\arguments{
  \item{x}{the data from which the plots are to be produced.  The data
    can be specified as a single vector, or as list of vectors, each
    corresponding to a component plot.  Alternatively a symbolic
    specification of the form \code{x ~ g} can be given, indicating the
    the observations in the vector \code{x} are to be grouped according
    to the levels of the factor \code{g}.
    \code{NA}s are allowed in the data.}
  \item{method}{the method to be used to separate coincident points.
    The default method \code{"overplot"} causes such points to be
    overplotted, but it is also possible to specify \code{"jitter"} to
    jitter the points, or \code{"stack"} have coincident points
    stacked.  The last method only makes sense for very granular data.}
  \item{jitter}{when jittering is used, \code{jitter} gives the amount
    of jittering applied.}
  \item{offset}{when stacking is used, points are stacked this many
    line-heights (symbol widths) apart.}
  \item{vertical}{when vertical is \code{TRUE} the plots are drawn
    vertically rather than the default horizontal.}
  \item{group.names}{group labels which will be printed alongside
    (or underneath) each plot.}
  \item{add}{logical, if true \emph{add} boxplot to current plot.}
  \item{at}{numeric vector giving the locations where the boxplots should
    be drawn, particularly when \code{add = TRUE};
    defaults to \code{1:n} where \code{n} is the number of boxes.}
  \item{xlim, ylim, main, ylab, xlab, log, pch, col, cex}{Graphical parameters.}
}
\details{
  Extensive examples of the use of this kind of plot can be found in
  Box, Hunter and Hunter or Seber and Wild.
}
\examples{
x <- rnorm(50)
xr<- round(x, 1)
stripchart(x) ; m <- mean(par("usr")[1:2])
text(m, 1.04, "stripchart(x, \"overplot\")")
stripchart(xr, method = "stack", add = TRUE, at = 1.2)
text(m, 1.35, "stripchart(round(x,1), \"stack\")")
stripchart(xr, method = "jitter", add = TRUE, at = 0.7)
text(m, 0.85, "stripchart(round(x,1), \"jitter\")")

data(OrchardSprays)
with(OrchardSprays,
     stripchart(decrease ~ treatment,
                main = "stripchart(Orchardsprays)", ylab = "decrease",
                vertical = TRUE, log = "y"))
% Fixme: ylab should have a non-""  default !

with(OrchardSprays,
     stripchart(decrease ~ treatment, at = c(1:8)^2,
                main = "stripchart(Orchardsprays)", ylab = "decrease",
                vertical = TRUE, log = "y"))
}
\keyword{hplot}
\eof
\name{strptime}
\alias{format.POSIXct}
\alias{format.POSIXlt}
\alias{strftime}
\alias{strptime}
\alias{as.character.POSIXt}
\alias{ISOdatetime}
\alias{ISOdate}
\title{Date-time Conversion Functions to and from Character}
\description{
  Functions to convert between character representations and objects of
  classes \code{"POSIXlt"} and \code{"POSIXct"} representing calendar
  dates and times.
}
\usage{
\method{format}{POSIXct}(x, format = "", tz = "", usetz = FALSE, \dots)
\method{format}{POSIXlt}(x, format = "", usetz = FALSE, \dots)

\method{as.character}{POSIXt}(x, \dots)

strftime(x, format="", usetz = FALSE, \dots)
strptime(x, format)

ISOdatetime(year, month, day, hour, min, sec, tz = "")
ISOdate(year, month, day, hour = 12, min = 0, sec = 0, tz = "GMT")
}
\arguments{
  \item{x}{An object to be converted.}
  \item{tz}{A timezone specification to be used for the conversion.
    System-specific, but \code{""} is the current time zone, and
    \code{"GMT"} is UTC.}
  \item{format}{A character string.  The default is
    \code{"\%Y-\%m-\%d \%H:\%M:\%S"} if any component has a time
    component which is not midnight, and \code{"\%Y-\%m-\%d"}
    otherwise.}
  \item{\dots}{Further arguments to be passed from or to other methods.}
  \item{usetz}{logical.  Should the timezone be appended to the output?
    This is used in printing time, and as a workaround for problems with
    using \code{"\%Z"} on most Linux systems.}
  \item{year, month, day}{numerical values to specify a day.}
  \item{hour, min, sec}{numerical values for a time within a day.}
}
\details{
  \code{strftime} is an alias for \code{format.POSIXlt}, and
  \code{format.POSIXct} first converts to class \code{"POSIXct"} by
  calling \code{\link{as.POSIXct}}. Note that only that conversion
  depends on the time zone.

  The usual vector re-cycling rules are applied to \code{x} and
  \code{format} so the answer will be of length that of the longer of the
  vectors.
  
  Locale-specific conversions to and from character strings are used
  where appropriate and available.  This affects the names of the days
  and months, the AM/PM indicator (if used) and the separators in
  formats such as \code{\%x} and \code{\%X}.

  The details of the formats are system-specific, but the following are
  defined by the POSIX standard for \code{strftime} and are likely to be
  widely available.  Any character in the format string other than
  the \code{\%} escapes is interpreted literally (and \code{\%\%} gives
  \code{\%}).
  \describe{
    \item{\code{\%a}}{Abbreviated weekday name.}
    \item{\code{\%A}}{Full weekday name.}
    \item{\code{\%b}}{Abbreviated month name.}
    \item{\code{\%B}}{Full month name.}
    \item{\code{\%c}}{Date and time, locale-specific.}
    \item{\code{\%d}}{Day of the month as decimal number (01--31).}
    \item{\code{\%H}}{Hours as decimal number (00--23).}
    \item{\code{\%I}}{Hours as decimal number (01--12).}
    \item{\code{\%j}}{Day of year as decimal number (001--366).}
    \item{\code{\%m}}{Month as decimal number (01--12).}
    \item{\code{\%M}}{Minute as decimal number (00--59).}
    \item{\code{\%p}}{AM/PM indicator in the locale.  Used in
      conjuction with \code{\%I} and \bold{not} with \code{\%H}.}
    \item{\code{\%S}}{Second as decimal number (00--61), allowing for
      up to two leap-seconds.}
    \item{\code{\%U}}{Week of the year as decimal number (00--53) using
      the first Sunday as day 1 of week 1.}
    \item{\code{\%w}}{Weekday as decimal number (0--6, Sunday is 0).}
    \item{\code{\%W}}{Week of the year as decimal number (00--53) using
      the first Monday as day 1 of week 1.}
    \item{\code{\%x}}{Date, locale-specific.}
    \item{\code{\%X}}{Time, locale-specific.}
    \item{\code{\%y}}{Year without century (00--99). If you use this on
      input, which century you get is system-specific.  So don't!  Often
      values up to 69 are prefixed by 20 and 70--99 by 19.}
    \item{\code{\%Y}}{Year with century.}
    \item{\code{\%Z}}{(output only.) Time zone as a character
      string (empty if not available).  Note: do not use this on Linux
      unless the \code{TZ} environment variable is set.}
  }
  Where leading zeros are shown they will be used on output but are
  optional on input.

  \code{ISOdatetime} and \code{ISOdate} are convenience wrappers for
  \code{strptime}, that differ only in their defaults.
}
\value{
  The \code{format} methods and \code{strftime} return character vectors
  representing the time.

  \code{strptime} turns character representations into an object of
  class \code{"POSIXlt"}.

  \code{ISOdatetime} and \code{ISOdate} return an object of class
  \code{"POSIXct"}.
}
\note{
  The default formats follow the rules of the ISO 8601 international
  standard which expresses a day as \code{"2001-02-03"} and a time as
  \code{"14:01:02"} using leading zeroes as here.  The ISO form uses no
  space to separate dates and times.

  If the date string does not specify the date completely, the returned
  answer may be system-specific.  The most common behaviour is to assume
  that unspecified seconds, minutes or hours are zero, and a missing
  year, month or day is the current one.

  If the timezone specified is invalid on your system, what happens is
  system-specific but it will probably be ignored.

  OS facilities will probably not print years before 1CE (aka 1AD)
  correctly.
}
\references{
  International Organization for Standardization (1988, 1997, \dots)
  \emph{ISO 8601. Data elements and interchange formats --
    Information interchange -- Representation of dates and times.}
  The 1997 version is available on-line at
  \url{ftp://ftp.qsl.net/pub/g1smd/8601v03.pdf}
}
\seealso{
  \link{DateTimeClasses} for details of the date-time classes;
  \code{\link{locales}} to query or set a locale.
  
  Your system's help pages on \code{strftime} and \code{strptime} to
  see how to specify their formats.
}
\examples{
## locale-specific version of date()
format(Sys.time(), "\%a \%b \%d \%X \%Y")
## we would include the timezone as in
## format(Sys.time(), "\%a \%b \%d \%X \%Y \%Z")
## but this crashes some Linux systems

## read in date info in format 'ddmmmyyyy'
## This will give NA(s) in some locales; setting the C locale
## as in the commented lines will overcome this on most systems.
## lct <- Sys.getlocale("LC_TIME"); Sys.setlocale("LC_TIME", "C")
x <- c("1jan1960", "2jan1960", "31mar1960", "30jul1960")
z <- strptime(x, "\%d\%b\%Y")
## Sys.setlocale("LC_TIME", lct)
z

## read in date/time info in format 'm/d/y h:m:s'
dates <- c("02/27/92", "02/27/92", "01/14/92",
           "02/28/92", "02/01/92")
times <- c("23:03:20", "22:29:56", "01:03:30",
           "18:21:03", "16:56:26")
x <- paste(dates, times)
z <- strptime(x, "\%m/\%d/\%y \%H:\%M:\%S")
z
}
\keyword{utilities}
\keyword{chron}
\eof
\name{strsplit}
\title{Split the Elements of a Character Vector}
\usage{strsplit(x, split, extended = TRUE)}
\alias{strsplit}
\description{
  Split the elements of a character vector \code{x} into substrings
  according to the presence of substring \code{split} within them.
}
\arguments{
  \item{x}{character vector, to be split.}
  \item{split}{character vector containing a regular expression to use
    as \dQuote{split}.  If empty matches occur, in particular if \code{split}
    has length 0, \code{x} is split into single characters.  If
    \code{split} has length greater than 1, it is re-cycled along \code{x}.}
  \item{extended}{if \code{TRUE}, extended regular expression matching
    is used, and if \code{FALSE} basic regular expressions are used.}
}
\value{
  A list of length \code{length(x)} the \code{i}-th element of which
  contains the vector of splits of \code{x[i]}.
}
\seealso{
  \code{\link{paste}} for the reverse,
  \code{\link{grep}} and \code{\link{sub}} for string search and
  manipulation; further \code{\link{nchar}}, \code{\link{substr}}.
}
\examples{
noquote(strsplit("A text I want to display with spaces", NULL)[[1]])

x <- c(as = "asfef", qu = "qwerty", "yuiop[", "b", "stuff.blah.yech")
# split x on the letter e
strsplit(x,"e")

unlist(strsplit("a.b.c", "."))
## [1] "" "" "" "" ""
## Note that 'split' is a regexp!
## If you really want to split on '.', use
unlist(strsplit("a.b.c", "\\\\."))
## [1] "a" "b" "c"

## a useful function: rev() for strings
strReverse <- function(x)
	sapply(lapply(strsplit(x,NULL), rev), paste, collapse="")
strReverse(c("abc", "Statistics"))

a <- readLines(file.path(R.home(),"AUTHORS"))[-(1:8)]
a <- a[(0:2)-length(a)]
sub("\t.*","", a)
strReverse(sub(" .*","", a))
}
\keyword{character}
\eof
\name{structure}
\title{Attribute Specification}
\usage{
structure(.Data, \dots)
}
\alias{structure}
\arguments{
  \item{.Data}{an object which will have
    various attributes attached to it.}
  \item{\dots}{attributes, specified in \code{tag=value}
    form, which will be attached to data.}
}
\description{
  \code{structure} returns the given object with its attributes set.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
structure(1:6, dim = 2:3)
}
\keyword{attribute}
\keyword{manip}
\eof
\name{strwidth}
\title{Plotting Dimensions of Character Strings and Math Expressions}
\usage{
strwidth(s, units = "user", cex = NULL)
strheight(s, units = "user", cex = NULL)
}
\alias{strwidth}
\alias{strheight}
\arguments{
  \item{s}{character vector or \code{\link{expression}}s whose string
    widths in plotting units are to be determined.  An attempt is made
    to coerce other vectors to character, and other language objects
    to expressions.}
  \item{units}{character indicating in which units \code{s} is measured;
    should be one of \code{"user"}, \code{"inches"}, \code{"figure"};
    partial matching is performed.}
  \item{cex}{character expansion to which is applies.  By default, the
    current \code{par("cex")} is used.}
}
\description{
  These functions compute the width or height, respectively, of the
  given strings or mathematical expressions \code{s[i]} on
  the current plotting device in \emph{user} coordinates, \emph{inches}
  or as fraction of the figure width \code{par("fin")}.
}
\value{
  Numeric vector with the same length as \code{s}, giving the
  width or height for each \code{s[i]}.  \code{NA} strings are given
  width and height 0 (as they are not plotted).
}
\seealso{
  \code{\link{text}}, \code{\link{nchar}}
}
\examples{
str.ex <- c("W","w","I",".","WwI.")
op <- par(pty='s'); plot(1:100,1:100, type="n")
sw <- strwidth(str.ex); sw
all.equal(sum(sw[1:4]), sw[5])#- since the last string contains the others

sw.i <- strwidth(str.ex, "inches"); 25.4 * sw.i # width in [mm]
unique(sw / sw.i)
# constant factor: 1 value
mean(sw.i / strwidth(str.ex, "fig")) / par('fin')[1] # = 1: are the same

## See how letters fall in classes -- depending on graphics device and font!
all.lett <- c(letters, LETTERS)
shL <- strheight(all.lett, units = "inches") * 72 # 'big points'
table(shL) # all have same heights ...
mean(shL)/par("cin")[2] # around 0.6

(swL <- strwidth(all.lett, units="inches") * 72) # 'big points'
split(all.lett, factor(round(swL, 2)))

sumex <- expression(sum(x[i], i=1,n), e^{i * pi} == -1)
strwidth(sumex)
strheight(sumex)

par(op)#- reset to previous setting
}
\keyword{dplot}
\keyword{character}
\eof
\name{strwrap}
\alias{strwrap}
\title{Wrap Character Strings to Format Paragraphs}
\description{
  Each character string in the input is first split into paragraphs (on
  lines containing whitespace only).  The paragraphs are then formatted
  by breaking lines at word boundaries.  The target columns for wrapping
  lines and the indentation of the first and all subsequent lines of a
  paragraph can be controlled independently.
}
\usage{
strwrap(x, width = 0.9 * getOption("width"), indent = 0, exdent = 0,
        prefix = "", simplify = TRUE)
}
\arguments{
  \item{x}{a character vector}
  \item{width}{a positive integer giving the target column for wrapping
    lines in the output.}
  \item{indent}{a non-negative integer giving the indentation of the
    first line in a paragraph.}
  \item{exdent}{a non-negative integer specifying the indentation of
    subsequent lines in paragraphs.}
  \item{prefix}{a character string to be used as prefix for each line.}
  \item{simplify}{a logical.  If \code{TRUE}, the result is a single
    character vector of line text; otherwise, it is a list of the same
    length as \code{x} the elements of which are character vectors of
    line text obtained from the corresponding element of \code{x}.
    (Hence, the result in the former case is obtained by unlisting that
    of the latter.)}
}
\details{
  Whitespace in the input is destroyed.  Double spaces after periods
  (thought as representing sentence ends) are preserved.  Currently, it
  possible sentence ends at line breaks are not considerd specially.
  
  Indentation is relative to the number of characters in the prefix
  string.
}
\examples{
## Read in file 'THANKS'.
x <- paste(readLines(file.path(R.home(), "THANKS")), collapse = "\n")
## Split into paragraphs and remove the first three ones
x <- unlist(strsplit(x, "\n[ \t\n]*\n"))[-(1:3)]
## Join the rest
x <- paste(x, collapse = "\n\n")
## Now for some fun:
writeLines(strwrap(x, width = 60))
writeLines(strwrap(x, width = 60, indent = 5))
writeLines(strwrap(x, width = 60, exdent = 5))
writeLines(strwrap(x, prefix = "THANKS> "))
}
\keyword{character}
\eof
\name{subset}
\alias{subset}
\alias{subset.default}
\alias{subset.data.frame}
\title{Subsetting Vectors and Data Frames}
\description{
  Return subsets of vectors or data frames which meet conditions.
}
\usage{
subset(x, \dots)

\method{subset}{default}(x, subset, \dots)

\method{subset}{data.frame}(x, subset, select, \dots)
}
\arguments{
  \item{x}{object to be subsetted.}
  \item{subset}{logical expression.}
  \item{select}{expression, indicating columns to select from a
    data frame.}
  \item{\dots}{further arguments to be passed to or from other methods.}
}
\details{
  For ordinary vectors, the result is simply
  \code{x[subset & !is.na(subset)]}.

  For data frames, the \code{subset} argument works similarly on the
  rows.  Note that \code{subset} will be evaluated in the data frame, so
  columns can be referred to (by name) as variables.

  The \code{select} argument exists only for the method for data frames.
  It works by
  first replacing names in the selection expression with the
  corresponding column numbers in the data frame and then using the
  resulting integer vector to index the columns.  This allows the use
  of the standard indexing conventions so that for example ranges of
  columns can be specified easily.
}
\value{
  An object similar to \code{x} contain just the selected elements (for
  a vector), rows and columns (for a data frame), and so on.
}
\author{Peter Dalgaard}
\seealso{
  \code{\link{[}}, % = ./Extract.Rd
  \code{\link{transform}}
}
\examples{
data(airquality)
subset(airquality, Temp > 80, select = c(Ozone, Temp))
subset(airquality, Day == 1, select = -Temp)
subset(airquality, select = Ozone:Wind)

with(airquality, subset(Ozone, Temp > 80))
}
\keyword{manip}
\eof
\name{substitute}
\title{Substituting and Quoting Expressions}
\usage{
substitute(expr, env=<<see below>>)
quote(expr)
}
\alias{substitute}
\alias{quote}
\description{
  \code{substitute} returns the parse tree for the (unevaluated)
  expression \code{expr}, substituting any variables bound in
  \code{env}.

  \code{quote} simply returns its argument. The argument is not evaluated
  and can be any R expression.
}
\arguments{
  \item{expr}{Any syntactically valid \R expression}
  \item{env}{An environment or a list object. Defaults to the
    current evaluation environment.}
}
\details{
  The typical use of \code{substitute} is to create informative labels
  for data sets and plots.
  The \code{myplot} example below shows a simple use of this facility.
  It uses the functions \code{\link{deparse}} and \code{substitute}
  to create labels for a plot which are character string versions
  of the actual arguments to the function \code{myplot}.

  Substitution takes place by examining each component of the parse tree
  as follows: If it is not a bound symbol in \code{env}, it is
  unchanged. If it is a promise object, i.e., a formal argument to a
  function or explicitly created using \code{\link{delay}()}, the expression
  slot of the promise replaces the symbol. If it is an ordinary
  variable, its value is substituted, unless \code{env} is
  \code{\link{.GlobalEnv}} in which case the symbol is left unchanged.
}
\value{
  The \code{\link{mode}} of the result is generally \code{"call"} but
  may in principle be any type. In particular, single-variable
  expressions have mode \code{"name"} and constants have the
  appropriate base mode.
}
\note{
  Substitute works on a purely lexical basis. There is no guarantee
  that the resulting expression makes any sense.

  Substituting and quoting often causes confusion when the argument is
  \code{expression(\dots)}. The result is a call to the
  \code{\link{expression}} constructor function and needs to be evaluated
  with \code{\link{eval}} to give the actual expression object.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{missing}} for argument \dQuote{missingness},
  \code{\link{bquote}} for partial substitution,
  \code{\link{sQuote}} and \code{\link{dQuote}} for adding quotation
  marks to strings.
}
\examples{
(s.e <- substitute(expression(a + b), list(a = 1)))  #> expression(1 + b)
(s.s <- substitute( a + b,            list(a = 1)))  #> 1 + b
c(mode(s.e), typeof(s.e)) #  "call", "language"
c(mode(s.s), typeof(s.s)) #   (the same)
# but:
(e.s.e <- eval(s.e))          #>  expression(1 + b)
c(mode(e.s.e), typeof(e.s.e)) #  "expression", "expression"

substitute(x <- x + 1, list(x=1)) # nonsense

myplot <- function(x, y)
    plot(x, y, xlab=deparse(substitute(x)),
         ylab=deparse(substitute(y)))

## Simple examples about lazy evaluation, etc:

f1 <- function(x, y = x)             { x <- x + 1; y }
s1 <- function(x, y = substitute(x)) { x <- x + 1; y }
s2 <- function(x, y) { if(missing(y)) y <- substitute(x); x <- x + 1; y }
a <- 10
f1(a)# 11
s1(a)# 11
s2(a)# a
typeof(s2(a))# "symbol"
}
\keyword{programming}
\keyword{data}
\eof
\name{substr}
\alias{substr}
\alias{substring}
\alias{substr<-}
\alias{substring<-}
\title{Substrings of a Character Vector}
\usage{
substr(x, start, stop)
substring(text, first, last = 1000000)
substr(x, start, stop) <- value
substring(text, first, last = 1000000) <- value
}
\arguments{
  \item{x, text}{a character vector}
  \item{start, first}{integer. The first element to be replaced.}
  \item{stop, last}{integer. The last element to be replaced.}
  \item{value}{a character vector, recycled if necessary.}
}
\description{
  Extract or replace substrings in a character vector.
}
\value{
  For \code{substr}, a character vector of the same length as \code{x}.

  For \code{substring}, a character vector of length the longest of the
  arguments.
}
\details{
  \code{substring} is compatible with S, with \code{first} and
  \code{last} instead of \code{start} and \code{stop}.
  For vector arguments, it expands the arguments cyclically to the
  length of the longest.

  When extracting, if \code{start} is larger than the string length then
  \code{""} is returned.

  For the replacement functions, if \code{start} is larger than the
  string length then no replacement is done.  If the portion to be
  replaced is longer than the replacement string, then only the
  portion the length of the string is replaced.
}
\note{
  The S4 version of \code{substring<-} ignores \code{last}; this version
  does not.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole. (\code{substring}.)
}
\seealso{
 \code{\link{strsplit}}, \code{\link{paste}}, \code{\link{nchar}}.
}
\examples{
substr("abcdef",2,4)
substring("abcdef",1:6,1:6)
## strsplit is more efficient ...

substr(rep("abcdef",4),1:4,4:5)
x <- c("asfef", "qwerty", "yuiop[", "b", "stuff.blah.yech")
substr(x, 2, 5)
substring(x, 2, 4:6)

substring(x, 2) <- c("..", "+++")
x
}
\keyword{character}
\eof
\name{sum}
\title{Sum of Vector Elements}
\usage{
sum(\dots, na.rm=FALSE)
}
\alias{sum}
\description{
  \code{sum} returns the sum of all the values
  present in its arguments.
  If \code{na.rm} is \code{FALSE} an \code{NA}
  value in any of the arguments will cause
  a value of \code{NA} to be returned, otherwise
  \code{NA} values are ignored.
}
\arguments{
  \item{\dots}{numeric or complex vectors.}
  \item{na.rm}{logical. Should missing values be removed?}
}
\value{
  The sum. If all of \code{\dots} are of type integer, then so is the
  sum, and in that case the result will be \code{NA} (with a warning)
  if integer overflow occurs.

  NB: the sum of an empty set is zero, by definition.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\keyword{arith}
\eof
\name{summary}
\alias{summary}
\alias{summary.default}
\alias{summary.data.frame}
\alias{summary.factor}
\alias{summary.matrix}
\title{Object Summaries}
\description{
  \code{summary} is a generic function used to produce result summaries
  of the results of various model fitting functions.  The function
  invokes particular \code{\link{methods}} which depend on the
  \code{\link[base]{class}} of the first argument.
}
\usage{
summary(object, \dots)

\method{summary}{default}(object, \dots, digits = max(3, getOption("digits")-3))
\method{summary}{data.frame}(object, maxsum = 7,
       digits = max(3, getOption("digits")-3), \dots)
\method{summary}{factor}(object, maxsum = 100, \dots)
\method{summary}{matrix}(object, \dots)
}
\arguments{
  \item{object}{an object for which a summary is desired.}
  \item{maxsum}{integer, indicating how many levels should be shown for
    \code{\link{factor}}s.}
  \item{digits}{integer, used for number formatting with
    \code{\link{signif}()} (for \code{summary.default}) or
    \code{\link{format}()} (for \code{summary.data.frame}).}
  \item{\dots}{additional arguments affecting the summary produced.}
}
\details{
    For \code{\link{factor}}s, the frequency of the first \code{maxsum - 1}
    most frequent levels is shown, where the less frequent levels are
    summarized in \code{"(Others)"} (resulting in \code{maxsum} frequencies).

    The functions \code{summary.lm} and \code{summary.glm} are examples
    of particular methods which summarise the results produced by
    \code{\link{lm}} and \code{\link{glm}}.
}
\value{
    The form of the value returned by \code{summary} depends on the
    class of its argument.  See the documentation of the particular
    methods for details of what is produced by that method.
}
\seealso{
  \code{\link{anova}},
  \code{\link{summary.glm}},
  \code{\link{summary.lm}}.
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S}.
  Wadsworth \& Brooks/Cole.
}
\examples{
data(attenu)
summary(attenu, digits = 4) #-> summary.data.frame(...), default precision
summary(attenu $ station, maxsum = 20) #-> summary.factor(...)

lst <- unclass(attenu$station) > 20 # logical with NAs
## summary.default() for logicals -- different from *.factor:
summary(lst)
summary(as.factor(lst))
}
\keyword{methods}
\eof
\name{summary.aov}
\alias{summary.aov}
\alias{summary.aovlist}
\alias{print.summary.aov}
\alias{print.summary.aovlist}
\title{Summarize an Analysis of Variance Model}
\usage{
\method{summary}{aov}(object, intercept = FALSE, split,
         expand.split = TRUE, keep.zero.df = TRUE, \dots)

\method{summary}{aovlist}(object, \dots)
}
\arguments{
  \item{object}{An object of class \code{"aov"} or \code{"aovlist"}.}
  \item{intercept}{logical: should intercept terms be included?}
  \item{split}{an optional named list, with names corresponding to terms
    in the model.  Each component is itself a list with integer
    components giving contrasts whose contributions are to be summed.}
  \item{expand.split}{logical: should the split apply also to
    interactions involving the factor?}
  \item{keep.zero.df}{logical: should terms with no degrees of freedom
    be included?}
  \item{\dots}{Arguments to be passed to or from other methods,
    for \code{summary.aovlist} including those for \code{summary.aov}.}
}
\description{
  Summarize an analysis of variance model.
}
\value{
  An object of class \code{c("summary.aov", "listof")} or
  \code{"summary.aovlist"} respectively.
}
\note{
  The use of \code{expand.split = TRUE} is little tested: it is always
  possible to set it to \code{FALSE} and specify exactly all
  the splits required.
}
\seealso{
  \code{\link{aov}}, \code{\link{summary}}, \code{\link{model.tables}},
  \code{\link{TukeyHSD}}
}
\examples{
## From Venables and Ripley (2002) p.165.
N <- c(0,1,0,1,1,1,0,0,0,1,1,0,1,1,0,0,1,0,1,0,1,1,0,0)
P <- c(1,1,0,0,0,1,0,1,1,1,0,0,0,1,0,1,1,0,0,1,0,1,1,0)
K <- c(1,0,0,1,0,1,1,0,0,1,0,1,0,1,1,0,0,0,1,1,1,0,1,0)
yield <- c(49.5,62.8,46.8,57.0,59.8,58.5,55.5,56.0,62.8,55.8,69.5,55.0,
           62.0,48.8,45.5,44.2,52.0,51.5,49.8,48.8,57.2,59.0,53.2,56.0)
npk <- data.frame(block=gl(6,4), N=factor(N), P=factor(P),
                  K=factor(K), yield=yield)

( npk.aov <- aov(yield ~ block + N*P*K, npk) )
summary(npk.aov)
coefficients(npk.aov)

# Cochran and Cox (1957, p.164)
# 3x3 factorial with ordered factors, each is average of 12. 
CC <- data.frame(
    y = c(449, 413, 326, 409, 358, 291, 341, 278, 312)/12,
    P = ordered(gl(3, 3)), N = ordered(gl(3, 1, 9))
)
CC.aov <- aov(y ~ N * P, data = CC , weights = rep(12, 9))
summary(CC.aov)

# Split both main effects into linear and quadratic parts.
summary(CC.aov, split = list(N = list(L = 1, Q = 2), P = list(L = 1, Q = 2)))

# Split only the interaction
summary(CC.aov, split = list("N:P" = list(L.L = 1, Q = 2:4)))

# split on just one var
summary(CC.aov, split = list(P = list(lin = 1, quad = 2)))
summary(CC.aov, split = list(P = list(lin = 1, quad = 2)),
        expand.split=FALSE)}
\keyword{models}
\keyword{regression}
\eof
\name{summary.glm}
\alias{summary.glm}
%\alias{summary.glm.null}
\alias{print.summary.glm}
%\alias{print.summary.glm.null}
\title{Summarizing Generalized Linear Model Fits}
\usage{
\method{summary}{glm}(object, dispersion = NULL, correlation = FALSE,
       symbolic.cor = FALSE, \dots)

\method{print}{summary.glm}(x, digits = max(3, getOption("digits") - 3),
      symbolic.cor = x$symbolic.cor,
      signif.stars = getOption("show.signif.stars"), \dots)
}
\arguments{
  \item{object}{an object of class \code{"glm"}, usually, a result of a
    call to \code{\link{glm}}.}
  \item{x}{an object of class \code{"summary.glm"}, usually, a result of a
    call to \code{summary.glm}.}
  \item{dispersion}{the dispersion parameter for the fitting family.
    By default it is obtained from \code{object}.}
  \item{correlation}{logical; if \code{TRUE}, the correlation matrix of
    the estimated parameters is returned and printed.}
  \item{digits}{the number of significant digits to use when printing.}
  \item{symbolic.cor}{logical. If \code{TRUE}, print the correlations in
    a symbolic form (see \code{\link{symnum}}) rather than as numbers.}
  \item{signif.stars}{logical. If \code{TRUE}, \dQuote{significance stars}
    are printed for each coefficient.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\description{
  These functions are all \code{\link{methods}} for class \code{glm} or
  \code{summary.glm} objects.
}
\details{
  \code{print.summary.glm} tries to be smart about formatting the
  coefficients, standard errors, etc. and additionally gives
  \dQuote{significance stars} if \code{signif.stars} is \code{TRUE}.

  Aliased coefficients are omitted in the returned object but (as from \R
  1.8.0) restored by the \code{print} method.

  Correlations are printed to two decimal places (or symbolically): to
  see the actual correlations print \code{summary(object)$correlation}
  directly.
}
\value{
  \code{summary.glm} returns an object of class \code{"summary.glm"}, a
  list with components

  \item{call}{the component from \code{object}.}
  \item{family}{the component from \code{object}.}
  \item{deviance}{the component from \code{object}.}
  \item{contrasts}{the component from \code{object}.}
  \item{df.residual}{the component from \code{object}.}
  \item{null.deviance}{the component from \code{object}.}
  \item{df.null}{the component from \code{object}.}
  \item{deviance.resid}{the deviance residuals:
    see \code{\link{residuals.glm}}.}
  \item{coefficients}{the matrix of coefficients, standard errors,
    z-values and p-values.  Aliased coefficients are omitted.}
  \item{aliased}{named logical vector showing if the original
    coefficients are aliased.} 
  \item{dispersion}{eother the supplied argument or the estimated
    dispersion if the latter in \code{NULL}}
  \item{df}{a 3-vector of the rank of the model and the number of
    residual degrees of freedom, plus number of non-aliased coefficients.}
  \item{cov.unscaled}{the unscaled (\code{dispersion = 1}) estimated covariance
    matrix of the estimated coefficients.}
  \item{cov.scaled}{ditto, scaled by \code{dispersion}.}
  \item{correlation}{(only if \code{correlation} is true.)  The estimated
    correlations of the estimated coefficients.}
  \item{symbolic.cor}{(only if \code{correlation} is true.)  The value
    of the argument \code{symbolic.cor}.}
}
\seealso{
  \code{\link{glm}}, \code{\link{summary}}.
}
\examples{
## --- Continuing the Example from  '?glm':%\code{\link{glm}}:
\dontshow{example("glm", echo = FALSE)}
summary(glm.D93)
}
\keyword{models}
\keyword{regression}

\eof
\name{summary.lm}
\alias{summary.lm}
% \alias{summary.lm.null}
\alias{summary.mlm}% mlm is *not* mentioned at all
\alias{print.summary.lm}
% \alias{print.summary.lm.null}
\title{Summarizing Linear Model Fits}
\usage{
\method{summary}{lm}(object, correlation = FALSE, symbolic.cor = FALSE, \dots)

\method{print}{summary.lm}(x, digits = max(3, getOption("digits") - 3),
      symbolic.cor = x$symbolic.cor,
      signif.stars = getOption("show.signif.stars"), \dots)
}
\arguments{
  \item{object}{an object of class \code{"lm"}, usually, a result of a
    call to \code{\link{lm}}.}
  \item{x}{an object of class \code{"summary.lm"}, usually, a result of a
    call to \code{summary.lm}.}
  \item{correlation}{logical; if \code{TRUE}, the correlation matrix of
    the estimated parameters is returned and printed.}
  \item{digits}{the number of significant digits to use when printing.}
  \item{symbolic.cor}{logical. If \code{TRUE}, print the correlations in
    a symbolic form (see \code{\link{symnum}}) rather than as numbers.}
  \item{signif.stars}{logical. If \code{TRUE}, \dQuote{significance stars}
    are printed for each coefficient.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\description{
\code{summary} method for class \code{"lm"}.
}
\details{
  \code{print.summary.lm} tries to be smart about formatting the
  coefficients, standard errors, etc. and additionally gives
  \dQuote{significance stars} if \code{signif.stars} is \code{TRUE}.

  Correlations are printed to two decimal places (or symbolically): to
  see the actual correlations print \code{summary(object)$correlation}
  directly.
}
\value{
  The function \code{summary.lm} computes and returns a list of summary
  statistics of the fitted linear model given in \code{object}, using
  the components (list elements) \code{"call"} and \code{"terms"}
  from its argument, plus
  \item{residuals}{the \emph{weighted} residuals, the usual residuals
    rescaled by the square root of the weights specified in the call to
    \code{lm}.}
  \item{coefficients}{a \eqn{p \times 4}{p x 4} matrix with columns for
    the estimated coefficient, its standard error, t-statistic and
    corresponding (two-sided) p-value.  Aliased coefficients are omitted.}
  \item{aliased}{named logical vector showing if the original
    coefficients are aliased.} 
  \item{sigma}{the square root of the estimated variance of the random
    error
    \deqn{\hat\sigma^2 = \frac{1}{n-p}\sum_i{R_i^2},}{%
      sigma^2 = 1/(n-p) Sum(R[i]^2),}
    where \eqn{R_i}{R[i]} is the \eqn{i}-th residual, \code{residuals[i]}.}
  \item{df}{degrees of freedom, a 3-vector \eqn{(p, n-p, p*)}, the last
    being the number of non-aliased coefficients.}
  \item{fstatistic}{(for models including non-intercept terms)
    a 3-vector with the value of the F-statistic with
    its numerator and denominator degrees of freedom.}
  \item{r.squared}{\eqn{R^2}, the \dQuote{fraction of variance explained by
    the model},
    \deqn{R^2 = 1 - \frac{\sum_i{R_i^2}}{\sum_i(y_i- y^*)^2},}{%
      R^2 = 1 - Sum(R[i]^2) / Sum((y[i]- y*)^2),}
    where \eqn{y^*}{y*} is the mean of \eqn{y_i}{y[i]} if there is an
    intercept and zero otherwise.}
  \item{adj.r.squared}{the above \eqn{R^2} statistic
    \dQuote{\emph{adjusted}}, penalizing for higher \eqn{p}.}
  \item{cov.unscaled}{a \eqn{p \times p}{p x p} matrix of (unscaled)
    covariances of the \eqn{\hat\beta_j}{coef[j]}, \eqn{j=1, \dots, p}.}
  \item{correlation}{the correlation matrix corresponding to the above
    \code{cov.unscaled}, if \code{correlation = TRUE} is specified.}
  \item{symbolic.cor}{(only if \code{correlation} is true.)  The value
    of the argument \code{symbolic.cor}.}
}
\seealso{
  The model fitting function \code{\link{lm}}, \code{\link{summary}}.
}
\examples{
\dontshow{example("lm", echo = FALSE)}
##-- Continuing the  lm(.) example:
coef(lm.D90)# the bare coefficients
sld90 <- summary(lm.D90 <- lm(weight ~ group -1))# omitting intercept
sld90
coef(sld90)# much more
}
\keyword{regression}
\keyword{models}
\eof
\name{summary.manova}
\alias{summary.manova}
\alias{print.summary.manova}
\title{Summary Method for Multivariate Analysis of Variance}
\description{
  A \code{summary} method for class \code{"manova"}.
}
\usage{
\method{summary}{manova}(object,
        test = c("Pillai", "Wilks", "Hotelling-Lawley", "Roy"),
        intercept = FALSE, \dots)
}
\arguments{
  \item{object}{An object of class \code{"manova"} or an \code{aov}
    object with multiple responses.}
  \item{test}{The name of the test statistic to be used. Partial
    matching is used so the name can be abbreviated.}
  \item{intercept}{logical. If \code{TRUE}, the intercept term is
    included in the table.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\details{
  The \code{summary.manova} method uses a multivariate test statistic
  for the summary table.  Wilks' statistic is most popular in the
  literature, but the default Pillai-Bartlett statistic is recommended
  by Hand and Taylor (1987).
}
\value{
  A list with components
  \item{SS}{A named list of sums of squares and product matrices.}
  \item{Eigenvalues}{A matrix of eigenvalues, }
  \item{stats}{A matrix of the statistics, approximate F value and
    degrees of freedom.}
}
\references{
  Krzanowski, W. J. (1988) \emph{Principles of Multivariate Analysis. A
    User's Perspective.} Oxford.

  Hand, D. J. and Taylor, C. C.  (1987)
  \emph{Multivariate Analysis of Variance and Repeated Measures.}
  Chapman and Hall.
}
\seealso{
  \code{\link{manova}}, \code{\link{aov}}
}

\examples{
## Example on producing plastic film from Krzanowski (1998, p. 381)
tear <- c(6.5, 6.2, 5.8, 6.5, 6.5, 6.9, 7.2, 6.9, 6.1, 6.3,
          6.7, 6.6, 7.2, 7.1, 6.8, 7.1, 7.0, 7.2, 7.5, 7.6)
gloss <- c(9.5, 9.9, 9.6, 9.6, 9.2, 9.1, 10.0, 9.9, 9.5, 9.4,
           9.1, 9.3, 8.3, 8.4, 8.5, 9.2, 8.8, 9.7, 10.1, 9.2)
opacity <- c(4.4, 6.4, 3.0, 4.1, 0.8, 5.7, 2.0, 3.9, 1.9, 5.7,
             2.8, 4.1, 3.8, 1.6, 3.4, 8.4, 5.2, 6.9, 2.7, 1.9)
Y <- cbind(tear, gloss, opacity)
rate <- factor(gl(2,10), labels=c("Low", "High"))
additive <- factor(gl(2, 5, len=20), labels=c("Low", "High"))

fit <- manova(Y ~ rate * additive)
summary.aov(fit)           # univariate ANOVA tables
summary(fit, test="Wilks") # ANOVA table of Wilks' lambda
}
\keyword{models}
\eof
\name{summaryRprof}
\alias{summaryRprof}
\title{Summarise Output of R Profiler}
\description{
Summarise the output of the \code{\link{Rprof}} function to show the
amount of time used by different \R functions.
}
\usage{
summaryRprof(filename = "Rprof.out", chunksize = 5000)
}
\arguments{
  \item{filename}{Name of a file produced by \code{Rprof()}}
  \item{chunksize}{Number of lines to read at a time}
}
\details{
This function is an alternative to \code{R CMD Rprof}. It provides the
convenience of an all-\R implementation but will be slower for large
files.

As the profiling output file could be larger than available memory, it
is read in blocks of \code{chunksize} lines. Increasing \code{chunksize}
will make the function run faster if sufficient memory is available.
}
\value{
  A list with components
  \item{by.self}{Timings sorted by \sQuote{self} time}
  \item{by.total}{Timings sorted by \sQuote{total} time}
  \item{sampling.time}{Total length of profiling run}
}


\seealso{
  The chapter on \dQuote{Tidying and profiling R code} in
  \dQuote{Writing \R Extensions} (see the \file{doc/manual} subdirectory
  of the \R source tree).

  \code{\link{Rprof}}
}
\examples{
\dontrun{
## Rprof() is not available on all platforms
Rprof(tmp <- tempfile())
example(glm)
Rprof()
summaryRprof(tmp)
unlink(tmp)
}
}
\keyword{utilities}
\eof
\name{sunflowerplot}
\alias{sunflowerplot}
\title{Produce a Sunflower Scatter Plot}
\description{
  Multiple points are plotted as \dQuote{sunflowers} with multiple leaves
  (\dQuote{petals}) such that overplotting is visualized instead of accidental and
  invisible.
}
\usage{
sunflowerplot(x, y = NULL, number, log = "", digits = 6,
             xlab = NULL, ylab = NULL, xlim = NULL, ylim = NULL,
             add = FALSE, rotate = FALSE,
             pch = 16, cex = 0.8, cex.fact = 1.5,
             size = 1/8, seg.col = 2, seg.lwd = 1.5, \dots)
}
\arguments{
  \item{x}{numeric vector of \code{x}-coordinates of length \code{n},
    say, or another valid plotting structure, as for
    \code{\link{plot.default}}, see also \code{\link{xy.coords}}.}
  \item{y}{numeric vector of \code{y}-coordinates of length \code{n}.}
  \item{number}{integer vector of length \code{n}. \code{number[i]} = number
    of replicates for \code{(x[i],y[i])}, may be 0.\cr
    Default: compute the exact multiplicity of the points \code{x[],y[]}.}
  \item{log}{character indicating log coordinate scale, see
    \code{\link{plot.default}}.}
  \item{digits}{when \code{number} is computed (i.e., not specified),
    \code{x} and \code{y} are rounded to \code{digits} significant
    digits before multiplicities are computes.}
  \item{xlab,ylab}{character label for x-, or y-axis, respectively.}
  \item{xlim,ylim}{\code{numeric(2)} limiting the extents of the x-,
    or y-axis.}
  \item{add}{logical; should the plot be added on a previous one ?
    Default is \code{FALSE}.}
  \item{rotate}{logical; if \code{TRUE}, randomly rotate the
    sunflowers (preventing artefacts).}
  \item{pch}{plotting character to be used for points
    (\code{number[i]==1}) and center of sunflowers.}
  \item{cex}{numeric; character size expansion of center points
    (s. \code{pch}).}
  \item{cex.fact}{numeric \emph{shrinking} factor to be used for the
    center points \emph{when there are flower leaves},
    i.e., \code{cex / cex.fact} is used for these.}
  \item{size}{of sunflower leaves in inches, 1[in] := 2.54[cm].
    Default: 1/8\", approximately 3.2mm.}
  \item{seg.col}{color to be used for the \bold{seg}ments which make the
    sunflowers leaves, see \code{\link{par}(col=)};
    \code{col = "gold"} reminds of real sunflowers.}
  \item{seg.lwd}{numeric; the line width for the leaves' segments.}
  \item{\dots}{further arguments to \code{\link{plot}} [if
    \code{add=FALSE}].}
}
\details{
  For \code{number[i]==1}, a (slightly enlarged) usual plotting symbol
  (\code{pch}) is drawn.
  For \code{number[i] > 1}, a small plotting symbol is drawn and
  \code{number[i]} equi-angular \dQuote{rays} emanate from it.

  If \code{rotate=TRUE} and \code{number[i] >= 2}, a random direction
  is chosen (instead of the y-axis) for the first ray.  The goal is to
  \code{\link{jitter}} the orientations of the sunflowers in order to prevent
  artefactual visual impressions.
}
\section{Side Effects}{
  A scatter plot is drawn with \dQuote{sunflowers} as symbols.
}
\value{
  A list with three components of same length,
  \item{x}{x coordinates}
  \item{y}{y coordinates}
  \item{number}{number}
}
\references{
  Chambers, J. M., Cleveland, W. S., Kleiner, B. and Tukey, P. A. (1983)
  \emph{Graphical Methods for Data Analysis.}  Wadsworth.

  Schilling, M. F. and Watkins, A. E. (1994)
  A suggestion for sunflower plots.
  \emph{The American Statistician}, \bold{48}, 303--305.
}
\author{
  Andreas Ruckstuhl, Werner Stahel, Martin Maechler, Tim Hesterberg,
  1989--1993.  Port to \R by Martin Maechler
  \email{maechler@stat.math.ethz.ch}.
}
\seealso{\code{\link{density}}}
\examples{
data(iris)
## 'number' is computed automatically:
sunflowerplot(iris[, 3:4])
## Imitating  Chambers et al., p.109, closely:
sunflowerplot(iris[, 3:4],cex=.2, cex.f=1, size=.035, seg.lwd=.8)

sunflowerplot(x=sort(2*round(rnorm(100))), y= round(rnorm(100),0),
             main = "Sunflower Plot of Rounded N(0,1)")

## A 'point process' {explicit 'number' argument}:
sunflowerplot(rnorm(100),rnorm(100), number=rpois(n=100,lambda=2),
                        rotate=TRUE, main="Sunflower plot")
}
\keyword{hplot}
\keyword{smooth}
\keyword{nonparametric}
\eof
\name{sunspots}
\docType{data}
\alias{sunspots}
\title{Monthly Sunspot Numbers, 1749--1983}
\description{
  Monthly mean relative sunspot numbers from 1749 to 1983.  Collected at
  Swiss Federal Observatory, Zurich until 1960, then Tokyo Astronomical
  Observatory.
}
\usage{data(sunspots)}
\format{
  A time series of monthly data from 1749 to 1983.
}
\source{
  Andrews, D. F. and Herzberg, A. M. (1985)
  \emph{Data: A Collection of Problems from Many Fields for the
    Student and Research Worker}.
  New York: Springer-Verlag.
}
\seealso{\code{\link[ts]{sunspot.month}} (package \pkg{ts}) has a
  longer (and a bit different) series.} 
\examples{
data(sunspots)
plot(sunspots, main = "sunspots data", xlab = "Year",
     ylab = "Monthly sunspot numbers")
}
\keyword{datasets}
\eof
\name{svd}
\alias{svd}
\alias{La.svd}
\title{Singular Value Decomposition of a Matrix}
\usage{
svd(x, nu = min(n, p), nv = min(n, p), LINPACK = FALSE)
La.svd(x, nu = min(n, p), nv = min(n, p), method = c("dgesdd", "dgesvd"))
}
\arguments{
  \item{x}{a matrix whose SVD decomposition is to be computed.}
  \item{nu}{the number of left  singular vectors to be computed.
    This must be one of \code{0}, \code{nrow(x)} and \code{ncol(x)},
    except for \code{method = "dgesdd"}.}
  \item{nv}{the number of right singular vectors to be computed.
    This must be one of \code{0} and \code{ncol(x)}.}
  \item{LINPACK}{logical. Should LINPACK be used (for compatibility with
    \R < 1.7.0)?}
  \item{method}{The LAPACK routine to use in the real case.}
}
\description{
  Compute the singular-value decomposition of a rectangular matrix.
}
\details{
  The singular value decomposition plays an important role in many
  statistical techniques.  \code{svd} and \code{La.svd} provide two
  slightly different interfaces.  The main functions used are
  the LAPACK routines DGESDD and ZGESVD; \code{svd(LINPACK=TRUE)}
  provides an interface to the LINPACK routine DSVDC, purely for
  backwards compatibility.
  
  \code{La.svd} provides an interface to both the LAPACK routines
  DGESVD and DGESDD.  The latter is usually substantially faster
  if singular vectors are required: see
  \url{http://www.cs.berkeley.edu/~demmel/DOE2000/Report0100.html}.
  Most benefit is seen with an optimized BLAS system.
  Using \code{method="dgesdd"} requires IEEE 754 arithmetic.  Should
  this not be supported on your platform, \code{method="dgesvd"} is
  used, with a warning.

  Computing the singular vectors is the slow part for large matrices.
}
\value{
  The SVD decomposition of the matrix as computed by LINPACK,
  \deqn{ \bold{X = U D V'},} where \eqn{\bold{U}} and \eqn{\bold{V}} are
  orthogonal, \eqn{\bold{V'}} means \emph{V transposed}, and
  \eqn{\bold{D}} is a diagonal matrix with the singular
  values \eqn{D_{ii}}{D[i,i]}.  Equivalently, \eqn{\bold{D = U' X V}},
  which is verified in the examples, below.

  The returned value is a list with components
  \item{d}{a vector containing the singular values of \code{x}.}
  \item{u}{a matrix whose columns contain the left singular vectors of
    \code{x}, present if \code{nu > 0}}
  \item{v}{a matrix whose columns contain the right singular vectors of
    \code{x}, present if \code{nv > 0}.}

  For \code{La.svd} the return value replaces \code{v} by \code{vt}, the
  (conjugated if complex) transpose of \code{v}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Dongarra, J. J., Bunch, J. R., Moler, C. B. and Stewart, G. W. (1978)
  \emph{LINPACK Users Guide.}  Philadelphia: SIAM Publications.

  Anderson. E. and ten others (1999)
  \emph{LAPACK Users' Guide}. Third Edition. SIAM.\cr
  Available on-line at
  \url{http://www.netlib.org/lapack/lug/lapack_lug.html}.
}
\seealso{
  \code{\link{eigen}}, \code{\link{qr}}.

  \code{\link{capabilities}} to test for IEEE 754 arithmetic.
}
\examples{
hilbert <- function(n) { i <- 1:n; 1 / outer(i - 1, i, "+") }
str(X <- hilbert(9)[,1:6])
str(s <- svd(X))
D <- diag(s$d)
s$u \%*\% D \%*\% t(s$v) #  X = U D V'
t(s$u) \%*\% X \%*\% s$v #  D = U' X V
}
\keyword{algebra}
\keyword{array}

\eof
\name{sweep}
\alias{sweep}
\title{Sweep out Array Summaries}
\description{
  Return an array obtained from an input array by sweeping out a summary
  statistic.
}
\usage{
sweep(x, MARGIN, STATS, FUN="-", \dots)
}
\arguments{
  \item{x}{an array.}
  \item{MARGIN}{a vector of indices giving the extents of \code{x}
    which correspond to \code{STATS}.}
  \item{STATS}{the summary statistic which is to be swept out.}
  \item{FUN}{the function to be used to carry out the sweep.  In the
    case of binary operators such as \code{"/"} etc., the function name
    must be quoted.}
  \item{\dots}{optional arguments to \code{FUN}.}
}
\value{
  An array with the same shape as \code{x}, but with the summary
  statistics swept out.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{apply}} on which \code{sweep} is based;
  \code{\link{scale}} for centering and scaling.
}
\examples{
data(attitude)
med.att <- apply(attitude, 2, median)
sweep(data.matrix(attitude), 2, med.att)# subtract the column medians
}
\keyword{array}
\keyword{iteration}
\eof
\name{swiss}
\docType{data}
\alias{swiss}
\title{Swiss Fertility and Socioeconomic Indicators (1888) Data}
\description{
  Standardized fertility measure and socio-economic indicators for each
  of 47 French-speaking provinces of Switzerland at about 1888.
}
\usage{data(swiss)}
\format{
  A data frame with 47 observations on 6 variables, \emph{each} of which
  is in percent, i.e., in \eqn{[0,100]}.

  \tabular{rll}{
    [,1] \tab Fertility \tab \eqn{I_g}{Ig}, \dQuote{common standardized
    fertility measure}\cr
    [,2] \tab Agriculture\tab \% of males involved in agriculture
    as occupation\cr
    [,3] \tab Examination\tab \% \dQuote{draftees} receiving highest mark
    on army examination\cr
    [,4] \tab Education \tab \% education beyond primary school for
    \dQuote{draftees}.\cr
    [,5] \tab Catholic \tab \% catholic (as opposed to \dQuote{protestant}).\cr
    [,6] \tab Infant.Mortality\tab live births who live less than 1
    year.
  }

  All variables but \sQuote{Fertility} give proportions of the
  population.
}
\details{
  (paraphrasing Mosteller and Tukey):

  Switzerland, in 1888, was entering a period known as the
  \dQuote{demographic transition}; i.e., its fertility was beginning to
  fall from the high level typical of underdeveloped countries.

  The data collected are for 47 French-speaking \dQuote{provinces} at
  about 1888.

  Here, all variables are scaled to \eqn{[0,100]}, where in the
  original, all but \code{"Catholic"} were scaled to \eqn{[0,1]}.
}
\source{
  Project \dQuote{16P5}, pages 549--551 in

  Mosteller, F. and Tukey, J. W. (1977)
  \emph{Data Analysis and Regression: A Second Course in Statistics}.
  Addison-Wesley, Reading Mass.

  indicating their source as
  \dQuote{Data used by permission of Franice van de Walle. Office of
  Population Research, Princeton University, 1976.  Unpublished data
  assembled under NICHD contract number No 1-HD-O-2077.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\note{
  Files for all 182 districts in 1888 and other years are available at
  \url{http://opr.princeton.edu/archive/eufert/switz.html}.

  They state that variables \code{Examination} and \code{Education}
  are averages for 1887, 1888 and 1889.
}
\examples{
data(swiss)
pairs(swiss, panel = panel.smooth, main = "swiss data",
      col = 3 + (swiss$Catholic > 50))
summary(lm(Fertility ~ . , data = swiss))
}
\keyword{datasets}
\eof
\name{switch}
\alias{switch}
\title{Select One of a List of Alternatives}
\description{
  \code{switch} evaluates \code{EXPR} and accordingly chooses one of the
  further arguments (in \code{\dots}).
}
\usage{
switch(EXPR, \dots)
}
\arguments{
  \item{EXPR}{an expression evaluating to a number or a character
    string.}
  \item{\dots}{the list of alternatives, given explicitly.}
}
\details{
  If the value of \code{EXPR} is an integer between 1 and
  \code{nargs()-1} then the corresponding element of \code{\dots} is
  evaluated and the result returned.

  If \code{EXPR} returns a character string then that string is used to
  match the names of the elements in \code{\dots}.  If there is an exact
  match then that element is evaluated and returned if there is one,
   otherwise the next element is chosen, e.g.,
  \code{switch("cc", a=1, cc=, d=2)} evaluates to \code{2}.

  In the case of no match, if there's a further argument in \code{switch}
  that one is returned, otherwise \code{NULL}.
}
\section{Warning}{
  Beware of partial matching: an alternative \code{E = foo} will match
  the first argument \code{EXPR} unless that is named. See the examples
  for good practice in naming the first argument.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
centre <- function(x, type) {
  switch(type,
        mean = mean(x),
        median = median(x),
        trimmed = mean(x, trim = .1))
}
x <- rcauchy(10)
centre(x, "mean")
centre(x, "median")
centre(x, "trimmed")

ccc <- c("b","QQ","a","A","bb")
for(ch in ccc) cat(ch,":",switch(EXPR = ch, a=1,    b=2:3),            "\n")
for(ch in ccc) cat(ch,":",switch(EXPR = ch, a=,A=1, b=2:3, "Otherwise: last"),"\n")

## Numeric EXPR don't allow an 'otherwise':
for(i in c(-1:3,9))  print(switch(i, 1,2,3,4))
}
\keyword{programming}
\eof
\name{symbols}
\alias{symbols}
\title{Draw symbols on a plot}
\description{
  This function draws symbols on a plot.  One of six symbols;
  \emph{circles}, \emph{squares}, \emph{rectangles}, \emph{stars},
  \emph{thermometers}, and \emph{boxplots}, can be plotted at a
  specified set of x and y coordinates.  Specific aspects of the
  symbols, such as relative size, can be customized by additional
  parameters.
}
\usage{
symbols(x, y = NULL, circles, squares, rectangles, stars,
        thermometers, boxplots, inches = TRUE, add = FALSE,
        fg = 1, bg = NA, xlab = NULL, ylab = NULL, main = NULL,
        xlim = NULL, ylim = NULL, \dots)
}
\arguments{
  \item{x, y}{the x and y co-ordinates for the symbols. They can be
    specified in any way which is accepted by \code{\link{xy.coords}}.}
  \item{circles}{a vector giving the radii of the circles.}
  \item{squares}{a vector giving the length of the sides of the squares.}
  \item{rectangles}{a matrix with two columns.  The first column gives
    widths and the second the heights of rectangle symbols.}
  \item{stars}{a matrix with three or more columns giving the lengths
    of the rays from the center of the stars.  \code{NA} values
    are replaced by zeroes.}
  \item{thermometers}{a matrix with three or four columns.  The first
    two columns give the width and height of the thermometer symbols.
    If there are three columns, the third is taken as a proportion.
    The thermometers are filled from their base to this proportion
    of their height.  If there are four columns, the third and fourth
    columns are taken as proportions.  The thermometers are filled
    between these two proportions of their heights.}
  \item{boxplots}{a matrix with five columns.  The first two columns
    give the width and height of the boxes, the next two columns
    give the lengths of the lower and upper whiskers and the fifth
    the proportion (with a warning if not in [0,1]) of the way up
    the box that the median line is drawn.}
  \item{inches}{If \code{inches} is \code{FALSE}, the units are taken
    to be those of the x axis.  If \code{inches} is \code{TRUE},
    the symbols are scaled so that the largest symbol is one
    inch in height.  If a number is given the symbols are scaled to
    make largest symbol this height in inches.}
  \item{add}{if \code{add} is \code{TRUE}, the symbols are added to
    an existing plot, otherwise a new plot is created.}
  \item{fg}{colors the symbols are to be drawn in (the default is
    the value of the \code{col} graphics parameter).}
  \item{bg}{if specified, the symbols are filled with this color.
    The default is to leave the symbols unfilled. }
  \item{xlab}{the x label of the plot if \code{add} is not true; this
    applies to the following arguments as well.  Defaults to the
    \code{\link{deparse}}d expression used for \code{x}.}
  \item{ylab}{the y label of the plot.}
  \item{main}{a main title for the plot.}
  \item{xlim}{numeric of length 2 giving the x limits for the plot.}
  \item{ylim}{numeric of length 2 giving the y limits for the plot.}
  \item{\dots}{graphics parameters can also be passed to this function.}
}
\details{
  Observations which have missing coordinates or missing size
  parameters are not plotted.  The exception to this is \emph{stars}.
  In that case, the length of any rays which are \code{NA} is reset
  to zero.

  Circles of radius zero are plotted at radius one pixel (which is
  device-dependent).
#ifdef windows
  On \code{\link{windows}} devices circles are plotted
  at radius at least one pixel as some Windows versions omit smaller
  circles.
#endif
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  W. S. Cleveland (1985)
  \emph{The Elements of Graphing Data.}
  Monterey, California: Wadsworth.
}
\seealso{\code{\link{stars}} for drawing \emph{stars} with a bit more
  flexibility; \code{\link{sunflowerplot}}.
}
\examples{
x <- 1:10
y <- sort(10*runif(10))
z <- runif(10)
z3 <- cbind(z, 2*runif(10), runif(10))
symbols(x, y, thermometers=cbind(.5, 1, z), inches=.5, fg = 1:10)
symbols(x, y, thermometers = z3, inches=FALSE)
text(x,y, apply(format(round(z3, dig=2)), 1, paste, collapse = ","),
     adj = c(-.2,0), cex = .75, col = "purple", xpd=NA)

data(trees)
## Note that  example(trees)  shows more sensible plots!
N <- nrow(trees)
attach(trees)
## Girth is diameter in inches
symbols(Height, Volume, circles=Girth/24, inches=FALSE,
        main="Trees' Girth")# xlab and ylab automatically
## Colors too:
palette(rainbow(N, end = 0.9))
symbols(Height, Volume, circles=Girth/16, inches=FALSE, bg = 1:N,
        fg="gray30", main="symbols(*, circles=Girth/16, bg = 1:N)")
palette("default"); detach()
}
\keyword{aplot}
\keyword{hplot}
\keyword{multivariate}
\eof
\name{symnum}
\alias{symnum}
\title{Symbolic Number Coding}
\description{
  Symbolically encode a given numeric or logical vector or array.
}
\usage{
symnum(x, cutpoints=c(0.3, 0.6, 0.8, 0.9, 0.95),
       symbols=c(" ", ".", ",", "+", "*", "B"),
       legend = length(symbols) >= 3,
       na = "?", eps = 1e-5, corr = missing(cutpoints),
       show.max = if(corr) "1", show.min = NULL,
       abbr.colnames = has.colnames,
       lower.triangular = corr & is.matrix(x),
       diag.lower.tri   = corr & !is.null(show.max))
}
\arguments{
  \item{x}{numeric or logical vector or array.}
  \item{cutpoints}{numeric vector whose values \code{cutpoints[j]}%
    \eqn{= c_j}{ == c[j]}  (\emph{after} augmentation, see \code{corr}
    below) are used for intervals.}
  \item{symbols}{character vector, one shorter than (the
    \emph{augmented}, see \code{corr} below) \code{cutpoints}.
    \code{symbols[j]}\eqn{= s_j}{ == s[j]} are used as \dQuote{code} for
    the (half open) interval \eqn{(c_j,c_{j+1}]}{(c[j], c[j+1]]}.

    For \code{logical} argument \code{x}, the default is
    \code{c(".","|")} (graphical 0 / 1 s).}
  \item{legend}{logical indicating if a \code{"legend"} attribute is
    desired.}
  \item{na}{character or logical. How \code{\link{NA}s} are coded.  If
    \code{na == FALSE}, \code{NA}s are coded invisibly, \emph{including}
    the \code{"legend"} attribute below, which otherwise mentions NA
    coding.}
  \item{eps}{absolute precision to be used at left and right boundary.}
  \item{corr}{logical.  If \code{TRUE}, \code{x} contains correlations.
    The cutpoints are augmented by \code{0} and \code{1} and
    \code{abs(x)} is coded.}
  \item{show.max}{if \code{TRUE}, or of mode \code{character}, the
    maximal cutpoint is coded especially.}
  \item{show.min}{if \code{TRUE}, or of mode \code{character}, the
    minmal cutpoint is coded especially.}
  \item{abbr.colnames}{logical, integer or \code{NULL} indicating how
    column names should be abbreviated (if there are); if \code{NULL}
    (or \code{FALSE} and \code{x} has no column names),
    the column names will all be empty, i.e., \code{""}; otherwise if
    \code{abbr.colnames} is false, they are left unchanged.}
  \item{lower.triangular}{logical.  If \code{TRUE} and \code{x} is a
    matrix, only the \emph{lower triangular} part of the matrix is coded
    as non-blank.}
  \item{diag.lower.tri}{logical.  If \code{lower.triangular} \emph{and}
    this are \code{TRUE}, the \emph{diagonal} part of the matrix is
    shown.}
}
\value{
  An atomic character object of class \code{\link{noquote}} and the same
  dimensions as \code{x}.

  If \code{legend} (\code{TRUE} by default when there more than 2 classes),
  it has an attribute \code{"legend"} containing a legend
  of the returned character codes, in the form
  \deqn{c_1 s_1 c_2 s_2 \dots s_n c_{n+1}}{% the dots are UGLY in LaTeX Math
    c[1] \sQuote{s[1]} c[2] \sQuote{s[2]} \dots \sQuote{s[n]} c_[n+1]}
  where \eqn{c_j}{c[j]}\code{ = cutpoints[j]} and
  \eqn{s_j}{s[j]}\code{ = symbols[j]}.
}
\author{Martin Maechler \email{maechler@stat.math.ethz.ch}}
\seealso{\code{\link{as.character}}}
\examples{
ii <- 0:8; names(ii) <- ii
symnum(ii, cut= 2*(0:4), sym = c(".", "-", "+", "$"))
symnum(ii, cut= 2*(0:4), sym = c(".", "-", "+", "$"), show.max=TRUE)

symnum(1:12 \%\% 3 == 0)# use for logical

##-- Symbolic correlation matrices:
data(attitude)
symnum(cor(attitude), diag = FALSE)
symnum(cor(attitude), abbr.= NULL)
symnum(cor(attitude), abbr.= FALSE)
symnum(cor(attitude), abbr.= 2)

symnum(cor(rbind(1, rnorm(25), rnorm(25)^2)))
symnum(cor(matrix(rexp(30, 1), 5, 18))) # <<-- PATTERN ! --
symnum(cm1 <- cor(matrix(rnorm(90) ,  5, 18))) # < White Noise SMALL n
symnum(cm1, diag=FALSE)
symnum(cm2 <- cor(matrix(rnorm(900), 50, 18))) # < White Noise "BIG" n
symnum(cm2, lower=FALSE)

## NA's:
Cm <- cor(matrix(rnorm(60),  10, 6)); Cm[c(3,6), 2] <- NA
symnum(Cm, show.max=NULL)

## Graphical P-values (aka "significance stars"):
pval <- rev(sort(c(outer(1:6, 10^-(1:3)))))
symp <- symnum(pval, corr=FALSE,
               cutpoints = c(0,  .001,.01,.05, .1, 1),
               symbols = c("***","**","*","."," "))
noquote(cbind(P.val = format(pval), Signif= symp))
}
\keyword{utilities}
\keyword{character}
\eof
\name{sys.parent}
\alias{sys.parent}
\alias{sys.call}
\alias{sys.calls}
\alias{sys.frame}
\alias{sys.frames}
\alias{sys.nframe}
\alias{sys.function}
\alias{sys.parents}
\alias{sys.on.exit}
\alias{sys.status}
\alias{parent.frame}
\title{Functions to Access the Function Call Stack}
\description{
  These functions provide access to \code{\link{environment}}s
  (\dQuote{frames} in S terminology) associated with functions further
  up the calling stack.
}
\usage{
sys.call(which = 0)
sys.frame(which = 0)
sys.nframe()
sys.function(n = 0)
sys.parent(n = 1)

sys.calls()
sys.frames()
sys.parents()
sys.on.exit()
sys.status()
parent.frame(n = 1)
}
\arguments{
  \item{which}{the frame number if non-negative, the number of generations
    to go back if negative. (See the Details section.)}
  \item{n}{the number of frame generations to go back.}
}
\details{
  \code{\link{.GlobalEnv}} is given number 0 in the list of frames.
  Each subsequent function evaluation increases the frame stack by 1
  and the environment for evaluation of that function is returned by
  \code{sys.frame} with the appropriate index.

  The parent of a function evaluation is the environment in which the
  function was called. It is not necessarily numbered one less than the frame
  number of the current evaluation, nor is it the environment within
  which the function was defined.  \code{sys.parent} returns the number
  of the parent frame if \code{n} is 1 (the default), the grandparent if
  \code{n} is 2, and so on. \code{sys.frame} returns the environment
  associated with a given frame number.

  \code{sys.call} and \code{sys.frame} both accept integer values
  for the argument \code{which}.  Non-negative values of
  \code{which} are normal frame numbers whereas negative values are counted
  back from the frame number of the current evaluation.

  \code{sys.nframe} returns the number of the current frame in that
  list. \code{sys.function} gives the definition of the function
  curently being evaluated in the frame \code{n} generations back.
  
  \code{sys.frames} gives a list of all the active frames and
  \code{sys.parents} gives the indices of the parent frames of each
  of the frames.
  
  Notice that even though the \code{sys.}\emph{xxx} functions (except
  \code{sys.status}) are
  interpreted, their contexts are not counted nor are they reported.
  There is no access to them.

  \code{sys.status()} returns a list with components \code{sys.calls},
  \code{sys.parents} and \code{sys.frames}.

  \code{sys.on.exit()} retrieves the expression stored for use by
  \code{\link{on.exit}} in the function currently being evaluated.
  (Note that this differs from S, which returns a list of expressions
  for the current frame and its parents.)

  \code{parent.frame(n)} is a convenient shorthand for
  \code{sys.frame(sys.parent(n))} (implemented slightly more efficiently).
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole. (not \code{parent.frame}.)
}
\seealso{
  \code{\link{eval}} for the usage of \code{sys.frame} and \code{parent.frame}.
}
\examples{
ff <- function(x) gg(x)
gg <- function(y) sys.status()
str(ff(1))

gg <- function(y) {
    ggg <- function() {
        cat("current frame is", sys.nframe(), "\n")
        cat("parents are", sys.parents(), "\n")
        print(sys.function(0)) # ggg
        print(sys.function(2)) # gg
    }
    if(y > 0) gg(y-1) else ggg()
}
gg(3)

t1 <- function() {
  aa <- "here"
  t2 <- function() {
    ## in frame 2 here
    cat("current frame is", sys.nframe(), "\n")
    str(sys.calls()) ## list with two components t1() and t2()
    cat("parents are frame nos", sys.parents(), "\n") ## 0 1
    print(ls(envir=sys.frame(-1))) ## [1] "aa" "t2"
    invisible()
  }
  t2()
}
t1()

test.sys.on.exit <- function() {
  on.exit(print(1))
  ex <- sys.on.exit()
  str(ex)
  cat("exiting...\n")
}
test.sys.on.exit()
## gives 'language print(1)', prints 1 on exit
}
\keyword{programming}
\keyword{data}
\eof
\name{sys.source}
\alias{sys.source}
\title{Parse and Evaluate Expressions from a File}
\description{
  Parses expressions in the given file, and then successively evaluates
  them in the specified environment.
}
\usage{
sys.source(file, envir = NULL, chdir = FALSE,
           keep.source = getOption("keep.source.pkgs"))
}
\arguments{
  \item{file}{a character string naming the file to be read from}
  \item{envir}{an \R object specifying the environment in which the
    expressions are to be evaluated.  May also be a list or an integer.
    The default value \code{NULL} corresponds to evaluation in the base
    environment.  This is probably not what you want; you should
    typically supply an explicit \code{envir} argument.}
  \item{chdir}{logical; if \code{TRUE}, the \R working directory is
    changed to the directory containing \code{file} for evaluating.}
  \item{keep.source}{logical.  If \code{TRUE}, functions \dQuote{keep
      their source} including comments, see
    \code{\link{options}(keep.source = *)} for more details.}
}
\details{
  For large files, \code{keep.source = FALSE} may save quite a bit of
  memory.
%%FIXME:  the following paragraph should be somewhere it's likely to be seen
  In order for the code being evaluated to use the correct environment
  (for example, in global assignments), source code in packages should
  call 
  \code{\link{topenv}}(), which will return the namespace, if any, the
  environment set up by \code{sys.source}, or the global environment
  if a saved image is being used.
}
\seealso{\code{\link{source}}, and \code{\link{library}} which uses
  \code{sys.source}.
}
\keyword{file}
\keyword{utilities}
\eof
\name{system.file}
\title{Find Names of R System Files}
\usage{
system.file(\dots, package = "base", lib.loc = NULL)
}
\alias{system.file}
\arguments{
  \item{\dots}{character strings, specifying subdirectory and file(s)
    within some package.  The default, none, returns the
    root of the package.  Wildcards are not supported.}
  \item{package}{a character string with the name of a single package.
    An error occurs if more than one package name is given.}
  \item{lib.loc}{a character vector with path names of \R libraries, or
    \code{NULL}.  The default value of \code{NULL} corresponds to all
    libraries currently known.  If the default is used, the loaded
    packages are searched before the libraries.}
}
\description{
  Finds the full file names of files in packages etc.
}
\value{
  A character vector of positive length, containing the file names
  that matched \code{\dots}, or the empty string, \code{""}, if none
  matched.  If matching the root of a package, there is no trailing
  separator.

  As a special case, \code{system.file()} gives the root of the
  \pkg{base} package only.
}
\seealso{\code{\link{list.files}}}
\examples{
system.file()                # The root of the 'base' package
system.file(package = "lqs") # The root of package 'lqs'
system.file("INDEX")
system.file("help", "AnIndex", package = "stepfun")
}
\keyword{file}
\keyword{utilities}
\eof
\name{system.time}
\title{CPU Time Used}
\usage{
system.time(expr)
unix.time(expr)
}
\alias{system.time}
\alias{unix.time}
\arguments{
  \item{expr}{Valid \R expression to be \dQuote{timed}}
}
\description{Return CPU (and other) times that \code{expr} used.
}    
\details{
  \code{system.time} calls the builtin \code{\link{proc.time}},
  evaluates \code{expr}, and then calls \code{proc.time} once more,
  returning the difference between the two \code{proc.time} calls.

  The values returned by the \code{proc.time} are (on Unix) those
  returned by the C library function \code{times}(3v), if available.

  \code{unix.time} is an alias of \code{system.time}, for
  compatibility reasons.
}
\value{
  A numeric vector of length 5 containing the user cpu, system cpu, elapsed,
  subproc1, subproc2 times. The subproc times are the user and
  system cpu time used by child processes (and so are usually zero).
#ifdef windows
  On Windows the subproc times are not available and so are always
  \code{NA}. The first two components are not available on Windows 9x,
  and so are reported as \code{NA}; they do return real values on
  Windows NT4/2000/XP.
#endif

  The resolution of the times will be system-specific; it is common for
  them to be recorded to of the order of 1/100 second, and elapsed
  time is rounded to the nearest 1/100.
}
#ifdef unix
\note{
  It is possible to compile \R without support for \code{system.time},
  when all the values will be \code{NA}.
}
#endif
\seealso{
  \code{\link{proc.time}}, \code{\link{time}} which is for time series.
}
\examples{
system.time(for(i in 1:100) mad(runif(1000)))
\dontrun{
exT <- function(n = 1000) {
  # Purpose: Test if system.time works ok;   n: loop size
  system.time(for(i in 1:n) x <- mean(rt(1000, df=4)))
}
#-- Try to interrupt one of the following (using Ctrl-C / Escape):
exT()                 #- about 3 secs on a 1GHz PIII
system.time(exT())    #~ +/- same
}}
\keyword{utilities}
\eof
\name{t}
\alias{t}
\alias{t.default}
\alias{t.data.frame}
\alias{t.ts}
\title{Matrix Transpose}
\description{
  Given a matrix or \code{\link{data.frame}} \code{x},
  \code{t} returns the transpose of \code{x}.
}
\usage{
t(x)
}
\arguments{
  \item{x}{a matrix or data frame, typically.}
}
\details{
  A data frame is first coerced to a matrix: see \code{\link{as.matrix}}.
  When \code{x} is a vector, it is treated as \dQuote{column}, i.e., the
  result is a 1-row matrix.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{aperm}} for permuting the dimensions of arrays.
}
\examples{
a <- matrix(1:30, 5,6)
ta <- t(a) ##-- i.e.,  a[i, j] == ta[j, i] for all i,j :
for(j in seq(ncol(a)))
  if(! all(a[, j] == ta[j, ])) stop("wrong transpose")
}
\keyword{array}
\eof
\name{table}
\title{Cross Tabulation and Table Creation}
\alias{table}
\alias{summary.table}
\alias{print.summary.table}
\alias{as.data.frame.table}
\alias{as.table}
\alias{as.table.default}
\alias{is.table}
\description{
  \code{table} uses the cross-classifying factors to build a contingency
  table of the counts at each combination of factor levels.
}
\usage{
table(\dots, exclude = c(NA, NaN), dnn = list.names(...), deparse.level = 1)
as.table(x, \dots)
is.table(x)

\method{as.data.frame}{table}(x, row.names = NULL, optional = FALSE, \dots)
}
\arguments{
  \item{\dots}{objects which can be interpreted as factors (including
    character strings), or a list (or data frame) whose components can
    be so interpreted}
  \item{exclude}{values to use in the exclude argument of \code{factor}
    when interpreting non-factor objects; if specified, levels to remove
    from all factors in \dots.}
  \item{dnn}{the names to be given to the dimensions in the result (the
    \emph{dimnames names}).}
  \item{deparse.level}{controls how the default \code{dnn} is
    constructed.  See details.}
  \item{x}{an arbitrary \R object, or an object inheriting from class
    \code{"table"} for the \code{as.data.frame} method.}
  \item{row.names}{a character vector giving the row names for the data
    frame.}
  \item{optional}{a logical controlling whether row names are set.
    Currently not used.}
}
\value{
  \code{table()} returns a \emph{contingency table}, an object of
  \code{\link[base]{class}} \code{"table"}; see the \code{\link{print}}
  method's separate documentation.

  There is a \code{summary} method for objects created by \code{table}
  or \code{\link{xtabs}}, which gives basic information and performs a
  chi-squared test for independence of factors (note that the function
  \code{\link[ctest]{chisq.test}} in package \pkg{ctest} currently only
  handles 2-d tables).

  \code{as.table} and \code{is.table} coerce to and test for contingency
  table, respectively.

  The \code{as.data.frame} method for objects inheriting from class
  \code{"table"} can be used to convert the array-based representation
  of a contingency table to a data frame containing the classifying
  factors and the corresponding counts (the latter as component
  \code{Freq}).  This is the inverse of \code{\link{xtabs}}.
}
\details{
  If the argument \code{dnn} is not supplied, the internal function
  \code{list.names} is called to compute the \sQuote{dimname names}.  If the
  arguments in \code{\dots} are named, those names are used.  For the
  remaining arguments, \code{deparse.level = 0} gives an empty name,
  \code{deparse.level = 1} uses the supplied argument if it is a symbol,
  and \code{deparse.level = 2} will deparse the argument.

  Only when \code{exclude} is specified (i.e., not by default), will
  \code{table} drop levels of factor arguments potentially.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
## Simple frequency distribution
table(rpois(100,5))
data(warpbreaks)
attach(warpbreaks)
## Check the design:
table(wool, tension)
data(state)
table(state.division, state.region)
detach()

data(airquality)
# simple two-way contingency table
with(airquality, table(cut(Temp, quantile(Temp)), Month))

a <- letters[1:3]
table(a, sample(a))                    # dnn is c("a", "")
table(a, sample(a), deparse.level = 0) # dnn is c("", "")
table(a, sample(a), deparse.level = 2) # dnn is c("a", "sample(a)")

## xtabs() <-> as.data.frame.table() :
data(UCBAdmissions) ## already a contingency table
DF <- as.data.frame(UCBAdmissions)
class(tab <- xtabs(Freq ~ ., DF))# xtabs & table
## tab *is* "the same" as the original table:
all(tab == UCBAdmissions)
all.equal(dimnames(tab), dimnames(UCBAdmissions))

a <- rep(c(NA, 1/0:3), 10)
table(a)
table(a, exclude=NULL)
b <- factor(rep(c("A","B","C"), 10))
table(b)
table(b, exclude="B")
d <- factor(rep(c("A","B","C"), 10), levels=c("A","B","C","D","E"))
table(d, exclude="B")

## NA counting:
is.na(d) <- 3:4
d <- factor(d, exclude=NULL)
d[1:7]
table(d, exclude = NULL)
}
\keyword{category}
\eof
\name{tabulate}
\title{Tabulation for Vectors}
\usage{
tabulate(bin, nbins = max(1, bin))
}
\alias{tabulate}
\arguments{
    \item{bin}{a vector of integers, or a factor.}
    \item{nbins}{the number of bins to be used.}
}
\description{
\code{tabulate} takes the integer valued vector \code{bin} and counts
the number of times each integer occurs in it.  \code{tabulate} is
used as the basis of the \code{table} function.
}
\details{
  If \code{bin} is a factor, its internal integer representation
  is tabulated.
  If the elements of \code{bin} are not integers, they are rounded
  to the nearest integer.  Elements outside the range \code{1,\dots,
    nbin} are (silently) ignored in the tabulation.
}
\seealso{
\code{\link{factor}}, \code{\link{table}}.
}
\examples{
tabulate(c(2,3,5))
tabulate(c(2,3,3,5), nb = 10)
tabulate(c(-2,0,2,3,3,5), nb = 3)
tabulate(factor(letters[1:10]))
}
\keyword{arith}
\eof
\name{tapply}
\alias{tapply}
\title{Apply a Function Over a ``Ragged'' Array}
\description{
  Apply a function to each cell of a ragged array, that is to each
  (non-empty) group of values given by a unique combination of the
  levels of certain factors.
}
\usage{
tapply(X, INDEX, FUN = NULL, \dots, simplify = TRUE)
}
\arguments{
  \item{X}{an atomic object, typically a vector.}
  \item{INDEX}{list of factors, each of same length as \code{X}.}
  \item{FUN}{the function to be applied.  In the case of functions like
    \code{+}, \code{\%*\%}, etc., the function name must be quoted.  If
    \code{FUN} is \code{NULL}, tapply returns a vector which can be used
    to subscript the multi-way array \code{tapply} normally produces.}
  \item{\dots}{optional arguments to \code{FUN}.}
  \item{simplify}{If \code{FALSE}, \code{tapply} always returns an array
    of mode \code{"list"}.  If \code{TRUE} (the default), then if
    \code{FUN} always returns a scalar, \code{tapply} returns an array
    with the mode of the scalar.}
}
\value{
  When \code{FUN} is present, \code{tapply} calls \code{FUN} for each
  cell that has any data in it.  If \code{FUN} returns a single atomic
  value for each cell (e.g., functions \code{mean} or \code{var}) and
  when \code{simplify} is \code{TRUE}, \code{tapply} returns a multi-way
  \link{array} containing the values.  The array has the same number of
  dimensions as \code{INDEX} has components; the number of levels in a
  dimension is the number of levels (\code{nlevels()}) in the
  corresponding component of \code{INDEX}.

  Note that contrary to S, \code{simplify = TRUE} always returns an
  array, possibly 1-dimensional.

  If \code{FUN} does not return a single atomic value, \code{tapply}
  returns an array of mode \code{\link{list}} whose components are the
  values of the individual calls to \code{FUN}, i.e., the result is a
  list with a \code{\link{dim}} attribute.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  the convenience functions \code{\link{by}} and \code{\link{aggregate}} 
(using \code{tapply});
  \code{\link{apply}},
  \code{\link{lapply}} with its versions
  \code{\link{sapply}} and \code{\link{mapply}}.
}
\examples{
groups <- as.factor(rbinom(32, n = 5, p = .4))
tapply(groups, groups, length) #- is almost the same as
table(groups)

data(warpbreaks)
## contingency table from data.frame : array with named dimnames
tapply(warpbreaks$breaks, warpbreaks[,-1], sum)
tapply(warpbreaks$breaks, warpbreaks[, 3, drop = FALSE], sum)

n <- 17; fac <- factor(rep(1:3, len = n), levels = 1:5)
table(fac)
tapply(1:n, fac, sum)
tapply(1:n, fac, sum, simplify = FALSE)
tapply(1:n, fac, range)
tapply(1:n, fac, quantile)

## example of ... argument: find quarterly means
data(presidents)
tapply(presidents, cycle(presidents), mean, na.rm = TRUE)

ind <- list(c(1, 2, 2), c("A", "A", "B"))
table(ind)
tapply(1:3, ind) #-> the split vector
tapply(1:3, ind, sum)
}
\keyword{iteration}
\keyword{category}
\eof
\name{taskCallback}
\alias{addTaskCallback}
\alias{removeTaskCallback}
\title{Add or remove a top-level task callback}
\description{
  \code{addTaskCallback} registers an R function
  that is to be called each time a top-level task
  is completed.

  \code{removeTaskCallback} un-registers a function
  that was registered earlier via \code{addTaskCallback}.

  These provide low-level access to the internal/native
  mechanism for managing task-completion actions.
  One can use \code{\link{taskCallbackManager}}
  at the S-language level to manage S functions
  that are called at the completion of each task.
  This is easier and more direct.
}
\usage{
addTaskCallback(f, data = NULL, name = character(0))
removeTaskCallback(id)
}
\arguments{
  \item{f}{the function that is to be invoked each time a top-level task
    is successfully completed. This is called with 5 or 4 arguments
    depending on whether \code{data} is specified or not, respectively.
    The return value should be a logical value indicating whether to
    keep the callback in the list of active callbacks or discard it.}
  \item{data}{if specified, this is the 5-th argument in the call to the
    callback function \code{f}.}
  \item{id}{a string or an integer identifying the element in the
    internal callback list to be removed.
    Integer indices are 1-based, i.e the first element is 1.
    The names of currently registered handlers is available
    using \code{\link{getTaskCallbackNames}}
    and is also returned in a call to \code{\link{addTaskCallback}}.
  }
  \item{name}{character: names to be used.}
}
\value{
  \code{addTaskCallback} returns
  an integer value giving  the position in the list
  of task callbacks that this new callback occupies.
  This is only the current position of the callback.
  It can be used to remove the entry as long as
  no other values are removed from earlier positions
  in the list first.

  \code{removeTaskCallback} returns a logical value
  indicating whether the specified element was removed.
  This can fail (i.e., return \code{FALSE})
  if an incorrect name or index is given that does not
  correspond to the name or position of an element in the list.
}
\details{
Top-level tasks are individual expressions
rather than entire lines of input. Thus an input
line of the form \code{expression1 ; expression2}
will give rise to 2 top-level tasks.
  
A top-level task callback is called with the expression for the
top-level task, the result of the top-level task, a logical value
indicating whether it was successfully completed or not (always TRUE
at present), and a logical value indicating whether the result was
printed or not. If the \code{data} argument was specified in the call
to \code{addTaskCallback}, that value is given as the fifth argument.

The callback function should return a logical value.
If the value is FALSE, the callback is removed from the task
list and will not be called again by this mechanism.
If the function returns TRUE, it is kept in the list and
will be called on the completion of the next top-level task.
}
\note{
  This is an experimental feature and the interface may be changed
  in the future.

  There is also C-level access to top-level task callbacks
  to allow C routines rather than R functions be used.
}
\seealso{
  \code{\link{getTaskCallbackNames}}
  \code{\link{taskCallbackManager}}
  \url{http://developer.r-project.org/TaskHandlers.pdf}
}
\examples{
  times <- function(total = 3, str="Task a") {
    ctr <- 0

    function(expr, value, ok, visible) {
     ctr <<- ctr + 1
     cat(str, ctr, "\n")
     if(ctr == total) {
       cat("handler removing itself\n")
     }
     return(ctr < total)
    }
  }

  # add the callback that will work for
  # 4 top-level tasks and then remove itself.
  n <- addTaskCallback(times(4))

  # now remove it, assuming it is still first in the list.
  removeTaskCallback(n)

\dontrun{
 # There is no point in running this
 # as 
  addTaskCallback(times(4))

  sum(1:10)
  sum(1:10)
  sum(1:10)
  sum(1:10)
  sum(1:10)
}
}
}
\keyword{environment}
\eof
\name{taskCallbackManager}
\alias{taskCallbackManager}
\title{Create an R-level task callback manager}
\description{
  This provides an entirely S-language mechanism
  for managing callbacks or actions  that are invoked at
  the conclusion of each top-level task.  Essentially,
  we register a single R function from this manager
  with the underlying, native
  task-callback mechanism and this function handles invoking the other
  R callbacks under the control of the manager.
  The manager consists of a collection of functions that access shared
  variables to manage the list of user-level callbacks.
}
\usage{
taskCallbackManager(handlers = list(), registered = FALSE, verbose = FALSE)
}
\arguments{
  \item{handlers}{this can be a list of callbacks in which each element
    is a list with  an element  named \code{"f"}
    which is a callback function, and an optional
    element named \code{"data"} which is the 5-th argument to be
    supplied  to the callback when it is invoked.
    Typically this argument is not specified, and one uses \code{add} to
    register callbacks after the manager is created.}
  \item{registered}{a logical value indicating whether
    the \code{evaluate} function has already been registered
    with the internal task callback mechanism.
    This is usually \code{FALSE} and 
    the first time a callback is added
    via the \code{add} function, the
    \code{evaluate} function is automatically registered.
    One can control when the function is registered
    by specifying \code{TRUE} for this argument
    and calling \code{\link{addTaskCallback}} manually.
  }
  \item{verbose}{a logical value, which if \code{TRUE},
    causes information to be printed to the console
    about certain activities this dispatch manager performs.
    This is useful for debugging callbacks and the handler
    itself.
  }
}
\value{
  A list containing 6 functions:
  \item{add}{register a callback with this manager, giving the
    function, an optional 5-th argument, an optional name
    by which the the callback is stored in the list,
    and a \code{register} argument which controls whether
    the \code{evaluate} function is registered with the internal
    C-level dispatch mechanism if necessary.}
  \item{remove}{remove an element from the manager's collection
    of callbacks, either by name or position/index.}
  \item{evaluate}{the \sQuote{real} callback function that is registered
    with the C-level dispatch mechanism and which invokes each of the
    R-leve callbacks within this manager's control.}
  \item{suspend}{a function to set the suspend state
    of the manager. If it is suspended, none of the callbacks will be
    invoked when a task is completed. One sets the state by specifying
    a logical value for the \code{status} argument.
  }
  \item{register}{a function to register the \code{evaluate}
    function with the internal C-level dispatch mechanism. This is
    done automatically by the \code{add} function, but can be called
    manually.}
  \item{callbacks}{returns the list of callbacks being maintained by this
   manager.}
}
\note{
  This is an experimental feature and the interface may be changed
  in the future.
}
\seealso{
  \code{\link{addTaskCallback}}
  \code{\link{removeTaskCallback}}
  \code{\link{getTaskCallbackNames}}
  \url{http://developer.r-project.org/TaskHandlers.pdf}  
}
\examples{
   # create the manager
  h <- taskCallbackManager()

   # add a callback
  h$add(function(expr, value, ok, visible) {
                         cat("In handler\n")
                         return(TRUE)
                       }, name = "simpleHandler")

   # look at the internal callbacks.
  getTaskCallbackNames()

   # look at the R-level callbacks
  names(h$callback())
 
   #
  getTaskCallbackNames()
  removeTaskCallback("R-taskCallbackManager")
}
\keyword{environment}
\eof
\name{taskCallbackNames}
\alias{getTaskCallbackNames}
\title{Query the names of the current internal top-level task callbacks}
\description{
  This provides a way to get the names (or identifiers)
  for the currently registered task callbacks
  that are invoked at the conclusion of each top-level task.
  These identifies can be used to remove a callback.
}
\usage{
getTaskCallbackNames()
}
\arguments{
}
\value{
  A character vector giving the name for each of the
  registered callbacks which are invoked when
  a top-level task is completed successfully.
  Each name is the one used when registering
  the callbacks and returned as the in the
  call to \code{\link{addTaskCallback}}. 
}
\note{
  One can use \code{\link{taskCallbackManager}}
  to manage user-level task callbacks,
  i.e., S-language functions, entirely within
  the S language and access the names
  more directly.
}
\seealso{
  \code{\link{addTaskCallback}}
  \code{\link{removeTaskCallback}}
  \code{\link{taskCallbackManager}}
  \url{http://developer.r-project.org/TaskHandlers.pdf}  
}
\examples{
  n <- addTaskCallback(function(expr, value, ok, visible) {
                         cat("In handler\n")
                         return(TRUE)
                       }, name = "simpleHandler")

  getTaskCallbackNames()

    # now remove it by name
  removeTaskCallback("simpleHandler")


  h <- taskCallbackManager()
  h$add(function(expr, value, ok, visible) {
                         cat("In handler\n")
                         return(TRUE)
                       }, name = "simpleHandler")
  getTaskCallbackNames()
  removeTaskCallback("R-taskCallbackManager")
}
\keyword{environment}
\eof
\name{tempfile}
\alias{tempfile}
\alias{tempdir}
\title{Create Names for Temporary Files}
\description{
  \code{tempfile} returns a vector of character strings which can be used as
  names for temporary files.
}
\usage{
tempfile(pattern = "file", tmpdir = tempdir())
tempdir()
}
\arguments{
  \item{pattern}{a non-empty character vector giving the initial part
    of the name.}
  \item{tmpdir}{a non-empty character vector giving the directory name}  
}
\value{
  For \code{tempfile} a character vector giving the names of possible
  (temporary) files. Note that no files are generated by
  \code{tempfile}.

  For \code{tempdir}, the path of the per-session temporary directory.
}
\details{
  If \code{pattern} has length greater than one then the result is of the
  same length giving a temporary file name for each component of
  \code{pattern}. 

  The names are very likely to be unique among calls to \code{tempfile}
  in an \R session and across simultaneous \R sessions.  The filenames are
  guaranteed not to be currently in use.

#ifdef unix
  The file name is made of the pattern, the process number in hex and a
  random suffix in hex.  By default, the filenames will be in the
  directory given by \code{tempdir()}.  This will be a subdirectory of
  the directory given by the environment variable \env{TMPDIR} if set,
  otherwise \code{"/tmp"}.
#endif
#ifdef windows
  By default, \code{tempdir()} gives a subdirectory of the first found
  of the environment variables \env{TMP}, \env{TEMP} and \env{R\_USER}
  (see \code{\link{Rconsole}}) which points to a writeable directory.
  If the path to the directory contains a space in any of the
  components, the path returned will use the shortnames version of the
  path.
#endif
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{\code{\link{unlink}} for deleting files.}
\examples{
tempfile(c("ab", "a b c"))   # give file name with spaces in!
}
\keyword{file}
\eof
\name{termplot}
\alias{termplot}
\title{Plot regression terms}
\description{
  Plots regression terms against their predictors, optionally with
  standard errors and partial residuals added.
}
\usage{
termplot(model, data=NULL, envir=environment(formula(model)),
         partial.resid=FALSE, rug=FALSE,
         terms=NULL, se=FALSE, xlabs=NULL, ylabs=NULL, main = NULL,
         col.term = 2, lwd.term = 1.5,
         col.se = "orange", lty.se = 2, lwd.se = 1,
         col.res = "gray", cex = 1, pch = par("pch"),
         ask = interactive() && nb.fig < n.tms && .Device !="postscript",
         use.factor.levels=TRUE,
         \dots)
}
\arguments{
  \item{model}{fitted model object}
  \item{data}{data frame in which variables in \code{model} can be
    found}
  \item{envir}{environment in which variables in \code{model} can be found}
  \item{partial.resid}{logical; should partial residuals be plotted?}
  \item{rug}{add \link{rug}plots (jittered 1-d histograms) to the axes?}
  \item{terms}{which terms to plot (default \code{NULL} means all terms)}
  \item{se}{plot pointwise standard errors?}
  \item{xlabs}{vector of labels for the x axes}
  \item{ylabs}{vector of labels for the y axes}
  \item{main}{logical, or vector of main titles;  if \code{TRUE}, the
    model's call is taken as main title, \code{NULL} or \code{FALSE} mean
    no titles.}
  \item{col.term, lwd.term}{color and line width for the \dQuote{term curve},
    see \code{\link{lines}}.}
  \item{col.se, lty.se, lwd.se}{color, line type and line width for the
    \dQuote{twice-standard-error curve} when \code{se = TRUE}.}
  \item{col.res, cex, pch}{color, plotting character expansion and type
    for partial residuals, when \code{partial.resid = TRUE}, see
    \code{\link{points}}.}
   \item{ask}{logical; if \code{TRUE}, the user is \emph{ask}ed before
     each plot, see \code{\link{par}(ask=.)}.}
   \item{use.factor.levels}{Should x-axis ticks use factor levels or
     numbers for factor terms?}
  \item{\dots}{other graphical parameters}
}
\details{
  The model object must have a \code{predict} method that accepts
  \code{type=terms}, eg \code{\link{glm}} in the\pkg{base} package,
  \code{\link[survival]{coxph}} and \code{\link[survival]{survreg}} in
  the \pkg{survival} package.

  For the \code{partial.resid=TRUE} option it must have a
  \code{\link{residuals}} method that accepts \code{type="partial"},
  which \code{\link{lm}} and \code{\link{glm}} do.

  The \code{data} argument should rarely be needed, but in some cases
  \code{termplot} may be unable to reconstruct the original data frame.

  Nothing sensible happens for interaction terms.
}
\seealso{For (generalized) linear models, \code{\link{plot.lm}} and
  \code{\link{predict.glm}}.}
\examples{
had.splines <- "package:splines" \%in\% search()
if(!had.splines) rs <- require(splines)
x <- 1:100
z <- factor(rep(LETTERS[1:4],25))
y <- rnorm(100,sin(x/10)+as.numeric(z))
model <- glm(y ~ ns(x,6) + z)

par(mfrow=c(2,2)) ## 2 x 2 plots for same model :
termplot(model, main = paste("termplot( ", deparse(model$call)," ...)"))
termplot(model, rug=TRUE)
termplot(model, partial=TRUE, rug= TRUE,
         main="termplot(..., partial = TRUE, rug = TRUE)")
termplot(model, partial=TRUE, se = TRUE, main = TRUE)
if(!had.splines && rs) detach("package:splines")
}
\keyword{hplot}
\keyword{regression}
\eof
\name{terms}
\title{Model Terms}
\usage{
terms(x, \dots)
}
\alias{terms}
\alias{terms.terms}
\alias{terms.aovlist}
\alias{terms.default}
\alias{print.terms}
\description{
  The function \code{terms} is a generic function
  which can be used to extract \emph{terms} objects
  from various kinds of \R data objects.
}
\arguments{
  \item{x}{object used to select a method to dispatch.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\details{
  There are methods for classes \code{"aovlist"}, and \code{"terms"}
  \code{"formula"} (see \code{\link{terms.formula}}):
  the default method just extracts the \code{terms} component of the
  object (if any).
}
\value{
  An object of class \code{c("terms", "formula")} which contains the
  \emph{terms} representation of a symbolic model. See
  \code{\link{terms.object}} for its structure.
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical models.}
  Chapter 2 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{terms.object}}, \code{\link{terms.formula}},
  \code{\link{lm}}, \code{\link{glm}}, \code{\link{formula}}.
}
%%--- MM: I would really like instructive examples here...
\keyword{models}
\eof
\name{terms.formula}
\alias{terms.formula}
\title{Construct a terms Object from a Formula}
\description{
  This function takes a formula and some optional arguments and
  constructs a terms object. The terms object can then be used to
  construct a \code{\link{model.matrix}}.
}
\usage{
\method{terms}{formula}(x, specials = NULL, abb = NULL, data = NULL, neg.out = TRUE,
     keep.order = FALSE, simplify = FALSE, ...)
}
\arguments{
  \item{x}{a formula.}
  \item{specials}{which functions in the formula should be marked as
    special in the \code{terms} object.}
  \item{abb}{Not implemented in \R.}
  \item{data}{a data frame from which the meaning of the special symbol
    \code{.} can be inferred. It is unused if there is no \code{.} in
    the formula.}
  \item{neg.out}{Not implemented in \R.}
  \item{keep.order}{a logical value indicating whether the terms should
    keep their positions. If \code{FALSE} the terms are reordered so
    that main effects come first, followed by the interactions,
    all second-order, all third-order and so on.  Effects of a given
    order are kept in the order specified.}
  \item{simplify}{should the formula be expanded and simplified, the
    pre-1.7.0 behaviour?}
  \item{\dots}{further arguments passed to or from other methods.}
}
\details{
  Not all of the options work in the same way that they do in S and not
  all are implemented.
}
\value{
  A \code{\link{terms.object}} object is returned.  The object itself is
  the re-ordered (unless \code{keep.order = TRUE}) formula.  In all
  cases variables within an interaction term in the formula are
  re-ordered by the ordering of the \code{"variables"} attribute, which
  is the order in which the variables occur in the formula.
}
\seealso{
  \code{\link{terms}}, \code{\link{terms.object}}
}
\keyword{models}
\eof
\name{terms.object}
\title{Description of Terms Objects}
\alias{terms.object}
\description{
  An object of class \code{\link{terms}} holds information about a
  model.  Usually the model was specified in terms of a
  \code{\link{formula}} and that formula was used to determine the terms
  object.
}
\value{
  The object itself is simply the formula supplied to the call of
  \code{\link{terms.formula}}.  The object has a number of attributes
  and they are used to construct the model frame:

  \item{factors}{A matrix of variables by terms showing which variables
    appear in which terms. The entries are 0 if the variable does not
    occur in the term, 1 if it does occur and should be coded by
    contrasts, and 2 if it occurs and should be coded via dummy
    variables for all levels (as when an intercept or lower-order term
    is missing).}
  \item{term.labels}{A character vector containing the labels for each
    of the terms in the model.  Non-syntactic names will be quoted by
    backticks.}
  \item{variables}{A call to \code{list} of the variables in the model.}
  \item{intercept}{Either 0, indicating no intercept is to be fit, or 1
    indicating that an intercept is to be fit.}
  \item{order}{A vector of the same length as \code{term.labels}
    indicating the order of interaction for each term }
  \item{response}{The index of the variable (in variables) of the
    response (the left hand side of the formula).}
  \item{offset}{If the model contains \code{\link{offset}} terms there
    is an \code{offset} attribute indicating which terms are offsets}
  \item{specials}{If the \code{specials} argument was given to
    \code{\link{terms.formula}} there is a \code{specials} attribute, a
    list of vectors indicating the terms that contain these special
    functions.}

  The object has class \code{c("terms", "formula")}.
}
\note{
  These objects are different from those found in S.  In particular
  there is no \code{formula} attribute, instead the object is itself a
  formula.  Thus, the mode of a terms object is different as well. 

  Examples of the \code{specials} argument can be seen in the
  \code{\link{aov}} and \code{\link[survival]{coxph}} functions.
}
\seealso{
  \code{\link{terms}}, \code{\link{formula}}.
}
%%--- MM: I would really like instructive examples here...
\keyword{models}
\eof
\name{text}
\title{Add Text to a Plot}
\usage{
text(x, \dots)

\method{text}{default} (x, y = NULL, labels = seq(along = x), adj = NULL,
     pos = NULL, offset = 0.5, vfont = NULL,
     cex = 1, col = NULL, font = NULL, xpd = NULL, \dots)
}
\alias{text}
\alias{text.default}
\arguments{
  \item{x, y}{numeric vectors of coordinates where the text
    \code{labels} should be written.  If the length of \code{x} and
    \code{y} differs, the shorter one is recycled.}
  \item{labels}{one or more character strings or expressions specifying
    the \emph{text} to be written.  An attempt is made
    to coerce other vectors to character, and other language objects
    to expressions.}
  \item{adj}{one or two values in \eqn{[0,1]} which specify the x
    (and optionally y) adjustment of the labels.  On most devices values
    outside that interval will also work.}
  \item{pos}{a position specifier for the text.  If specified this
    overrides any \code{adj} value given.  Values of \code{1},
    \code{2}, \code{3} and \code{4}, respectively indicate
    positions below, to the left of, above and to the right of
    the specified coordinates.}
  \item{offset}{when \code{pos} is specified, this value gives the
    offset of the label from the specified coordinate in fractions
    of a character width.}
  \item{vfont}{if a character vector of length 2 is specified, then Hershey
    vector fonts are used.  The first element of the vector
    selects a typeface and the second element selects a style.}
  \item{cex}{numeric \bold{c}haracter \bold{ex}pansion factor; multiplied
    by \code{\link{par}("cex")} yields the final character size.}
  \item{col, font}{the color and font to be used; these default to the
    values of the global graphical parameters in \code{\link{par}()}.}
  \item{xpd}{(where) should clipping take place?  Defaults to
    \code{\link{par}("xpd")}.}
  \item{\dots}{further graphical parameters (from \code{\link{par}}).}
%% such as ???, etc.
}
\description{
  \code{text} draws the strings given in the vector \code{labels} at the
  coordinates given by \code{x} and \code{y}.
  \code{y} may be missing since \code{\link{xy.coords}(x,y)} is used for
  construction of the coordinates.
}
\details{
  \code{labels} must be of type \code{\link{character}} or
  \code{\link{expression}} (or be coercible to such a type).
  In the latter case, quite a bit of
  mathematical notation is available such as sub- and superscripts,
  greek letters, fractions, etc.

  \code{adj} allows \emph{adj}ustment of the text with respect to \code{(x,y)}.
  Values of 0, 0.5, and 1 specify left/bottom, middle and
  right/top, respectively.  The default is for centered text, i.e.,
  \code{adj = c(0.5, 0.5)}. Accurate vertical centering needs
  character metric information on individual characters, which is
  only available on some devices.

  The \code{pos} and \code{offset} arguments can be used in conjunction
  with values returned by \code{identify} to recreate an interactively
  labelled plot.

  Text can be rotated by using graphical parameters \code{srt} (see
  \code{\link{par}}); this rotates about the centre set by \code{adj}.

  Graphical parameters \code{col}, \code{cex} and \code{font} can be
  vectors and will then be applied cyclically to the \code{labels} (and
  extra values will be ignored).

  Labels whose \code{x}, \code{y}, \code{labels}, \code{cex} or \code{xol}
  value is \code{NA} are omitted from the plot.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{mtext}}, \code{\link{title}},
  \code{\link{Hershey}} for details on Hershey vector fonts,
  \code{\link{plotmath}} for details and more examples on
  mathematical annotation.
}
\examples{
plot(-1:1,-1:1, type = "n", xlab = "Re", ylab = "Im")
K <- 16; text(exp(1i * 2 * pi * (1:K) / K), col = 2)

## The following two examples use latin1 characters: these may not
## appear correctly (or be omitted entirely).
plot(1:10, 1:10, main = "text(...) examples\n~~~~~~~~~~~~~~",
     sub = "R is GNU ©, but not ® ...")
mtext("«ISO-accents»: ± éè øØ å<Å æ<Æ", side=3)
points(c(6,2), c(2,1), pch = 3, cex = 4, col = "red")
text(6, 2, "the text is CENTERED around (x,y) = (6,2) by default",
     cex = .8)
text(2, 1, "or Left/Bottom - JUSTIFIED at (2,1) by 'adj = c(0,0)'",
     adj = c(0,0))
text(4, 9, expression(hat(beta) == (X^t * X)^{-1} * X^t * y))
text(4, 8.4, "expression(hat(beta) == (X^t * X)^{-1} * X^t * y)", cex = .75)
text(4, 7, expression(bar(x) == sum(frac(x[i], n), i==1, n)))

## Two more latin1 examples
text(5,10.2,
     "Le français, c'est façile: Règles, Liberté, Egalité, Fraternité...")
text(5,9.8, "Jetz no chli züritüütsch: (noch ein bißchen Zürcher deutsch)")
}
\keyword{aplot}
\eof
\name{textConnection}
\alias{textConnection}
\title{Text Connections}
\description{
  Input and output text connections.
}
\usage{
textConnection(object, open = "r", local = FALSE)
}
\arguments{
  \item{object}{character.  A description of the connection. 
    For an input this is an \R character vector object, and for an output
    connection the name for the \R character vector to receive the
    output.
  }
  \item{open}{character.  Either \code{"r"} (or equivalently \code{""})
    for an input connection or \code{"w"} or \code{"a"} for an output
    connection.}
  \item{local}{logical.  Used only for output connections.  If \code{TRUE},
    output is assigned to a variable in the calling environment.  Otherwise
    the global environment is used.}
}
\details{
  An input text connection is opened and the character vector is copied
  at time the connection object is created, and \code{close}
  destroys the copy.

  An output text connection is opened and creates an \R character vector
  of the given name in the user's workspace or in the calling environment,
  depending on the value of the \code{local} argument.  This object will at all
  times hold the completed lines of output to the connection, and
  \code{\link{isIncomplete}} will indicate if there is an incomplete
  final line.  Closing the connection will output the final line,
  complete or not.  (A line is complete once it has been terminated by
  end-of-line, represented by \code{"\\n"} in \R.)

  Opening a text connection with \code{mode = "a"} will attempt to
  append to an existing character vector with the given name in the
  user's workspace or the calling environment.  If none is found (even
  if an object exists of the right name but the wrong type) a new
  character vector wil be created, with a warning.

  You cannot \code{seek} on a text connection, and \code{seek} will
  always return zero as the position.
}

\value{
  A connection object of class \code{"textConnection"} which inherits
  from class \code{"connection"}.
}

\note{
  As output text connections keep the character vector up to date
  line-by-line, they are relatively expensive to use, and it is often
  better to use an anonymous \code{\link{file}()} connection to collect
  output.

  On platforms where \code{vsnprintf} does not return the needed length
  of output (e.g., Windows) there is a 100,000 character limit on the
  length of line for output connections: longer lines will be truncated
  with a warning.
}
 
\seealso{
  \code{\link{connections}}, \code{\link{showConnections}},
  \code{\link{pushBack}}, \code{\link{capture.output}}.
}

\examples{
zz <- textConnection(LETTERS)
readLines(zz, 2)
scan(zz, "", 4)
pushBack(c("aa", "bb"), zz)
scan(zz, "", 4)
close(zz)

zz <- textConnection("foo", "w")
writeLines(c("testit1", "testit2"), zz)
cat("testit3 ", file=zz)
isIncomplete(zz)
cat("testit4\n", file=zz)
isIncomplete(zz)
close(zz)
foo

\dontrun{# capture R output: use part of example from help(lm)
zz <- textConnection("foo", "w")
ctl <- c(4.17, 5.58, 5.18, 6.11, 4.5, 4.61, 5.17, 4.53, 5.33, 5.14)
trt <- c(4.81, 4.17, 4.41, 3.59, 5.87, 3.83, 6.03, 4.89, 4.32, 4.69)
group <- gl(2, 10, 20, labels = c("Ctl", "Trt"))
weight <- c(ctl, trt)
sink(zz)
anova(lm.D9 <- lm(weight ~ group))
cat("\nSummary of Residuals:\n\n")
summary(resid(lm.D9))
sink()
close(zz)
cat(foo, sep = "\n")
}
}
\keyword{file}
\keyword{connection}
\eof
\name{time}
\alias{time}
\alias{cycle}
\alias{frequency}
\alias{deltat}
\alias{time.default}
\alias{time.ts}
\alias{cycle.default}
\alias{cycle.ts}
\alias{frequency.default}
\alias{deltat.default}
\title{Sampling Times of Time Series}
\description{
  \code{time} creates the vector of times at which a time series was sampled.

  \code{cycle} gives the positions in the cycle of each observation.

  \code{frequency} returns the number of samples per unit time and
  \code{deltat} the time interval between observations (see
  \code{\link{ts}}).
}
\usage{
time(x, \dots)
\method{time}{default}(x, offset=0, \dots)

cycle(x, \dots)
frequency(x, \dots)
deltat(x, \dots)
}
\arguments{
  \item{x}{a univariate or multivariate time-series, or a vector or matrix.}
  \item{offset}{can be used to indicate when sampling took place
    in the time unit. \code{0} (the default) indicates the start
    of the unit, \code{0.5} the middle and \code{1} the end of
    the interval.}
  \item{\dots}{extra arguments for future methods.}
}
\details{
  These are all generic functions, which will use the
  \code{\link{tsp}} attribute of \code{x} if it exists. \code{time}
  and \code{cycle} have methods for class \code{\link{ts}} that coerce
  the result to that class.
}
\seealso{
  \code{\link{ts}}, \code{\link{start}}, \code{\link{tsp}},
  \code{\link{window}}.

  \code{\link{date}} for clock time, \code{\link{system.time}}
  for CPU usage.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
data(presidents)
cycle(presidents)
# a simple series plot: c() makes the x and y arguments into vectors
plot(c(time(presidents)), c(presidents), type="l")
}
\keyword{ts}
\eof
\name{title}
\title{Plot Annotation}
\usage{
title(main = NULL, sub = NULL, xlab = NULL, ylab = NULL,
      line = NA, outer = FALSE, \dots)
}
\alias{title}
\arguments{
  \item{main}{The main title (on top) using font and size (character
    expansion) \code{par("font.main")} and color
    \code{par("col.main")}.}
  \item{sub}{Sub-title (at bottom) using font and size
    \code{par("font.sub")} and color \code{par("col.sub")}.}
  \item{xlab}{X axis label using font and character expansion
    \code{par("font.axis")} and color \code{par("col.axis")}.}
  \item{ylab}{Y axis label, same font attributes as \code{xlab}.}
  \item{line}{specifying a value for \code{line} overrides the
    default placement of labels, and places them this many lines
    from the plot.}
  \item{outer}{a logical value.  If \code{TRUE}, the titles are
    placed in the outer margins of the plot.}
  \item{\dots}{further graphical parameters from
    \code{\link{par}}.  Use e.g., \code{col.main} or \code{cex.sub}
    instead of just \code{col} or \code{cex}.}
}
\description{
  This function can be used to add labels to a plot.  Its first four
  principal arguments can also be used as arguments in most high-level
  plotting functions.  They must be of type \code{\link{character}} or
  \code{\link{expression}}. In the latter case, quite a bit of
  mathematical notation is available such as sub- and superscripts,
  greek letters, fractions, etc.
}
\details{
  The labels passed to title can be simple strings or expressions,
  or they can be a list containing the string to be plotted, and
  a selection of the optional modifying graphical parameters
  \code{cex=}, \code{col=}, \code{font=}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{mtext}}, \code{\link{text}};
  \code{\link{plotmath}} for details on mathematical annotation.
}
\examples{
data(cars)
plot(cars, main = "") # here, could use main directly
title(main = "Stopping Distance versus Speed")

plot(cars, main = "")
title(main = list("Stopping Distance versus Speed", cex=1.5,
                  col="red", font=3))

## Specifying "..." :
plot(1, col.axis = "sky blue", col.lab = "thistle")
title("Main Title", sub = "sub title",
      cex.main = 2,   font.main= 4, col.main= "blue",
      cex.sub = 0.75, font.sub = 3, col.sub = "red")


x <- seq(-4, 4, len = 101)
y <- cbind(sin(x), cos(x))
matplot(x, y, type = "l", xaxt = "n",
        main = expression(paste(plain(sin) * phi, "  and  ",
                                plain(cos) * phi)),
        ylab = expression("sin" * phi, "cos" * phi), # only 1st is taken
        xlab = expression(paste("Phase Angle ", phi)),
        col.main = "blue")
axis(1, at = c(-pi, -pi/2, 0, pi/2, pi),
     lab = expression(-pi, -pi/2, 0, pi/2, pi))
abline(h = 0, v = pi/2 * c(-1,1), lty = 2, lwd = .1, col = "gray70")
}
\keyword{aplot}
\eof
\name{toString}
\alias{toString}
\alias{toString.default}

\title{toString Converts its Argument to a Character String}
\description{
  This is a helper function for \code{\link{format}}. It converts its argument
  to a string. If the argument is a vector then its elements are
  concatenated with a \code{,} as a separtor. 
  Most methods should honor the width argument. 
  The minimum value for \code{width} is six. 
}
\usage{
toString(x, \dots)

\method{toString}{default}(x, width, \dots)
}
\arguments{
  \item{x}{The object to be converted.}
  \item{width}{The returned value is at most the first \code{width} characters.}
  \item{\dots}{Optional arguments for methods.}
}
\value{
  A character vector of length 1 is returned.
}
\author{ Robert Gentleman }

\seealso{ \code{\link{format}} }

\examples{
x <- c("a", "b", "aaaaaaaaaaa")
toString(x)
toString(x, width=8)
}
\keyword{utilities}
\eof
\name{trace}
\title{Interactive Tracing and Debugging of Calls to a Function or Method}
\alias{trace}
\alias{untrace}
\alias{tracingState}
%% internal
\alias{.primTrace}
\alias{.primUntrace}
\description{
  A call to \code{trace} allows you to insert debugging code (e.g., a
  call to \code{\link{browser}} or \code{\link{recover}}) at chosen
  places in any function.  A call to \code{untrace} cancels the tracing.
  Specified methods can be traced the same way, without tracing all
  calls to the function.  Trace code can be any \R expression.  Tracing
  can be temporarily turned on or off globally by calling \code{tracingState}.
}
\usage{
trace(what, tracer, exit, at, print, signature, where = topenv(parent.frame()))
untrace(what, signature = NULL, where = topenv(parent.frame()))

tracingState(on = NULL)
}
\arguments{
  \item{what}{The name (quoted or not) of a function to be traced or
    untraced.  More than one name can be given in the quoted form, and
    the same action will be applied to each one.}
  \item{tracer}{Either a function or an unevaluated expression.  The
    function will be called or the expression will be evaluated either
    at the beginning of the call, or before those steps in the call
    specified by the argument \code{at}.
    See the details section.}
  \item{exit}{ Either a function or an unevaluated expression.  The
    function will be called or the expression will be evaluated on
    exiting the function.
    See the details section.}
  \item{at}{optional numeric vector.  If supplied, \code{tracer}
    will be called just before the corresponding step in the body of the
    function.
    See the details section. }
  \item{print}{If \code{TRUE} (as per default), a descriptive line is
    printed before any trace expression is evaluated.}
  \item{signature}{ If this argument is supplied, it should be a
    signature for a method for function \code{what}.  In this case, the
    method, and \emph{not} the function itself, is traced.}
  \item{where}{the environment from which to look for the function to be
    traced; by default, the top-level environment of the call to
    \code{trace}.  If you put a call to \code{trace} into code in a
    package, you may need to specify \code{where=.GlobalEnv} if
    the package containing the call has a namespace, but the function
    you want to trace is somewhere on the search list.
  }
  \item{on}{logical; a call to \code{tracingState} returns \code{TRUE}
    if tracing is globally turned on, \code{FALSE} otherwise.  An
    argument of one or the other of those values sets the state.  If the
    tracing state is \code{FALSE}, none of the trace actions will
    actually occur (used, for example, by debugging functions to shut
    off tracing during debugging).}
}
\details{
  The \code{trace} function operates by constructing a revised version
  of the function (or of the method, if \code{signature} is supplied),
  and assigning the new object back where the original was found.
  If only the \code{what} argument is given, a line of trace printing is
  produced for each call to the function (back compatible with the
  earlier version of \code{trace}).

  The object constructed by \code{trace} is from a class that extends
  \code{"function"} and which contains the original, untraced version.
  A call to \code{untrace} re-assigns this version.

  If the argument \code{tracer} or \code{exit} is the name of a
  function, the tracing expression will be a call to that function, with
  no arguments.  This is the easiest and most common case, with the
  functions \code{\link{browser}} and \code{\link{recover}} the
  likeliest candidates; the former browses in the frame of the function
  being traced, and the latter allows browsing in any of the currently
  active calls.

  The \code{tracer} or \code{exit} argument can also be an unevaluated
  expression (such as returned by a call to \code{\link{quote}} or
  \code{\link{substitute}}).  This expression itself is inserted in the
  traced function, so it will typically involve arguments or local
  objects in the traced function.  An expression of this form is useful
  if you only want to interact when certain conditions apply (and in
  this case you probably want to supply \code{print=FALSE} in the call
  to \code{trace} also).

  When the \code{at} argument is supplied, it should be a vector of
  integers referring to the substeps of the body of the function (this
  only works if the body of the function is enclosed in \code{{ ...}}.  In
  this case \code{tracer} is \emph{not} called on entry, but instead
  just before evaluating each of the steps listed in \code{at}.  (Hint:
  you don't want to try to count the steps in the printed version of a
  function; instead, look at \code{as.list(body(f))} to get the numbers
  associated with the steps in function \code{f}.)

  An intrinsic limitation in the \code{exit} argument is that it won't
  work if the function itself uses \code{on.exit}, since the existing
  calls will override the one supplied by \code{trace}.

  Tracing does not nest.  Any call to \code{trace} replaces previously
  traced versions of that function or method, and \code{untrace} always
  restores an untraced version.  (Allowing nested tracing has too many
  potentials for confusion and for accidentally leaving traced versions
  behind.)

  Tracing primitive functions (builtins and specials) from the base
  package works, but only by a special mechanism and not very
  informatively.  Tracing a primitive causes the primitive to be
  replaced by a function with argument \dots (only).  You can get a bit
  of information out, but not much.  A warning message is issued when
  \code{trace} is used on a primitive.

  The practice of saving the traced version of the function back where
  the function came from means that tracing carries over from one
  session to another, \emph{if} the traced function is saved in the
  session image.  (In the next session, \code{untrace} will remove the
  tracing.)  On the other hand, functions that were in a package, not in
  the global environment, are not saved in the image, so tracing expires
  with the session for such functions.

  Tracing a method is basically just like tracing a function, with the
  exception that the traced version is stored by a call to
  \code{\link[methods]{setMethod}} rather than by direct assignment, and so is
  the untraced version after a call to \code{untrace}.

  The version of \code{trace} described here is largely compatible with
  the version in S-Plus, although the two work by entirely different
  mechanisms.  The S-Plus \code{trace} uses the session frame, with the
  result that tracing never carries over from one session to another (\R
  does not have a session frame).  Another relevant distinction has
  nothing directly to do with \code{trace}:  The browser in S-Plus
  allows changes to be made to the frame being browsed, and the changes
  will persist after exiting the browser.  The \R browser allows changes,
  but they disappear when the browser exits.  This may be relevant in
  that the S-Plus version allows you to experiment with code changes
  interactively, but the \R version does not.  (A future revision may
  include a \dQuote{destructive} browser for \R.)
}
\note{
  The version of function tracing that includes any of the arguments
  except for the function name requires the methods package (because it
  uses special classes of objects to store and restore versions of the
  traced functions).

  If methods dispatch is not currently on, \code{trace} will load the
  methods namespace, but will not put the methods package on the search
  list.
}
\value{
  The traced function(s) name(s).  The relevant consequence is the
  assignment that takes place.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{browser}} and \code{\link{recover}}, the likeliest
  tracing functions;
  also, \code{\link{quote}} and \code{\link{substitute}} for
  constructing general expressions.
}
\examples{
\dontshow{ hasMethods <- .isMethodsDispatchOn()}

f <- function(x, y) {
    y <- pmax(y, .001)
    x ^ y
}

## arrange to call the browser on entering and exiting
## function f
trace("f", browser, exit = browser)

## instead, conditionally assign some data, and then browse
## on exit, but only then.  Don't bother me otherwise

trace("f", quote(if(any(y < 0)) yOrig <- y),
      exit = quote(if(exists("yOrig")) browser()),
      print = FALSE)

## trace a utility function, with recover so we
## can browse in the calling functions as well.

trace("as.matrix", recover)

## turn off the tracing

untrace(c("f", "as.matrix"))

if(!hasMethods) detach("package:methods")
}
\keyword{programming}
\keyword{debugging}
\eof
\name{traceback}
\title{Print Call Stack of Last Error}
\usage{
traceback()
}
\alias{traceback}
\alias{.Traceback}
\description{
  \code{traceback()} prints the call stack of the last error, i.e., the
  sequence of calls that lead to the error.  This is useful when an
  error occurs with an unidentifiable error message.
  This stack is stored as a list in \code{.Traceback},
  which \code{traceback} prints in a user-friendly format.
}
\value{
  \code{traceback()} returns nothing, but prints the deparsed call stack
  deepest call first.  The calls may print on more that one line, and
  the first line is labelled by the frame number.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
foo <- function(x) { print(1); bar(2) }
bar <- function(x) { x + a.variable.which.does.not.exist }
\dontrun{
foo(2) # gives a strange error
traceback()}
## 2: bar(2)
## 1: foo(2)
bar
## Ah, this is the culprit ...
}
\keyword{programming}
\eof
\name{transform}
\alias{transform}
\alias{transform.default}
\alias{transform.data.frame}
\title{Transform an Object, for Example a Data Frame}
\usage{
transform(x, \dots)
%transform.default(x, \dots)
%transform.data.frame(x, \dots)
}
\arguments{
    \item{x}{The object to be transformed}
    \item{\dots}{Further arguments of the form \code{tag=value}}
}
\description{
  \code{transform} is a generic function, which---at least
  currently---only does anything useful with
  data frames. \code{transform.default} converts its first argument to
  a data frame if possible and calls \code{transform.data.frame}. 
}
\details{
  The \code{\dots} arguments to \code{transform.data.frame} are tagged
  vector expressions, which are evaluated in the data frame
  \code{x}.  The tags are matched against \code{names(x)}, and for
  those that match, the value replace the corresponding variable in
  \code{x}, and the others are appended to \code{x}.
} 
\value{
  The modified value of \code{x}.
}
\author{Peter Dalgaard}
\note{If some of the values are not vectors of the appropriate length,
  you deserve whatever you get!}
\seealso{
    \code{\link{subset}},
    \code{\link{list}},
    \code{\link{data.frame}}
}
\examples{
data(airquality)
transform(airquality, Ozone = -Ozone)
transform(airquality, new = -Ozone, Temp = (Temp-32)/1.8)

attach(airquality)
transform(Ozone, logOzone = log(Ozone)) # marginally interesting ...
detach(airquality)
}
\keyword{manip}
\eof
\name{trees}
\docType{data}
\alias{trees}
\title{Girth, Height and Volume for Black Cherry Trees}
\description{
  This data set provides measurements of the girth, height and volume
  of timber in 31 felled black cherry trees.  Note that girth is the
  diameter of the tree (in inches) measured at 4 ft 6 in above the
  ground.
}
\usage{data(trees)}
\format{
  A data frame with 31 observations on 3 variables.
  \tabular{rlll}{
    \code{[,1]} \tab \code{Girth} \tab numeric
    \tab Tree diameter in inches\cr
    \code{[,2]} \tab \code{Height}\tab numeric
    \tab Height in ft\cr
    \code{[,3]} \tab \code{Volume}\tab numeric
    \tab Volume of timber in cubic ft\cr}
}
\source{
  Ryan, T. A., Joiner, B. L. and Ryan, B. F. (1976)
  \emph{The Minitab Student Handbook}.
  Duxbury Press.
}
\references{
  Atkinson, A. C. (1985)
  \emph{Plots, Transformations and Regression}.
  Oxford University Press.
}
\examples{
data(trees)
pairs(trees, panel = panel.smooth, main = "trees data")
plot(Volume ~ Girth, data = trees, log = "xy")
coplot(log(Volume) ~ log(Girth) | Height, data = trees,
       panel = panel.smooth)
summary(fm1 <- lm(log(Volume) ~ log(Girth), data = trees))
summary(fm2 <- update(fm1, ~ . + log(Height), data = trees))
step(fm2)
## i.e., Volume ~= c * Height * Girth^2  seems reasonable
}
\keyword{datasets}
\eof
\name{try}
\alias{try}
\title{Try an Expression Allowing Error Recovery}
\description{
  \code{try} is a wrapper to run an expression that might fail and allow
  the user's code to handle error-recovery.
}
\usage{
try(expr, silent = FALSE)
}
\arguments{
  \item{expr}{an \R expression to try.}
  \item{silent}{logical: should the report of error messages be suppressed?}
}
\details{
  \code{try} evaluates an expression and traps any errors that occur
  during the evaluation.  \code{try} establishes a handler for
  errors that uses the default error handling protocol. It also
  establishes a \code{tryRestart} restart that can be used by
  \code{invokeRestart}.
}
\value{
  The value of the expression if \code{expr} is evaluated without error,
  but an invisible object of class \code{"try-error"} containing the
  error message if it fails. The normal error handling will print the
  same message unless \code{options("show.error.messages")} is false or
  the call includes \code{silent = TRUE}.
}
\seealso{
  \code{\link{options}} for setting error handlers and suppressing the
  printing of error messages;
  \code{\link{geterrmessage}} for retrieving the last error message.
  \code{tryCatch} provides another means of catching and handling
  errors.
}
\examples{
## this example will not work correctly in example(try), but
## it does work correctly if pasted in
options(show.error.messages = FALSE)
try(log("a"))
print(.Last.value)
options(show.error.messages = TRUE)

## alternatively,
print(try(log("a"), TRUE))

## run a simulation, keep only the results that worked.
set.seed(123)
x <- rnorm(50)
doit <- function(x)
{
    x <- sample(x, replace=TRUE)
    if(length(unique(x)) > 30) mean(x)
    else stop("too few unique points")
}
## alternative 1
res <- lapply(1:100, function(i) try(doit(x), TRUE))
## alternative 2
\dontrun{res <- vector("list", 100)
for(i in 1:100) res[[i]] <- try(doit(x), TRUE)}
unlist(res[sapply(res, function(x) !inherits(x, "try-error"))])
}
\keyword{programming}
\eof
\name{ts-methods}
\alias{diff.ts}
\alias{na.omit.ts}
\title{Methods for Time Series Objects}
\description{
  Methods for objects of class \code{"ts"}, typically the result of
  \code{\link{ts}}.
}
\usage{
\method{diff}{ts}(x, lag=1, differences=1, \dots)

\method{na.omit}{ts}(object, \dots)
}
\arguments{
  \item{x}{an object of class \code{"ts"} containing the values to be
    differenced.}
  \item{lag}{an integer indicating which lag to use.}
  \item{differences}{an integer indicating the order of the difference.}
  \item{object}{a univariate or multivariate time series.}
  \item{\dots}{further arguments to be passed to or from methods.}
}
\details{
  The \code{na.omit} method omits initial and final segments with
  missing values in one or more of the series.  \sQuote{Internal}
  missing values will lead to failure.
}
\value{
  For the \code{na.omit} method, a time series without missing values.
  The class of \code{object} will be preserved.
}
\seealso{
  \code{\link{diff}};
  \code{\link{na.omit}}, \code{\link{na.fail}},
  \code{\link[ts]{na.contiguous}}.
}
\keyword{ts}
\eof
\name{ts}
\title{Time-Series Objects}
\alias{ts}
\alias{as.ts}
\alias{is.ts}
\alias{Ops.ts}
\alias{cbind.ts}
\alias{is.mts}
\description{
  The function \code{ts} is used to create time-series objects.

  \code{as.ts} and \code{is.ts} coerce an object to a time-series and
  test whether an object is a time series.
}
\usage{
ts(data = NA, start = 1, end = numeric(0), frequency = 1,
   deltat = 1, ts.eps = getOption("ts.eps"), class = , names = )
as.ts(x)
is.ts(x)
}
\arguments{
  \item{data}{a numeric vector or matrix of the observed time-series
    values. A data frame will be coerced to a numeric matrix via
    \code{data.matrix}.}
  \item{start}{the time of the first observation.  Either a single
    number or a vector of two integers, which specify a natural time
    unit and a (1-based) number of samples into the time unit.  See
    the examples for the use of the second form.}
  \item{end}{the time of the last observation, specified in the same way
    as \code{start}.}
  \item{frequency}{the number of observations per unit of time.}
  \item{deltat}{the fraction of the sampling period between successive
    observations; e.g., 1/12 for monthly data.  Only one of
    \code{frequency} or \code{deltat} should be provided.}
  \item{ts.eps}{time series comparison tolerance.  Frequencies are
    considered equal if their absolute difference is less than
    \code{ts.eps}.}
  \item{class}{class to be given to the result, or none if \code{NULL}
    or \code{"none"}.  The default is \code{"ts"} for a single series,
    \code{c("mts", "ts")} for multiple series.}
  \item{names}{a character vector of names for the series in a multiple
    series: defaults to the colnames of \code{data}, or \code{Series 1},
    \code{Series 2}, \dots.}
  \item{x}{an arbitrary \R object.}
}
\details{
  The function \code{ts} is used to create time-series objects.  These
  are vector or matrices with class of \code{"ts"} (and additional
  attributes) which represent data which has been sampled at equispaced
  points in time.  In the matrix case, each column of the matrix
  \code{data} is assumed to contain a single (univariate) time series.
  Time series must have an least one observation, and although they need
  not be no numeric there is very limited support for non-numeric series.

  Class \code{"ts"} has a number of methods.  In particular arithmetic
  will attempt to align time axes, and subsetting to extract subsets of
  series can be used (e.g., \code{EuStockMarkets[, "DAX"]}).  However,
  subsetting the first (or only) dimension will return a matrix or
  vector, as will matrix subsetting.

  The value of argument \code{frequency} is used when the series is
  sampled an integral number of times in each unit time interval.  For
  example, one could use a value of \code{7} for \code{frequency} when
  the data are sampled daily, and the natural time period is a week, or
  \code{12} when the data are sampled monthly and the natural time
  period is a year.  Values of \code{4} and \code{12} are assumed in
  (e.g.) \code{print} methods to imply a quarterly and monthly series
  respectively.

  \code{as.ts} will use the \code{\link{tsp}} attribute of the object if
  it has one to set the start and end times and frequency.

  \code{is.ts} tests if an object is a time series. It is generic: you
  can write methods to handle of specific classes of objects,
  see \link{InternalMethods}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{tsp}},
  \code{\link{frequency}},
  \code{\link{start}},
  \code{\link{end}},
  \code{\link{time}},
  \code{\link{window}};
  \code{\link{print.ts}}, the print method for time series objects;
  \code{\link{plot.ts}}, the plot method for time series objects.
  Standard package \pkg{ts} for many additional time-series functions.
}
\examples{
ts(1:10, frequency = 4, start = c(1959, 2)) # 2nd Quarter of 1959
print( ts(1:10, freq = 7, start = c(12, 2)), calendar = TRUE) # print.ts(.)
## Using July 1954 as start date:
gnp <- ts(cumsum(1 + round(rnorm(100), 2)),
          start = c(1954, 7), frequency = 12)
plot(gnp) # using 'plot.ts' for time-series plot

## Multivariate
z <- ts(matrix(rnorm(300), 100, 3), start=c(1961, 1), frequency=12)
class(z)
plot(z)
plot(z, plot.type="single", lty=1:3)

## A phase plot:
data(nhtemp)
plot(nhtemp, c(nhtemp[-1], NA), cex = .8, col="blue",
     main = "Lag plot of New Haven temperatures")
## a clearer way to do this would be
\dontrun{library(ts)
plot(nhtemp, lag(nhtemp, 1), cex = .8, col="blue",
     main = "Lag plot of New Haven temperatures")
}}
\keyword{ts}
\eof
\name{tsp}
\title{Tsp Attribute of Time-Series-like Objects}
\alias{tsp}
\alias{tsp<-}
\alias{hasTsp}
\usage{
tsp(x)
tsp(x) <- value
hasTsp(x)
}
\arguments{
    \item{x}{a vector or matrix or univariate or multivariate time-series.}
    \item{value}{a numeric vector of length 3 or \code{NULL}.}
}
\description{
    \code{tsp} returns the \code{tsp} attribute (or \code{NULL}).
    It is included for compatibility with S version 2. \code{tsp<-}
    sets the \code{tsp} attribute. \code{hasTsp} ensures \code{x} has a
    \code{tsp} attribute, by adding one if needed.
}
\details{
    The \code{tsp} attribute was previously described here as
    \code{c(start(x), end(x), frequency(x))}, but this is incorrect.
    It gives the start time \emph{in time units}, the end time and
    the frequency.

    Assignments are checked for consistency.    

    Assigning \code{NULL} which removes the \code{tsp} attribute
    \emph{and} any \code{"ts"} class of \code{x}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
    \code{\link{ts}}, \code{\link{time}}, \code{\link{start}}.
}
\keyword{ts}
\eof
\name{type.convert}
\alias{type.convert}
\title{Type Conversion on Character Variables}
\description{
  Convert a character vector to logical, integer, numeric, complex or
  factor as appropriate.
}
\usage{
type.convert(x, na.strings = "NA", as.is = FALSE, dec = ".")
}
\arguments{
  \item{x}{a character vector.}

  \item{na.strings}{a vector of strings which are to be interpreted as
    \code{\link{NA}} values.  Blank fields are also considered to be
    missing values.}

  \item{as.is}{logical. See Details.}

  \item{dec}{the character to be assumed for decimal points.}
}
\details{
  This is principally a helper function for \code{\link{read.table}}.
  Given a character vector, it attempts to convert it to logical,
  integer, numeric or complex, and failing that converts it to factor
  unless \code{as.is = TRUE}.  The first type that can accept all the
  non-missing values is chosen.

  Vectors which are entirely missing values are converted to logical,
  since \code{NA} is primarily logical.
}
\value{
  A vector of the selected class, or a factor.
}

\seealso{\code{\link{read.table}}}

\keyword{manip}
\eof
\name{typeof}
\alias{typeof}
\title{The Type of an Object}
\description{
  \code{typeof} determines the (\R internal)
  type or storage mode of any object
}
\usage{
typeof(x)
}
\arguments{
  \item{x}{any \R object.}
}
\value{
  A character string.
}
\seealso{
  \code{\link{mode}}, \code{\link{storage.mode}}.
}
\examples{
typeof(2)
mode(2)
}
\keyword{attribute}
\eof
\name{unique}
\alias{unique}
\alias{unique.default}
\alias{unique.data.frame}
\alias{unique.matrix}
\alias{unique.array}
\title{Extract Unique Elements}
\description{
  \code{unique} returns a vector, data frame or array like \code{x}
  but with duplicate  elements removed.
}
\usage{
unique(x, incomparables = FALSE, \dots)

\method{unique}{array}(x, incomparables = FALSE, MARGIN = 1, \dots)
}
\arguments{
  \item{x}{an atomic vector or a data frame or an array.}
  \item{incomparables}{a vector of values that cannot be compared.
    Currently, \code{FALSE} is the only possible value, meaning that all
    values can be compared.}
  \item{\dots}{arguments for particular methods.}
  \item{MARGIN}{the array margin to be held fixed: a single integer.}
}
\details{
  This is a generic function with methods for vectors, data frames and
  arrays (including matrices).

  The array method calculates for each element of the dimension
  specified by \code{MARGIN} if the remaining dimensions are identical
  to those for an earlier element (in row-major order).  This would most
  commonly be used to find unique rows (the default) or columns
  (with \code{MARGIN = 2}).
}
\value{
  An object of the same type of \code{x}. but if
  an element is equal to one with a smaller index, it is removed.
  Dimensions of arrays are not dropped.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{duplicated}} which gives the indices of duplicated
  elements.
}
\examples{
unique(c(3:5, 11:8, 8 + 0:5))
length(unique(sample(100, 100, replace=TRUE)))
## approximately 100(1 - 1/e) = 63.21

data(iris)
unique(iris)
}
\keyword{manip}
\keyword{logic}
\eof
\name{uniroot}
\title{One Dimensional Root (Zero) Finding}
\usage{
uniroot(f, interval, lower = min(interval), upper = max(interval),
        tol = .Machine$double.eps^0.25, maxiter = 1000, \dots)
}
\alias{uniroot}
\arguments{
  \item{f}{the function for which the root is sought.}
  \item{interval}{a vector containing the end-points of the interval
    to be searched for the root.}
  \item{lower}{the lower end point of the interval to be searched.}
  \item{upper}{the upper end point of the interval to be searched.}
  \item{tol}{the desired accuracy (convergence tolerance).}
  \item{maxiter}{the maximum number of iterations.}
  \item{\dots}{additional arguments to \code{f}.}
}
\description{
  The function \code{uniroot} searches the interval from \code{lower}
  to \code{upper} for a root (i.e., zero) of the function \code{f} with
  respect to its first argument.
}
\details{
  Either \code{interval} or both \code{lower} and \code{upper} must be
  specified.  The function uses Fortran subroutine \file{"zeroin"} (from
  Netlib) based on algorithms given in the reference below.

  If the algorithm does not converge in \code{maxiter} steps, a warning
  is printed and the current approximation is returned.
}
\value{
  A list with four components: \code{root} and \code{f.root} give the
  location of the root and the value of the function evaluated at that
  point. \code{iter} and \code{estim.prec} give the number of iterations
  used and an approximate estimated precision for \code{root}.
}
\references{
  Brent, R. (1973)
  \emph{Algorithms for Minimization without Derivatives.}
  Englewood Cliffs, NJ: Prentice-Hall.
}
\seealso{
  \code{\link{polyroot}} for all complex roots of a polynomial;
  \code{\link{optimize}}, \code{\link{nlm}}.
}
\examples{
f <- function (x,a) x - a
str(xmin <- uniroot(f, c(0, 1), tol = 0.0001, a = 1/3))
str(uniroot(function(x) x*(x^2-1) + .5, low = -2, up = 2, tol = 0.0001),
    dig = 10)
str(uniroot(function(x) x*(x^2-1) + .5, low = -2, up =2 , tol = 1e-10 ),
    dig = 10)

## Find the smallest value x for which exp(x) > 0 (numerically):
r <- uniroot(function(x) 1e80*exp(x) -1e-300,,-1000,0, tol=1e-20)
str(r, digits= 15)##> around -745.1332191

exp(r$r)	# = 0, but not for r$r * 0.999...
minexp <- r$r * (1 - .Machine$double.eps)
exp(minexp)	# typically denormalized
}
\keyword{optimize}
\eof
\name{units}
\alias{xinch}
\alias{yinch}
\alias{xyinch}
\alias{cm}
\title{Graphical Units}
\description{
  \code{xinch} and \code{yinch} convert the specified number of inches
  given as their arguments into the correct units for plotting with
  graphics functions.  Usually, this only makes sense when normal
  coordinates are used, i.e., \emph{no} \code{log} scale (see the
  \code{log} argument to \code{\link{par}}).

  \code{xyinch} does the same for a pair of numbers \code{xy},
  simultaneously.

  \code{cm} translates inches in to cm (centimeters).
}
\usage{
xinch(x = 1, warn.log = TRUE)
yinch(y = 1, warn.log = TRUE)
xyinch(xy = 1, warn.log = TRUE)
cm(x)
}
\arguments{
  \item{x,y}{numeric vector}
  \item{xy}{numeric of length 1 or 2.}
  \item{warn.log}{logical; if \code{TRUE}, a warning is printed in case
    of active log scale.}
}
\examples{
all(c(xinch(),yinch()) == xyinch()) # TRUE
xyinch()
xyinch #- to see that is really   delta{"usr"} / "pin"

cm(1)# = 2.54

## plot labels offset 0.12 inches to the right
## of plotted symbols in a plot
data(mtcars)
with(mtcars, {
    plot(mpg, disp, pch=19, main= "Motor Trend Cars")
    text(mpg + xinch(0.12), disp, row.names(mtcars),
         adj = 0, cex = .7, col = 'blue')
    })
}
\keyword{dplot}
\eof
\name{unlink}
\title{Delete Files and Directories}
\usage{unlink(x, recursive = FALSE)}
\alias{unlink}
\arguments{
  \item{x}{a character vector with the names of the file(s) or
    directories to be deleted.
    Wildcards (normally \file{*} and \file{?}) are allowed.}
  \item{recursive}{logical. Should directories be deleted
    recusively?}
}
\description{
  \code{unlink} deletes the file(s) or directories specified by \code{x}.
}
\details{
  If \code{recusive = FALSE} directories are not deleted,
  not even empty ones.

  \code{\link{file.remove}} can only remove files, but gives more
  detailed error information.
}
\value{
#ifdef unix
  The return value of the corresponding system command, \code{rm -f},
  normally \code{0} for success, \code{1} for failure.
#endif
#ifdef windows
  \code{0} for success, \code{1} for failure.
#endif
  Not deleting a non-existent file is not a failure.
}
\note{
  Prior to \R version 1.2.0 the default on Unix was \code{recursive =
    TRUE}, and on Windows empty directories could be deleted.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{file.remove}}.
}
%Examples: tempfile has an 'unlink' example
\keyword{file}
\eof
\name{unlist}
\title{Flatten Lists}
\description{
  Given a list structure \code{x}, \code{unlist} simplifies it to
  produce a vector which contains all the atomic components
  which occur in \code{x}.
}
\usage{
unlist(x, recursive = TRUE, use.names = TRUE)
}
\alias{unlist}
\arguments{
  \item{x}{A list or vector.}
  \item{recursive}{logical. Should unlisting be applied to list
    components of \code{x}?}
  \item{use.names}{logical. Should names be preserved?}
}
\details{
  \code{unlist} is generic: you can write methods to handle
  of specific classes of objects, see \link{InternalMethods}.
  
  If \code{recursive = FALSE}, the function will not recurse beyond
  the first level items in \code{x}.

  \code{x} can be a vector, but then \code{unlist} does nothing useful,
  not even drop names.

  By default, \code{unlist} tries to retain the naming
  information present in \code{x}.
  If \code{use.names = FALSE} all naming information is dropped.

  Where possible the list elements are coerced to a common mode during
  the unlisting, and so the result often ends up as a character vector.

  A list is a (generic) vector, and the simplified vector might still be
  a list (and might be unchanged).  Non-vector elements of the list
  (for example language elements such as names, formulas and calls)
  are not coerced, and so a list containing one or more of these remains a
  list.  (The effect of unlisting an \code{\link{lm}} fit is a list which
  has individual residuals as components,)
}
\value{
  A vector of an appropriate mode to hold the list components.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{c}}, \code{\link{as.list}}.
}
\examples{
unlist(options())
unlist(options(), use.names=FALSE)

l.ex <- list(a = list(1:5, LETTERS[1:5]), b = "Z", c = NA)
unlist(l.ex, recursive = FALSE)
unlist(l.ex, recursive = TRUE)

l1 <- list(a="a", b=2, c=pi+2i)
unlist(l1) # a character vector
l2 <- list(a="a", b=as.name("b"), c=pi+2i)
unlist(l2) # remains a list
}
\keyword{list}
\keyword{manip}
\eof
\name{unname}
\alias{unname}
\title{Remove `names' or `dimnames'}
\description{
  Remove the \code{\link{names}} or \code{\link{dimnames}} attribute of
  an \R object.
}
\usage{
unname(obj, force = FALSE)
}
\arguments{
 \item{obj}{the \R object which is wanted \dQuote{nameless}.}
 \item{force}{logical; if true, the \code{dimnames} are even removed
   from \code{\link{data.frame}}s.
   \emph{This argument is currently \bold{experimental} and hence
     might change!}}
}
\value{
  Object as \code{obj} but without \code{\link{names}} or
  \code{\link{dimnames}}.
}
\examples{
## Answering a question on R-help (14 Oct 1999):
col3 <- 750+ 100* rt(1500, df = 3)
breaks <- factor(cut(col3,breaks=360+5*(0:155)))
str(table(breaks)) # The names are quite larger than the data ...
barplot(unname(table(breaks)), axes= FALSE)
}
\keyword{utilities}
\eof
\name{update}
\title{Update and Re-fit a Model Call}
\usage{
update(object, \dots)

\method{update}{default}(object, formula., \dots, evaluate = TRUE)
}
\alias{update}
\alias{update.default}
\arguments{
 \item{object}{An existing fit from a model function such as \code{lm},
   \code{glm} and many others.}
 \item{formula.}{Changes to the formula -- see \code{update.formula} for
   details.}
 \item{\dots}{Additional arguments to the call, or arguments with
   changed values. Use \code{name=NULL} to remove the argument \code{name}.}
 \item{evaluate}{If true evaluate the new call else return the call.}
}
\description{
\code{update} will update and (by default) re-fit a model. It does this
by extracting the call stored in the object, updating the call and (by
default) evaluating that call. Sometimes it is useful to call
\code{update} with only one argument, for example if the data frame has
been corrected.
}
\value{
  If \code{evaluate = TRUE} the fitted object, otherwise the updated call.
}
\seealso{
  \code{\link{update.formula}}
}
\references{
  Chambers, J. M. (1992)
  \emph{Linear models.}
  Chapter 4 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\examples{
oldcon <- options(contrasts = c("contr.treatment", "contr.poly"))
## Annette Dobson (1990) "An Introduction to Generalized Linear Models".
## Page 9: Plant Weight Data.
ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)
trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)
group <- gl(2, 10, 20, labels = c("Ctl", "Trt"))
weight <- c(ctl, trt)
lm.D9 <- lm(weight ~ group)
lm.D9
summary(lm.D90 <- update(lm.D9, . ~ . - 1))
options(contrasts = c("contr.helmert", "contr.poly"))
update(lm.D9)
options(oldcon)
}
\keyword{models}
\eof
\name{update.formula}
\alias{update.formula}
\title{Model Updating}
\usage{
\method{update}{formula}(old, new, ...)
}
\arguments{
  \item{old}{a model formula to be updated.}
  \item{new}{a formula giving a template which specifies how to update.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\description{
  \code{update.formula} is used to update model formulae.
  This typically involves adding or dropping terms,
  but updates can be more general.
}
\details{
  The function works by first identifying the \emph{left-hand side}
  and \emph{right-hand side} of the \code{old} formula.
  It then examines the \code{new} formula and substitutes
  the \emph{lhs} of the \code{old} formula for any occurence
  of "\code{.}" on the left of \code{new}, and substitutes
  the \emph{rhs} of the \code{old} formula for any occurence
  of "\code{.}" on the right of \code{new}.
}
\value{
  The updated formula is returned.
}
\seealso{
  \code{\link{terms}}, \code{\link{model.matrix}}.
}
\examples{
update(y ~ x,    ~ . + x2) #> y ~ x + x2
update(y ~ x, log(.) ~ . ) #> log(y) ~ x
}
\keyword{models}
\eof
\name{update.packages}
\alias{update.packages}
\alias{installed.packages}
\alias{CRAN.packages}
\alias{old.packages}
\alias{download.packages}
\alias{install.packages}
\alias{contrib.url}
\title{Download Packages from CRAN}}
\description{
  These functions can be used to automatically compare the version
  numbers of installed packages with the newest available version on
  CRAN and update outdated packages on the fly.}
}
\usage{
update.packages(lib.loc = NULL, CRAN = getOption("CRAN"),
                contriburl = contrib.url(CRAN),
                method, instlib = NULL,
                ask=TRUE, available=NULL, destdir=NULL,
		installWithVers=FALSE)

installed.packages(lib.loc = NULL, priority = NULL)
CRAN.packages(CRAN = getOption("CRAN"), method,
              contriburl = contrib.url(CRAN))
old.packages(lib.loc = NULL, CRAN = getOption("CRAN"),
             contriburl = contrib.url(CRAN),
             method, available = NULL)

download.packages(pkgs, destdir, available = NULL,
                  CRAN = getOption("CRAN"),
                  contriburl = contrib.url(CRAN), method)
install.packages(pkgs, lib, CRAN = getOption("CRAN"),
                 contriburl = contrib.url(CRAN),
                 method, available = NULL, destdir = NULL,
		 installWithVers = FALSE)
}
\arguments{
  \item{lib.loc}{character vector describing the location of R
    library trees to search through (and update packages therein).}
  \item{CRAN}{character, the base URL of the CRAN mirror to use, i.e.,
    the URL of a CRAN root such as \code{"http://cran.r-project.org"}
    (the default) or its Statlib mirror,
    \code{"http://lib.stat.cmu.edu/R/CRAN"}.}
  \item{contriburl}{URL of the contrib section of CRAN. Use this argument
    only if your CRAN mirror is incomplete, e.g., because you burned
    only the contrib section on a CD.  Overrides argument \code{CRAN}.}
  \item{method}{Download method, see \code{\link{download.file}}.}
  \item{pkgs}{character vector of the short names of
    packages whose current versions should be downloaded from \code{CRAN}.}
  \item{destdir}{directory where downloaded packages are stored.}
  \item{priority}{character vector or \code{NULL} (default).  If
    non-null, used to select packages; \code{"high"} is equivalent to
    \code{c("base","recommended")}.}
  \item{available}{list of packages available at CRAN as returned by
    \code{CRAN.packages}.}
  \item{lib,instlib}{character string giving the library directory where to
    install the packages.}
  \item{ask}{logical indicating to ask before packages are actually downloaded
    and installed.}
  \item{installWithVers}{If \code{TRUE}, will invoke the install the
    package such that it can be referenced by package version}
}
\details{
  \code{installed.packages} scans the \file{DESCRIPTION} files of each
  package found along \code{lib.loc} and returns a list of package
  names, library paths and version numbers.  \code{CRAN.packages}
  returns a similar list, but corresponding to packages currently
  available in the contrib section of CRAN, the comprehensive R archive
  network.  The current list of packages is downloaded over the internet
  (or copied from a local CRAN mirror). Both functions use
  \code{\link{read.dcf}} for parsing the description files.
  \code{old.packages} compares the two lists and reports installed
  packages that have newer versions on CRAN.

  \code{download.packages} takes a list of package names and a
  destination directory, downloads the newest versions of the package
  sources and saves them in \code{destdir}.  If the list of available
  packages is not given as argument, it is also directly obtained from
  CRAN.  If CRAN is local, i.e., the URL starts with \code{"file:"},
  then the packages are not downloaded but used directly.

  The main function of the bundle is \code{update.packages}.  First a
  list of all packages found in \code{lib.loc} is created and compared
  with the packages available on CRAN.  Outdated packages are reported
  and for each outdated package the user can specify if it should be
  automatically updated.
#ifdef unix
  If so, the package sources are downloaded from
  CRAN and installed in the respective library path (or \code{instlib}
  if specified) using the \R \code{\link{INSTALL}} mechanism.
#endif
#ifdef windows
  If so, the pre-compiled packages are
  downloaded from CRAN and installed in the respective library path (or
  \code{instlib} if specified).
#endif

  \code{install.packages} can be used to install new packages, it
  takes a vector of package names and a destination library, downloads
  the packages from CRAN and installs them. If the library
  is omitted it defaults to the first directory in \code{.libPaths()}, with
  a warning if there is more than one.
%  The first argument can be an unquoted name, as in
%  \code{install.packages(nlme)}.
#ifdef windows
  Argument \code{pkgs} can also be a character vector of file names of
  zip files if \code{CRAN=NULL}. The zip files are then unpacked directly.
#endif

  For \code{install.packages} and \code{update.packages}, \code{destdir}
  is the directory to which packages will be downloaded. If it is
  \code{NULL} (the default) a temporary directory is used, and the user
  will be given the option of deleting the temporary files once the
  packages are installed.  (They will always be deleted at the end of
  the \R session.)
}
\seealso{
  See \code{\link{download.file}} for how to handle proxies and
  other options to monitor file transfers.

#ifdef unix
  \code{\link{INSTALL}}, \code{\link{REMOVE}},
#endif
  \code{\link{library}}, \code{\link{.packages}}, \code{\link{read.dcf}}
}
\examples{
str(ip <- installed.packages(priority = "high"))
ip[, c(1,3:5)]
}
\keyword{utilities}
\eof
\name{url.show}
\alias{url.show}
\title{Display a text URL}
\description{
  Extension of \code{\link{file.show}} to display text files on a remote 
  server.
}
\usage{
url.show(url, title = url, file = tempfile(),
         delete.file = TRUE, method, \dots)
}
\arguments{
  \item{url}{The URL to read from.}
  \item{title}{Title for the browser.}
  \item{file}{File to copy to.}
  \item{delete.file}{Delete the file afterwards?}
  \item{method}{File transfer method: see \code{\link{download.file}}}
  \item{\dots}{Arguments to pass to \code{\link{file.show}}.}
}
\seealso{
  \code{\link{url}}, \code{\link{file.show}},\code{\link{download.file}}
}
\examples{
\dontrun{url.show("http://lib.stat.cmu.edu/datasets/csb/ch3a.txt")}
}
\keyword{file}
\keyword{misc}
\eof
\name{uspop}
\docType{data}
\alias{uspop}
\title{Populations Recorded by the US Census}
\description{
  This data set gives the population of the United States (in millions)
  as recorded by the decennial census for the period 1790--1970.
}
\usage{data(uspop)}
\format{A time series of 19 values.}
\source{
  McNeil, D. R. (1977)
  \emph{Interactive Data Analysis}.
  New York: Wiley.
}
% FIXME: missing \references{}
\examples{
data(uspop)
plot(uspop, log = "y", main = "uspop data", xlab = "Year",
     ylab = "U.S. Population (millions)")
}
\keyword{datasets}
\eof
\name{vcov}
\alias{vcov}
\alias{vcov.lm}
\alias{vcov.glm}
\alias{vcov.lme}
\alias{vcov.gls}
\alias{vcov.coxph}
\alias{vcov.survreg}
\title{
Calculate Variance-Covariance Matrix for a Fitted Model Object
}
\description{
Returns the variance-covariance matrix of the main parameters of
a fitted model object.
}
\usage{
vcov(object, \dots)
}
\arguments{
  \item{object}{
    a fitted model object.
  }
  \item{\dots}{
    additional arguments for method functions.  For the
    \code{\link{glm}} method this can be used to pass a
    \code{dispersion} parameter.
  }
}
\value{
  A matrix of the estimated covariances between the parameter estimates
  in the linear or non-linear predictor of the model.
}
\details{
This is a generic function.
Functions with names beginning in \code{vcov.} will be
methods for this function.
Classes with methods for this function include:
\code{lm}, \code{glm}, \code{nls}, \code{lme}, \code{gls}, \code{coxph}
and \code{survreg}
}
\keyword{models}
\keyword{nonlinear}
\eof
\name{vector}
\title{Vectors}
\usage{
vector(mode = "logical", length = 0)
as.vector(x, mode = "any")
is.vector(x, mode = "any")
}
\alias{vector}
\alias{as.vector}
\alias{as.vector.factor}
\alias{is.vector}
\arguments{
  \item{mode}{A character string giving an atomic mode, or \code{"any"}.}
  \item{length}{A non-negative integer specifying the desired length.}
  \item{x}{An object.}
}
\description{
  \code{vector} produces a vector of the given length and mode.

  \code{as.vector}, a generic, attempts to coerce its argument into a
  vector of mode \code{mode} (the default is to coerce to whichever mode
  is most convenient).  The attributes of \code{x} are removed.

  \code{is.vector} returns \code{TRUE} if \code{x} is a vector (of mode
  logical, integer, real, complex, character or list if not specified)
  and \code{FALSE} otherwise.
}
\details{
  \code{is.vector} returns \code{FALSE} if \code{x} has any attributes
  except names.  (This is incompatible with S.)  On the other hand,
  \code{as.vector} removes \emph{all} attributes including names.
  
  Note that factors are \emph{not} vectors;  \code{is.vector} returns
  \code{FALSE} and \code{as.vector} converts to character mode.
}
\value{
  For \code{vector}, a vector of the given length and mode.  Logical
  vector elements are initialized to \code{FALSE}, numeric vector
  elements to \code{0} and character vector elements to \code{""}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
\code{\link{c}}, \code{\link{is.numeric}}, \code{\link{is.list}}, etc.
}
\examples{
df <- data.frame(x=1:3, y=5:7)
\dontrun{## Error:
  as.vector(data.frame(x=1:3, y=5:7), mode="numeric")
}

x <- c(a = 1, b = 2)
is.vector(x)
as.vector(x)
all.equal(x, as.vector(x)) ## FALSE


###-- All the following are TRUE:
is.list(df)
! is.vector(df)
! is.vector(df, mode="list")

is.vector(list(), mode="list")
is.vector(NULL,   mode="NULL")
}
\keyword{classes}
\eof
\name{vignette}
\alias{vignette}
\title{View or List Vignettes}
\description{
  View a specified vignette, or list the available ones.
}
\usage{
vignette(topic, package = NULL, lib.loc = NULL)
}
\arguments{
  \item{topic}{a character string giving the (base) name of the vignette
    to view.}
  \item{package}{a character vector with the names of packages to
    search through, or \code{NULL} in which case \emph{all} available
    packages in the library trees specified by \code{lib.loc} are
    searched.}
  \item{lib.loc}{a character vector of directory names of \R libraries,
    or \code{NULL}.  The default value of \code{NULL} corresponds to all
    libraries currently known.}
}
\details{
  Currently, only PDF versions of vignettes can be viewed.
#ifdef unix
  The program specified by the \code{pdfviewer} option is used for this.
#endif
  If several vignettes have PDF versions with base name identical to
  \code{topic}, the first one found is used for viewing.

  If no topics are given, the available vignettes are listed.  The
  corresponding information is returned in an object of class
  \code{"packageIQR"}.  The structure of this class is experimental.
}
\examples{
## List vignettes in all attached packages
vignette()
## List vignettes in all available packages
vignette(package = .packages(all.available = TRUE))
}
\keyword{documentation}
  
  
\eof
\name{volcano}
\docType{data}
\alias{volcano}
\title{Topographic Information on Auckland's Maunga Whau Volcano}
\description{
  Maunga Whau (Mt Eden) is one of about 50 volcanos in the Auckland
  volcanic field.  This data set gives topographic information for
  Maunga Whau on a 10m by 10m grid.
}
\usage{data(volcano)}
\format{
  A matrix with 87 rows and 61 columns, rows corresponding to grid lines
  running east to west and columns to grid lines running south to
  north.}
\source{
  Digitized from a topographic map by Ross Ihaka.
  These data should not be regarded as accurate.
}
% FIXME: missing \references{}
\seealso{\code{\link{filled.contour}} for a nice plot.}
\examples{
data(volcano)
filled.contour(volcano, color = terrain.colors, asp = 1)
title(main = "volcano data: filled contour map")
}
\keyword{datasets}
\eof
\name{warning}
\alias{warning}
\alias{suppressWarnings}
\title{Warning Messages}
\description{
  Generates a warning message that corresponds to its argument(s) and
  (optionally) the expression or function from which it was called.
}
\usage{
warning(\dots, call. = TRUE)
suppressWarnings(expr)
}
\arguments{
  \item{\dots}{character vectors (which are pasted together with no
    separator), a condition object, or \code{NULL}.}
  \item{call.}{logical, indicating if the call should become part of the
    warning message.}
  \item{expr}{expression to evaluate.}
}
\details{
  The result \emph{depends} on the value of
  \code{\link{options}("warn")} and on handlers established in the
  executing code.

  \code{warning} signals a warning condition by (effectively) calling
  \code{signalCondition}.  If there are no handlers or if all handlers
  return, then the value of \code{warn} is used to determine the
  appropriate action.  If \code{warn} is negative warnings are
  ignored; if it is zero they are stored and printed after the
  top--level function has completed; if it is one they are printed as
  they occur and if it is 2 (or larger) warnings are turned into
  errors.

  If \code{warn} is zero (the default), a top-level variable
  \code{last.warning} is created.  It contains the warnings which can be
  printed via a call to \code{\link{warnings}}.

  Warnings will be truncated to \code{getOption("warning.length")}
  characters, default 1000.

  While the warning is being processed, a \code{muffleWarning} restart
  is available.  If this restart is invoked with \code{invokeRestart},
  then \code{warning} returns immediately.

   \code{suppressWarnings} evaluates its expression in a context that
   ignores all warnings.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{stop}} for fatal errors,
  \code{\link{warnings}},
  and \code{\link{options}} with argument \code{warn=}.
}
\examples{
\dontshow{oldopt <- options(warn=1)}
testit <- function() warning("testit")
testit() ## shows call
testit <- function() warning("problem in testit", call. = FALSE)
testit() ## no call
suppressWarnings(warning("testit"))
\dontshow{eigenval <- 10 ^ -rnorm(1, m=6)
if(eigenval < 1.e-7) warning("system near singular")
options(oldopt)}
}
\keyword{programming}
\keyword{error}
\eof
\name{warnings}
\alias{warnings}
\title{Print Warning Messages}
\description{
  \code{warnings} prints the top-level variable \code{last.warning} in a
  pleasing form.
}
\usage{
warnings(\dots)
}
\arguments{
  \item{\dots}{arguments to be passed to \code{\link{cat}}.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{\code{\link{warning}}.}
\examples{
ow <- options("warn")
for(w in -1:1) {
   options(warn = w); cat("\n warn =",w,"\n")
   for(i in 1:3) { cat(i,"..\n"); m <- matrix(1:7, 3,4) }
}
warnings()
options(ow) # reset
}
\keyword{programming}
\keyword{error}
\eof
\name{warpbreaks}
\docType{data}
\alias{warpbreaks}
\title{The Number of Breaks in Yarn during Weaving}
\description{
  This data set gives the number of warp breaks per loom, where a loom
  corresponds to a fixed length of yarn.
}
\usage{data(warpbreaks)}
\format{
  A data frame with 54 observations on 3 variables.
  \tabular{rlll}{
    \code{[,1]} \tab \code{breaks}  \tab numeric \tab The number of breaks\cr
    \code{[,2]} \tab \code{wool}    \tab factor  \tab The type of wool (A or B)\cr
    \code{[,3]} \tab \code{tension} \tab factor  \tab The level of tension (L, M, H)
  }
  There are measurements on 9 looms for each of the six types of warp
  (AL, AM, AH, BL, BM, BH).
}
\source{
  Tippett, L. H. C. (1950)
  \emph{Technological Applications of Statistics}.
  Wiley.  Page 106.

}
\references{
  Tukey, J. W. (1977)
  \emph{Exploratory Data Analysis}.
  Addison-Wesley.

  McNeil, D. R. (1977)
  \emph{Interactive Data Analysis}.
  Wiley.
}
\seealso{
  \code{\link{xtabs}} for ways to display these data as a table.
}
\examples{
data(warpbreaks)
summary(warpbreaks)
opar <- par(mfrow = c(1,2), oma = c(0, 0, 1.1, 0))
plot(breaks ~ tension, data = warpbreaks, col = "lightgray",
     varwidth = TRUE, subset = wool == "A", main = "Wool A")
plot(breaks ~ tension, data = warpbreaks, col = "lightgray",
     varwidth = TRUE, subset = wool == "B", main = "Wool B")
mtext("warpbreaks data", side = 3, outer = TRUE)
par(opar)
summary(fm1 <- lm(breaks ~ wool*tension, data = warpbreaks))
anova(fm1)
}
\keyword{datasets}
\eof
\name{weekdays}
\alias{weekdays}
\alias{weekdays.POSIXt}
\alias{months}
\alias{months.POSIXt}
\alias{quarters}
\alias{quarters.POSIXt}
\alias{julian}
\alias{julian.POSIXt}
\title{Extract Parts of a POSIXt Object}
\description{
  Extract the weekday, month or quarter, or the Julian time
  (days since some origin).  These are generic functions: the methods
  for the internal date-time classes are documented here.
}
\usage{
weekdays(x, abbreviate)
\method{weekdays}{POSIXt}(x, abbreviate = FALSE)

months(x, abbreviate)
\method{months}{POSIXt}(x, abbreviate = FALSE)

quarters(x, abbreviate)
\method{quarters}{POSIXt}(x, \dots)

julian(x, \dots)
\method{julian}{POSIXt}(x, origin = as.POSIXct("1970-01-01", tz="GMT"), \dots)
}
\arguments{
  \item{x}{an object inheriting from class \code{"POSIXt"}.}
  \item{abbreviate}{logical.  Should the names be abbreviated?}
  \item{origin}{an length-one object inheriting from class \code{"POSIXt"}.}
  \item{\dots}{arguments for other methods.}
}
\value{
  \code{weekdays} and \code{months} return a character
  vector of names in the locale in use.

  \code{quarters} returns a character vector of \code{"Q1"} to
  \code{"Q4"}.

  \code{julian} returns the number of days (possibly fractional)
  since the origin, with the origin as a \code{"origin"} attribute.
}
\note{
  Other components such as the day of the month or the year are
  very easy to compute: just use \code{\link{as.POSIXlt}} and extract the
  relevant component.
}

\seealso{\code{\link{DateTimeClasses}}}

\examples{
weekdays(.leap.seconds)
months(.leap.seconds)
quarters(.leap.seconds)
}
\keyword{chron}
\eof
\name{weighted.mean}
\title{Weighted Arithmetic Mean}
\usage{
weighted.mean(x, w, na.rm=FALSE)
}
\alias{weighted.mean}
\arguments{
  \item{x}{a numeric vector containing the values
    whose mean is to be computed.}
  \item{w}{a vector of weights the same length as \code{x} giving
    the weights to use for each element of \code{x}.}
  \item{na.rm}{a logical value indicating whether \code{NA}
    values in \code{x} should be stripped before the computation proceeds.}
}
\description{
  Compute a weighted mean of a numeric vector.
}
\details{
  If \code{w} is missing then all elements of \code{x} are
  given the same weight.
  
  Missing values in \code{w} are not handled.
}
\seealso{\code{\link{mean}}
}
\examples{
## GPA from Siegel 1994
wt <- c(5,  5,  4,  1)/15
x <- c(3.7,3.3,3.5,2.8)
xm <- weighted.mean(x,wt)
}
\keyword{univar}
\eof
\name{weighted.residuals}
\alias{weighted.residuals}
\title{Compute Weighted Residuals}
\usage{
weighted.residuals(obj, drop0 = TRUE)
}
\arguments{
  \item{obj}{\R object, typically of class \code{\link{lm}} or
    \code{\link{glm}}.}
  \item{drop0}{logical.  If \code{TRUE}, drop all cases with
    \code{\link{weights} == 0}.}
}
\description{
  Computed weighted residuals from a linear model fit.
}
\details{
  Weighted residuals are the usual residuals \eqn{R_i}{Ri}, multiplied
  by \eqn{\sqrt{w_i}}{wi^0.5}, where \eqn{w_i}{wi} are the
  \code{weights} as specified in \code{\link{lm}}'s call.

  Dropping cases with weights zero is compatible with
  \code{\link{influence}} and related functions.
}
\value{
  Numeric vector of length \eqn{n'}, where \eqn{n'} is the number of
  of non-0 weights (\code{drop0 = TRUE}) or the number of
  observations, otherwise.
}
\seealso{\code{\link{residuals}}, \code{\link{lm.influence}}, etc.}
\examples{
example("lm")
all.equal(weighted.residuals(lm.D9),
          residuals(lm.D9))
x <- 1:10
w <- 0:9
y <- rnorm(x)
weighted.residuals(lmxy <- lm(y ~ x, weights = w))
weighted.residuals(lmxy, drop0 = FALSE)
}
\keyword{regression}

\eof
\name{which}
\alias{which}
\title{Which indices are TRUE?}
\description{
  Give the \code{TRUE} indices of a logical object, allowing for array
  indices.
}
\usage{
which(x, arr.ind = FALSE)
}
\arguments{
 \item{x}{a \code{\link{logical}} vector or array.  \code{\link{NA}}s
   are allowed and omitted (treated as if \code{FALSE}).}
 \item{arr.ind}{logical; should \bold{arr}ay \bold{ind}ices be returned
   when \code{x} is an array?}
}
\value{
  If \code{arr.ind == FALSE} (the default), an integer vector with
  \code{length} equal to \code{sum(x)}, i.e., to the number of
  \code{TRUE}s in \code{x}; Basically, the result is
  \code{(1:length(x))[x]}.
  
  If \code{arr.ind == TRUE} and \code{x} is an \code{\link{array}} (has
  a \code{\link{dim}} attribute), the result is a matrix who's rows each
  are the indices of one element of \code{x}; see Examples below.
}
\author{Werner Stahel and Peter Holzer \email{holzer@stat.math.ethz.ch},
  for the array case.}
\seealso{\code{\link{Logic}}, \code{\link{which.min}} for the index of
  the minimum or maximum, and \code{\link{match}} for the first index of
  an element in a vector, i.e., for a scalar \code{a}, \code{match(a,x)}
  is equivalent to  \code{min(which(x == a))} but much more efficient.}
\examples{
which(LETTERS == "R")
which(ll <- c(TRUE,FALSE,TRUE,NA,FALSE,FALSE,TRUE))#> 1 3 7
names(ll) <- letters[seq(ll)]
which(ll)
which((1:12)\%\%2 == 0) # which are even?
str(which(1:10 > 3, arr.ind=TRUE))

( m <- matrix(1:12,3,4) )
which(m \%\% 3 == 0)
which(m \%\% 3 == 0, arr.ind=TRUE)
rownames(m) <- paste("Case",1:3, sep="_")
which(m \%\% 5 == 0, arr.ind=TRUE)

dim(m) <- c(2,2,3); m
which(m \%\% 3 == 0, arr.ind=FALSE)
which(m \%\% 3 == 0, arr.ind=TRUE)

vm <- c(m)
dim(vm) <- length(vm) #-- funny thing with  length(dim(...)) == 1
which(vm \%\% 3 == 0, arr.ind=TRUE)
}
\keyword{logic}
\keyword{attribute}
\eof
\name{which.min}
\alias{which.min}
\alias{which.max}
\title{Where is the Min() or Max() ?}
\description{
  Determines the location, i.e., index of the (first) minimum or maximum
  of a numeric vector.
}
\usage{
which.min(x)
which.max(x)
}
\arguments{
 \item{x}{numeric vector, whose \code{\link{min}} or \code{\link{max}}
   is searched.}
}
\value{
  an \code{\link{integer}} of length 1 or 0 (iff \code{x} has no
  non-\code{NA}s) , giving the index of the \emph{first} minimum or
  maximum respectively of \code{x}.

  If this extremum is unique (or empty), the result is the same (but more
  efficient) as  \code{which(x == min(x))} or \code{which(x == max(x))}
  respectively.
}
\author{Martin Maechler}
\seealso{
  \code{\link{which}}, \code{\link{max.col}}, \code{\link{max}}, etc.

  \code{\link[nnet]{which.is.max}} in package \pkg{nnet} differs in
  breaking ties at random (and having a \dQuote{fuzz} in the definition
  of ties).
}
\examples{
x <- c(1:4,0:5,11)
which.min(x)
which.max(x)

data(presidents)
presidents[1:30]
range(presidents, na.rm = TRUE)
which.min(presidents)# 28
which.max(presidents)# 2
}
\keyword{utilities}
\eof
\name{window}
\alias{window}
\alias{window.default}
\alias{window.ts}
\title{Time Windows}
\usage{
window(x, \dots)

\method{window}{ts}(x, \dots)

\method{window}{default}(x, start = NULL, end = NULL,
      frequency = NULL, deltat = NULL, extend = FALSE, \dots)
}
\arguments{
  \item{x}{a time-series or other object.}
  \item{start}{the start time of the period of interest.}
  \item{end}{the end time of the period of interest.}
  \item{frequency, deltat}{the new frequency can be specified by either
    (or both if they are consistent).}
  \item{extend}{logical. If true, the \code{start} and \code{end} values
    are allowed to extend the series. If false, attempts to extend the
    series give a warning and are ignored.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\description{
  \code{window} is a generic function which
  extracts the subset of the object \code{x}
  observed between the times \code{start} and \code{end}. If a
  frequency is specified, the series is then re-sampled at the new
  frequency.
}
\details{
  The start and end times can be specified as for \code{\link{ts}}. If
  there is no observation at the new \code{start} or \code{end},
  the immediately following (\code{start}) or preceding (\code{end})
  observation time is used.
}
\value{
  The value depends on the method. \code{window.default} will return a
  vector or matrix with an appropriate \code{\link{tsp}} attribute.

  \code{window.ts} differs from \code{window.default} only in
  ensuring the result is a \code{ts} object.

  If \code{extend = TRUE} the series will be padded with \code{NA} if
  needed.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{\code{\link{time}}, \code{\link{ts}}.}
\examples{
data(presidents)
window(presidents, 1960, c(1969,4)) # values in the 1960's
window(presidents, deltat=1)  # All Qtr1s
window(presidents, start=c(1945,3), deltat=1)  # All Qtr3s
window(presidents, 1944, c(1979,2), extend=TRUE)
}
\keyword{ts}
\eof
\name{with}
\alias{with}
\alias{with.default}
\title{Evaluate an Expression in a Data Environment}
\description{
  Evaluate an \R expression in an environment constructed from data.
}
\usage{
with(data, expr, \dots)
%\method{with}{default}(data, expr, \dots)
}
\arguments{
  \item{data}{data to use for constructing an environment. For the
    default method this may be an environment, a list, a data frame,
    or an integer as in \code{sys.call}.}
  \item{expr}{expression to evaluate.}
  \item{\dots}{arguments to be passed to future methods.}
}
\details{
  \code{with} is a generic function that evaluates \code{expr} in a
  local environment constructed from \code{data}.  The environment has
  the caller's environment as its parent.  This is useful for
  simplifying calls to modeling functions.

  Note that assignments within \code{expr} take place in the constructed
  environment and not in the user's workspace.
}
\seealso{
  \code{\link{evalq}}, \code{\link{attach}}.
}
\examples{
#examples from glm:
\dontrun{
library(MASS)
data(anorexia)
with(anorexia, {
    anorex.1 <- glm(Postwt ~ Prewt + Treat + offset(Prewt),
                    family = gaussian)
    summary(anorex.1)
})
}

with(data.frame(u = c(5,10,15,20,30,40,60,80,100),
                lot1 = c(118,58,42,35,27,25,21,19,18),
                lot2 = c(69,35,26,21,18,16,13,12,12)),
    list(summary(glm(lot1 ~ log(u), family=Gamma)),
         summary(glm(lot2 ~ log(u), family=Gamma))))

# example from boxplot:
data(ToothGrowth)
with(ToothGrowth, {
    boxplot(len ~ dose, boxwex = 0.25, at = 1:3 - 0.2,
            subset= supp == "VC", col="yellow",
            main="Guinea Pigs' Tooth Growth",
            xlab="Vitamin C dose mg",
            ylab="tooth length", ylim=c(0,35))
    boxplot(len ~ dose, add = TRUE, boxwex = 0.25, at = 1:3 + 0.2,
            subset= supp == "OJ", col="orange")
    legend(2, 9, c("Ascorbic acid", "Orange juice"),
           fill = c("yellow", "orange"))
})

# alternate form that avoids subset argument:
with(subset(ToothGrowth, supp == "VC"),
     boxplot(len ~ dose, boxwex = 0.25, at = 1:3 - 0.2,
             col="yellow", main="Guinea Pigs' Tooth Growth",
             xlab="Vitamin C dose mg",
             ylab="tooth length", ylim=c(0,35)))
with(subset(ToothGrowth,  supp == "OJ"),
     boxplot(len ~ dose, add = TRUE, boxwex = 0.25, at = 1:3 + 0.2,
             col="orange"))
legend(2, 9, c("Ascorbic acid", "Orange juice"),
       fill = c("yellow", "orange"))
}
\keyword{data}
\keyword{programming}
\eof
\name{women}
\docType{data}
\alias{women}
\title{Average Heights and Weights for American Women}
\description{
  This data set gives the average heights and weights for American women
  aged 30--39.
}
\usage{data(women)}
\format{A data frame with 15 observations on 2 variables.
  \tabular{rlll}{
    \code{[,1]}  \tab \code{height}  \tab numeric  \tab Height (in)\cr
    \code{[,2]}  \tab \code{weight}  \tab numeric  \tab Weight (lbs)
  }
}
\source{The World Almanac and Book of Facts, 1975.}
\details{
  The data set appears to have been taken from the American Society of
  Actuaries \emph{Build and Blood Pressure Study} for some (unknown to
  us) earlier year.
    
  The World Almanac notes: \dQuote{The figures represent weights in
    ordinary indoor clothing and shoes, and heights with shoes}.
}
\references{
  McNeil, D. R. (1977)
  \emph{Interactive Data Analysis}.
  Wiley.
}
\examples{
data(women)
plot(women, xlab = "Height (in)", ylab = "Weight (lb)",
     main = "women data: American women aged 30-39")
}
\keyword{datasets}
\eof
\name{write}
\title{Write Data to a File}
\usage{
write(x, file = "data",
      ncolumns = if(is.character(x)) 1 else 5,
      append = FALSE)
}
\alias{write}
\arguments{
  \item{x}{the data to be written out.}
  \item{file}{A connection, or  a character string naming the file to write to.
    If \code{""}, print to the standard output connection.
#ifdef unix
    If it is \code{"|cmd"}, the output is piped to the command given
    by \file{cmd}.
#endif
  }
  \item{ncolumns}{the number of columns to write the data in.}
  \item{append}{if \code{TRUE} the data \code{x} is appended to file \code{file}.}
}
\description{
  The data (usually a matrix) \code{x} are written to file \code{file}.
  If \code{x} is a two-dimensional matrix you need to transpose it to get the
  columns in \code{file} the same as those in the internal representation.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{save}} for writing any \R objects,
  \code{\link{write.table}} for data frames,
  and \code{\link{scan}} for reading data.
}
\examples{
# create a 2 by 5 matrix
x <- matrix(1:10,ncol=5)

# the file data contains x, two rows, five cols
# 1 3 5 6 9 will form the first row
write(t(x))

# the file data now contains the data in x,
# two rows, five cols but the first row is 1 2 3 4 5
write(x)
unlink("data") # tidy up
}
\keyword{file}
\keyword{connection}
\eof
\name{write.table}
\alias{write.table}
\title{Data Output}
\description{
  \code{write.table} prints its required argument \code{x} (after
  converting it to a data frame if it is not one already) to
  \code{file}.  The entries in each line (row) are separated by the
  value of \code{sep}.
}
\usage{
write.table(x, file = "", append = FALSE, quote = TRUE, sep = " ",
            eol = "\n", na = "NA", dec = ".", row.names = TRUE,
	    col.names = TRUE, qmethod = c("escape", "double"))
}
\arguments{
  \item{x}{the object to be written, typically a data frame.  If not, it
    is attempted to coerce \code{x} to a data frame.}
  \item{file}{either a character string naming a file or a connection.
    \code{""} indicates output to the console.}
  \item{append}{logical.  If \code{TRUE}, the output is appended to the
    file.  If \code{FALSE}, any existing file of the name is destroyed.}
  \item{quote}{a logical or a numeric vector.  If \code{TRUE}, any
    character or factor columns will be surrounded by double quotes.  If
    a numeric vector, its elements are taken as the indices of the
    variable (columns) to quote.  In both cases, row and columns names
    are quoted if they are written, but not if \code{quote is FALSE}.} 
  \item{sep}{the field separator string.  Values within each row of
    \code{x} are separated by this string.}
  \item{eol}{the character(s) to print at the end of each line (row).}
  \item{na}{the string to use for missing values in the data.}
  \item{dec}{the string to use for decimal points.}
  \item{row.names}{either a logical value indicating whether the row
    names of \code{x} are to be written along with \code{x}, or a
    character vector of row names to be written.}
  \item{col.names}{either a logical value indicating whether the column
    names of \code{x} are to be written along with \code{x}, or a
    character vector of column names to be written.}
  \item{qmethod}{a character string specifying how to deal with embedded
    double quote characters when quoting strings.  Must be one of
    \code{"escape"} (default), in which case the quote character is
    escaped in C style by a backslash, or \code{"double"}, in which case
    it is doubled.  You can specify just the initial letter.}
}
\details{
  Normally there is no column name for a column of row names.  If
  \code{col.names=NA} a blank column name is added.  This can be used to
  write CSV files for input to spreadsheets.

  \code{write.table} can be slow for data frames with large numbers
  (hundreds or more) of columns: this is inevitable as each column could
  be of a different class and so must be handled separately.
  Function \code{\link[MASS]{write.matrix}} in package \pkg{MASS}
  may be much more efficient if \code{x} is a matrix or can be
  represented in a numeric matrix.
}

\seealso{
  The \dQuote{R Data Import/Export} manual.
  
  \code{\link{read.table}}, \code{\link{write}}.

  \code{\link[MASS]{write.matrix}}.
}

\examples{
\dontrun{
## To write a CSV file for input to Excel one might use
write.table(x, file = "foo.csv", sep = ",", col.names = NA)
## and to read this file back into R one needs
read.table("file.csv", header = TRUE, sep = ",", row.names=1)
}}
\keyword{print}
\keyword{file}
\eof
\name{writeLines}
\alias{writeLines}
\title{Write Lines to a Connection}
\description{
  Write text lines to a connection.
}
\usage{
writeLines(text, con = stdout(), sep = "\n")
}
\arguments{
  \item{text}{A character vector}
  \item{con}{A connection object or a character string.}
  \item{sep}{character. A string to be written to the connection after
    each line of text.}
}
\details{
  If the \code{con} is a character string, the functions call
  \code{\link{file}} to obtain an file connection which is opened for
  the duration of the function call.

  If the connection is open it is written from its current position.
  If it is not open, it is opened for the duration of the call and then
  closed again.

  Normally \code{writeLines} is used with a text connection, and the
  default separator is converted to the normal separator for that
  platform (LF on Unix/Linux, CRLF on Windows, CR on Classic MacOS).  For
  more control, open a binary connection and specify the precise value
  you want written to the file in \code{sep}.  For even more control,
  use \code{\link{writeChar}} on a binary connection.
}
\seealso{
  \code{\link{connections}}, \code{\link{writeChar}}, \code{\link{writeBin}},
  \code{\link{readLines}}, \code{\link{cat}}
}

\keyword{file}
\keyword{connection}
\eof
\name{xfig}
\alias{xfig}
\title{XFig Graphics Device}
\description{
  \code{xfig} starts the graphics device driver for producing XFig
  (version 3.2) graphics.

  The auxiliary function \code{ps.options} can be used to set and view
  (if called without arguments) default values for the arguments to
  \code{xfig} and \code{postscript}.
}
\usage{
xfig(file = ifelse(onefile, "Rplots.fig", "Rplot\%03d.fig"),
     onefile = FALSE, \dots)
}
\arguments{
  \item{file}{a character string giving the name of the file.  If it is
    \code{""}, the output is piped to the command given by the argument
    \code{command}.  For use with \code{onefile=FALSE} give a
    \code{printf} format such as \code{"Rplot\%d.fig"} (the default in
    that case).}
  \item{onefile}{logical: if true allow multiple figures
    in one file. If false, assume only one page per file and generate a
    file number containing the page number.}
  \item{\dots}{further arguments to \code{\link{ps.options}} accepted by
    \code{xfig()}:
    \describe{
      \item{\code{paper}}{the size of paper in the printer.  The choices
	are \code{"A4"}, \code{"Letter"} and \code{"Legal"} (and these
	can be lowercase).  A further choice is \code{"default"}, which
	is the default.  If this is selected, the papersize is taken
	from the option \code{"papersize"} if that is set and to
	\code{"A4"} if it is unset or empty.}
      \item{\code{horizontal}}{the orientation of the printed image, a
	logical.  Defaults to true, that is landscape orientation.}
      \item{\code{width}, \code{height}}{the width and height of the
	graphics region in inches.  The default is to use the entire
	page less a 0.25 inch border.}
      \item{\code{family}}{the font family to be used.  This must be one
	of \code{"AvantGarde"}, \code{"Bookman"}, \code{"Courier"},
	\code{"Helvetica"}, \code{"Helvetica-Narrow"},
	\code{"NewCenturySchoolbook"}, \code{"Palatino"} or
	\code{"Times"}.}
      \item{\code{pointsize}}{the default point size to be used.}
      \item{\code{bg}}{the default background color to be used.}
      \item{\code{fg}}{the default foreground color to be used.}
      \item{\code{pagecentre}}{logical: should the device region be
	centred on the page: defaults to \code{TRUE}.}
    }
  }
}
%%>>> REAL DOC in SOURCE:    ../../../main/devices.c  &   ../../../unix/devPS.c
\details{
  Although \code{xfig} can produce multiple plots in one file, the XFig
  format does not say how to separate or view them.  So
  \code{onefile=FALSE} is the default.
}
\note{
  On some line textures (\code{0 <= lty > 4}) are used.  Eventually this
  will be partially remedied, but the XFig file format does not allow as
  general line textures as the \R model.  Unimplemented line textures
  are displayed as \emph{dash-double-dotted}.

  There is a limit of 512 colours (plus white and black) per file.
}
\seealso{
  \code{\link{Devices}},
  \code{postscript},
  \code{\link{ps.options}}.
}
\keyword{device}
\eof
\name{xtabs}
\alias{xtabs}
\alias{print.xtabs}
\title{Cross Tabulation}
\description{
  Create a contingency table from cross-classifying factors, usually
  contained in a data frame, using a formula interface.
}
\usage{
xtabs(formula = ~., data = parent.frame(), subset, na.action,
      exclude = c(NA, NaN), drop.unused.levels = FALSE)
}
\arguments{
  \item{formula}{a formula object with the cross-classifying variables,
    separated by \code{+}, on the right hand side.  Interactions are not
    allowed.  On the left hand side, one may optionally give a vector or
    a matrix of counts; in the latter case, the columns are interpreted
    as corresponding to the levels of a variable.  This is useful if the
    data has already been tabulated, see the examples below.}
  \item{data}{a data frame, list or environment containing the variables
    to be cross-tabulated.}
  \item{subset}{an optional vector specifying a subset of observations
    to be used.}
  \item{na.action}{a function which indicates what should happen when
    the data contain \code{NA}s.}
  \item{exclude}{a vector of values to be excluded when forming the
    set of levels of the classifying factors.}
  \item{drop.unused.levels}{a logical indicating whether to drop unused
    levels in the classifying factors.  If this is \code{FALSE} and
    there are unused levels, the table will contain zero marginals, and
    a subsequent chi-squared test for independence of the factors will
    not work.}
}
\details{
  There is a \code{summary} method for contingency table objects created
  by \code{table} or \code{xtabs}, which gives basic information and
  performs a chi-squared test for independence of factors (note that the
  function \code{\link[ctest]{chisq.test}} in package \pkg{ctest}
  currently only handles 2-d tables).

  If a left hand side is given in \code{formula}, its entries are simply
  summed over the cells corresponding to the right hand side; this also
  works if the lhs does not give counts.
}
\value{
  A contingency table in array representation of class \code{c("xtabs",
    "table")}, with a \code{"call"} attribute storing the matched call.
}
\seealso{
  \code{\link{table}} for \dQuote{traditional} cross-tabulation, and
  \code{\link{as.data.frame.table}} which is the inverse operation of
  \code{xtabs} (see the \code{DF} example below).
}
\examples{
data(esoph)
## 'esoph' has the frequencies of cases and controls for all levels of
## the variables 'agegp', 'alcgp', and 'tobgp'.
xtabs(cbind(ncases, ncontrols) ~ ., data = esoph)
## Output is not really helpful ... flat tables are better:
ftable(xtabs(cbind(ncases, ncontrols) ~ ., data = esoph))
## In particular if we have fewer factors ...
ftable(xtabs(cbind(ncases, ncontrols) ~ agegp, data = esoph))

data(UCBAdmissions)
## This is already a contingency table in array form.
DF <- as.data.frame(UCBAdmissions)
## Now 'DF' is a data frame with a grid of the factors and the counts
## in variable 'Freq'.
DF
## Nice for taking margins ...
xtabs(Freq ~ Gender + Admit, DF)
## And for testing independece ...
summary(xtabs(Freq ~ ., DF))

data(warpbreaks)
## Create a nice display for the warp break data.
warpbreaks$replicate <- rep(1:9, len = 54)
ftable(xtabs(breaks ~ wool + tension + replicate, data = warpbreaks))
}
\keyword{category}
\eof
\name{xy.coords}
\title{Extracting Plotting Structures}
\description{
  \code{xy.coords} is used by many functions to obtain
  x and y coordinates for plotting.
  The use of this common mechanism across all \R functions
  produces a measure of consistency.
}
\usage{
xy.coords(x, y, xlab = NULL, ylab = NULL, log = NULL, recycle = FALSE)
}
\alias{xy.coords}
\arguments{
  \item{x, y}{the x and y coordinates of a set of points.
    Alternatively, a single argument \code{x} can be provided.}
  \item{xlab,ylab}{names for the x and y variables to be extracted.}
  \item{log}{character, \code{"x"}, \code{"y"} or both, as for
    \code{\link{plot}}.  Sets negative values to \code{\link{NA}} and
    gives a warning.}
\item{recycle}{logical; if \code{TRUE}, recycle (\code{\link{rep}}) the shorter
    of \code{x} or \code{y} if their lengths differ.}
}
\details{
  An attempt is made to interpret the arguments \code{x} and \code{y} in
  a way suitable for plotting.

  If \code{y} is missing and \code{x} is a
  \describe{
    \item{formula:}{of the form \code{yvar ~ xvar}. \code{xvar} and
      \code{yvar} are used as x and y variables.}

    \item{list:}{containing components \code{x} and \code{y}, these are
      used are assumed to define plotting coordinates.}

    \item{time series:}{the x values are taken to be
      \code{\link{time}(x)} and the y values to be the time series.}

    \item{matrix with two columns:}{the first is assumed to contain the
      x values and the second the y values.}
  }
  In any other case, the \code{x}argument is coerced to a vector and
  the values plotted against their indices.

  If \code{x} (after transformation as above) inherits from class
  \code{"POSIXt"} it is coerced to class \code{"POSIXct"}.
}
\value{
  A list with the components
  \item{x}{numeric (i.e., \code{"double"}) vector of abscissa values.}
  \item{y}{numeric vector of the same length as \code{x}.}
  \item{xlab}{\code{character(1)} or \code{NULL}, the \sQuote{label} of
    \code{x}.}
  \item{ylab}{\code{character(1)} or \code{NULL}, the \sQuote{label} of
    \code{y}.}
}
\seealso{
  \code{\link{plot.default}}, \code{\link{lines}}, \code{\link{points}}
  and \code{\link{lowess}} are examples of functions which use this mechanism.
}
\examples{
xy.coords(fft(c(1:10)), NULL)
data(cars) ; attach(cars)
xy.coords(dist ~ speed, NULL)$xlab # = "speed"

str(xy.coords(1:3, 1:2, recycle=TRUE))
str(xy.coords(-2:10,NULL, log="y"))
##> warning: 3 y values <=0 omitted ..
detach()
}
\keyword{dplot}
\eof
\name{xyz.coords}
\alias{xyz.coords}
\title{Extracting Plotting Structures}
\description{
  Utility for obtaining consistent x, y and z coordinates and labels
  for three dimensional (3D) plots.
}
\usage{
xyz.coords(x, y, z, xlab=NULL, ylab=NULL, zlab=NULL, log=NULL,
    recycle=FALSE)
}
\arguments{
  \item{x, y, z}{the x, y and z coordinates of a set of points.
    Alternatively, a single argument \code{x} can be be provided.
    In this case, an attempt is made to interpret the
    argument in a way suitable for plotting.

    If the argument is a formula \code{zvar ~ xvar + yvar},
    \code{xvar}, \code{yvar} and \code{zvar} are used as x, y and z
    variables;
    if the argument is a list containing components \code{x},
    \code{y} and \code{z}, these are assumed to define plotting coordinates;
    if the argument is a matrix with three columns, the first is
    assumed to contain the x values, etc.

    Alternatively, two arguments \code{x} and \code{y} can be be provided.
    One may be real, the other complex;
    in any other case, the arguments are coerced to vectors
    and the values plotted against their indices.
  }
  \item{xlab, ylab, zlab}{names for the x, y and z variables to be extracted.}
  \item{log}{character, \code{"x"}, \code{"y"}, \code{"z"} or combinations.
    Sets negative values to \code{\link{NA}} and gives a warning.}
  \item{recycle}{logical; if \code{TRUE}, recycle (\code{\link{rep}}) the
    shorter ones of \code{x}, \code{y} or \code{z} if their lengths differ.}
}
\value{
  A list with the components
  \item{x}{numeric (i.e., \code{\link{double}}) vector of abscissa values.}
  \item{y}{numeric vector of the same length as \code{x}.}
  \item{z}{numeric vector of the same length as \code{x}.}
  \item{xlab}{\code{character(1)} or \code{NULL}, the axis label of \code{x}.}
  \item{ylab}{\code{character(1)} or \code{NULL}, the axis label of \code{y}.}
  \item{zlab}{\code{character(1)} or \code{NULL}, the axis label of \code{z}.}
}
\author{Uwe Ligges and Martin Maechler}
\seealso{\code{\link{xy.coords}} for 2D.}
\examples{
str(xyz.coords(data.frame(10*1:9, -4),y=NULL,z=NULL))

str(xyz.coords(1:6, fft(1:6),z=NULL,xlab="X", ylab="Y"))

y <- 2 * (x2 <- 10 + (x1 <- 1:10))
str(xyz.coords(y ~ x1 + x2,y=NULL,z=NULL))

str(xyz.coords(data.frame(x=-1:9,y=2:12,z=3:13),y=NULL,z=NULL,
    log="xy"))
##> Warning message: 2 x values <= 0 omitted ...
}
\keyword{dplot}
\eof
\name{C}
\title{Sets Contrasts for a Factor}
\usage{
C(object, contr, how.many, \dots)
}
\alias{C}
\arguments{
  \item{object}{a factor or ordered factor}
  \item{contr}{which contrasts to use. Can be a matrix with one row for
    each level of the factor or a suitable function like
    \code{contr.poly} or a character string giving the name of the function}
  \item{how.many}{the number of contrasts to set, by default one less
    than \code{nlevels(object)}.}
  \item{\dots}{additional arguments for the function \code{contr}.}
}
\description{
  Sets the \code{"contrasts"} attribute for the factor.
}
\details{
  For compatibility with S, \code{contr} can be \code{treatment},
  \code{helmert}, \code{sum} or \code{poly} (without quotes) as shorthand
  for \code{contr.treatment} and so on.
}
\value{
  The factor \code{object} with the \code{"contrasts"} attribute set.
}
\seealso{
  \code{\link{contrasts}}, \code{\link{contr.sum}}, etc.
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical models.}
  Chapter 2 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\examples{
## reset contrasts to defaults
options(contrasts=c("contr.treatment", "contr.poly"))
data(warpbreaks)
attach(warpbreaks)
tens <- C(tension, poly, 1)
attributes(tens)
detach()
## tension SHOULD be an ordered factor, but as it is not we can use
aov(breaks ~ wool + tens + tension, data=warpbreaks)

## show the use of ...  The default contrast is contr.treatment here
summary(lm(breaks ~ wool + C(tension, base=2), data=warpbreaks))


data(esoph) # following on from help(esoph)
model3 <- glm(cbind(ncases, ncontrols) ~ agegp + C(tobgp, , 1) +
     C(alcgp, , 1), data = esoph, family = binomial())
summary(model3)
}
\keyword{models}
\eof
\name{.Machine}
\title{Numerical Characteristics of the Machine}
\usage{
.Machine
}
\alias{.Machine}
\description{
  \code{.Machine} is a variable holding information on the numerical
  characteristics of the machine \R is running on, such as the largest
  double or integer and the machine's precision.
}
\value{
  A list with components (for simplicity, the prefix \dQuote{double} is
  omitted in the explanations)
  \item{double.eps}{the smallest positive floating-point number
    \code{x} such that \code{1 + x != 1}.  It equals
    \code{base^ulp.digits} if either \code{base} is 2 or \code{rounding}
    is 0;  otherwise, it is \code{(base^ulp.digits) / 2}.}
  \item{double.neg.eps}{a small positive floating-point number \code{x}
    such that \code{1 - x != 1}.  It equals \code{base^neg.ulp.digits}
    if \code{base} is 2 or \code{round} is 0;  otherwise, it is
    \code{(base^neg.ulp.digits) / 2}.
    As \code{neg.ulp.digits} is bounded below by \code{-(digits + 3)},
    \code{neg.eps} may not be the smallest number that can alter 1 by
    subtraction.}
  \item{double.xmin}{the smallest non-vanishing normalized
    floating-point power of the radix, i.e., \code{base^min.exp}.}
  \item{double.xmax}{the largest finite floating-point number.
    Typically, it is equal to \code{(1 - neg.eps) * base^max.exp}, but
    on some machines it is only the second, or perhaps third, largest
    number, being too small by 1 or 2 units in the last digit of the
    significand.}
  \item{double.base}{the radix for the floating-point representation}
  \item{double.digits}{the number of base digits in the floating-point
    significand}
  \item{double.rounding}{the rounding action. \cr
    0 if floating-point addition chops; \cr
    1 if floating-point addition rounds, but not in the IEEE style; \cr
    2 if floating-point addition rounds in the IEEE style; \cr
    3 if floating-point addition chops, and there is partial underflow; \cr
    4 if floating-point addition rounds, but not in the IEEE style, and
    there is partial underflow; \cr
    5 if floating-point addition rounds in the IEEE style, and there is
    partial underflow}
  \item{double.guard}{the number of guard digits for multiplication
    with truncating arithmetic.  It is 1 if floating-point arithmetic
    truncates and more than \code{digits} base \code{base} digits
    participate in the post-normalization shift of the floating-point
    significand in multiplication, and 0 otherwise.}
  \item{double.ulp.digits}{the largest negative integer \code{i} such
    that \code{1 + base^i != 1}, except that it is bounded below by
    \code{-(digits + 3)}.}
  \item{double.neg.ulp.digits}{the largest negative integer \code{i}
    such that \code{1 - base^i != 1}, except that it is bounded below by
    \code{-(digits + 3)}.}
  \item{double.exponent}{
    the number of bits (decimal places if \code{base} is 10) reserved
    for the representation of the exponent (including the bias or sign)
    of a floating-point number}
  \item{double.min.exp}{
    the largest in magnitude negative integer \code{i} such that
    \code{base ^ i} is positive and normalized.}
  \item{double.max.exp}{
    the smallest positive power of \code{base} that overflows.}
  \item{integer.max}{the largest integer which can be represented.}
  \item{sizeof.long}{the number of bytes in a C \code{long} type.}
  \item{sizeof.longlong}{the number of bytes in a C \code{long long}
    type. Will be zero if there is no such type.}
  \item{sizeof.longdouble}{the number of bytes in a C \code{long double}
    type. Will be zero if there is no such type.}
  \item{sizeof.pointer}{the number of bytes in a C \code{SEXP}
    type.}
}
\details{
  The algorithm is based on Cody's (1988) subroutine MACHAR.
}
\references{
  Cody, W. J. (1988)
  MACHAR: A subroutine to dynamically determine machine parameters.
  \emph{Transactions on Mathematical Software}, \bold{14}, 4, 303--311.
}
\seealso{
  \code{\link{.Platform}} for details of the platform.
}
\examples{
str(.Machine)
}
\keyword{sysdata}
\keyword{programming}
\keyword{math}
\eof
\name{InternalMethods}
\alias{InternalMethods}
\title{Internal Generic Functions}
\description{
  Many \R-internal functions are \emph{generic} and allow
  methods to be written for.
}

\details{
  % -------------------- grep -nw DispatchOrEval src/*/*[ch]
  %                         --------------
  The following builtin functions are \emph{generic} as well, i.e., you
  can write \code{\link{methods}} for them:

  \code{\link{[}},            % do_subset()          [subset.c:464]
  \code{\link{[[}},           % do_subset2()         [subset.c:567]
  \code{\link{$}},
  \code{\link{[<-}},
  \code{\link{[[<-}},
  \code{\link{$<-}},

  \code{\link{length}},
    
  \code{\link{dimnames<-}},   % do_dimnamesgets()    [attrib.c:422]
  \code{\link{dimnames}},     % do_dimnames()        [attrib.c:489]
  \code{\link{dim<-}},        % do_dimgets()         [attrib.c:513]
  \code{\link{dim}}           % do_dim()             [attrib.c:501]
    
  \code{\link{c}},            % do_c()               [bind.c:524]
  \code{\link{unlist}},       % do_unlist()          [bind.c:648]
  
  \code{\link{as.character}},
  \code{\link{as.vector}},    % do_asvector()        [coerce.c:948]
  \code{\link{is.array}},
  \code{\link{is.atomic}},
  \code{\link{is.call}},
  \code{\link{is.character}},
  \code{\link{is.complex}},
  \code{\link{is.double}},
  \code{\link{is.environment}},
  \code{\link{is.function}},
  \code{\link{is.integer}},
  \code{\link{is.language}},
  \code{\link{is.logical}},
  \code{\link{is.list}},
  \code{\link{is.matrix}},
  \code{\link{is.na}},        % do_isna()            [coerce.c:1244]
  \code{\link{is.nan}}        % do_isnan()           [coerce.c:1332]
  \code{\link{is.null}},
  \code{\link{is.numeric}},
  \code{\link{is.object}},
  \code{\link{is.pairlist}},
  \code{\link{is.recursive}},
  \code{\link{is.single}},
  \code{\link{is.symbol}}.
}
\seealso{
  \code{\link{methods}} for the methods of non-Internal generic functions.
}
\keyword{methods}
\eof
\name{.Script}
\title{Scripting Language Interface}
\alias{.Script}
\description{
  Run a script through its interpreter with given arguments.
}
\usage{
.Script(interpreter, script, args, \dots)
}
\arguments{
  \item{interpreter}{a character string naming the interpreter for the
    script.}
  \item{script}{a character string with the base file name of the
    script, which must be located in the \file{\code{interpreter}}
    subdirectory of \file{R\_HOME/share}.}
  \item{args}{a character string giving the arguments to pass to the
    script.}
  \item{\dots}{further arguments to be passed to \code{\link{system}}
    when invoking the interpreter on the script.}
}
\note{This function is for R internal use only.}
\examples{
.Script("perl", "massage-Examples.pl",
        paste("tools", system.file("R-ex", package = "tools")))
}
\keyword{interface}
\eof
\name{zcbind}
\alias{.cbind.ts}
\title{Bind Two or More Time Series}
\description{
  Bind Two or More Time Series which have common frequency.
}
\usage{
.cbind.ts(sers, nmsers, dframe = FALSE, union = TRUE)
}
\arguments{
  \item{sers}{a list of two or more univariate or multivariate time
    series, or objects which can coerced to time series.}
  \item{nmsers}{a character vector of the same length as \code{sers}
    with the names for the time series.}
  \item{dframe}{logical; if \code{TRUE} return the result as a data
    frame.}
  \item{union}{logical; if \code{TRUE}, act as \code{ts.union} or
    \code{ts.intersect}.}
}
\details{
  This is an internal function which is not to be called by the user.
}
\keyword{internal}
\eof
\name{zip.file.extract}
\alias{zip.file.extract}
\title{Extract File from a Zip Archive}
\usage{
zip.file.extract(file, zipname = "R.zip")
}
\arguments{
 \item{file}{A file name.}
 \item{zipname}{The file name of a \code{zip} archive, including the
   \code{".zip"} extension if required.}
}
\description{
  This will extract the file named \code{file} from the zip archive,
  if possible, and write it in a temporary location.
}
\details{
  The method used is selected by \code{options(unzip=)}. All platforms
  support an \code{"internal"} unzip: this is the default under Windows
  and the fall-back under Unix if no \code{unzip} program was found
  during configuration and \env{R\_UNZIPCMD} is not set.
  
  The file will be extracted if it is in the archive and any required
  \code{unzip} utility is available.  It will probably be extracted to
  the directory given by \code{tempdir}, overwriting an existing file of
  that name.
}
\value{
  The name of the original or extracted file.  Success is indicated by
  returning a different name.
}
\note{
  The \code{"internal"} method is very simple, and will not set file dates.
}

\keyword{file}
\eof
\name{BATCH}
\alias{BATCH}
\title{Batch Execution of R}
\description{Run R non-interactively with input from a given file and
  place output (stdout/stderr) to another file.}
\usage{R CMD BATCH [options] infile [outfile]}
\arguments{
  \item{infile}{the name of a file with R code to be executed.}
  \item{options}{a list of R command line options, e.g., for setting the
    amount of memory available and controlling the load/save process.
    If \code{infile} starts with a \code{-}, use \code{--} as the
    final option.}
  \item{outfile}{the name of a file to which to write output.  If not
    given, the name used is the one of \code{infile}, with a possible
    \file{.R} extension stripped, and \file{.Rout} appended.}
}
\details{
  By default, the input commands are printed along with the output.  To
  suppress this behavior, add \code{options(echo = FALSE)} at the
  beginning of \code{infile}.

  The \code{infile} can have end of line marked by LF or CRLF (but not
  just CR), and files with a missing EOL mark are processed correctly.

  Using \code{R CMD BATCH} sets the GUI to \code{"none"}, so none of
  \code{\link{x11}}, \code{\link{jpeg}} and \code{\link{png}} are available.
}
\note{
  Unlike \code{Splus BATCH}, this does not run the \R process in the
  background.  In most shells,
  \code{R CMD BATCH [options] infile [outfile] &}
  will do so. 
}
\keyword{utilities}
\eof
\name{COMPILE}
\alias{COMPILE}
\title{Compile Files for Use with R}
\description{
  Compile given source files so that they can subsequently be collected
  into a shared library using \code{R CMD SHLIB} and be loaded into R
  using \code{dyn.load()}.
}
\usage{R CMD COMPILE [options] srcfiles}
\arguments{
  \item{srcfiles}{A list of the names of source files to be compiled.
    Currently, C, C++ and FORTRAN are supported; the corresponding files
    should have the extensions \file{.c}, \file{.cc} (or \file{.cpp} or
    \file{.C}), and \file{.f}, respectively.}
  \item{options}{A list of compile-relevant settings, such as special
    values for \code{CFLAGS} or \code{FFLAGS}, or for obtaining
    information about usage and version of the utility.}
}
\details{
  Note that Ratfor is not supported.  If you have Ratfor source code,
  you need to convert it to FORTRAN.  On many Solaris systems mixing
  Ratfor and FORTRAN code will work.
}
\seealso{
  \code{\link{SHLIB}},
  \code{\link{dyn.load}}
}
\keyword{utilities}
\eof
\name{INSTALL}
\alias{INSTALL}
\title{Install Add-on Packages}
\description{Utility for installing add-on packages.}
\usage{R CMD INSTALL [options] [-l lib] pkgs}
\arguments{
  \item{pkgs}{A list with the path names of the packages to be
    installed.}
  \item{lib}{the path name of the \R library tree to install to.}
  \item{options}{a list of options through which in particular the
    process for building the help files can be controlled.}
}
\details{
  If used as \code{R CMD INSTALL pkgs} without explicitly specifying
  \code{lib}, packages are installed into the library tree rooted at the
  first directory given in the environment variable \env{R\_LIBS} if
  this is set and non-null, and to the default library tree (which is
  rooted at \file{\$R\_HOME/library}) otherwise.

  To install into the library tree \code{lib}, use
  \code{R CMD INSTALL -l lib pkgs}.

  Both \code{lib} and the elements of \code{pkgs} may be absolute or
  relative path names. \code{pkgs} can also contain name of package
  archive files of the form \file{pkg\_version.tar.gz} as obtained from
  CRAN, these are then extracted in a temporary directory.
  
  Some package sources contain a \file{configure} script that can be
  passed arguments or variables via the option \option{--configure-args}
  and \option{--configure-vars}, respectively, if necessary.  The latter
  is useful in particular if libraries or header files needed for the
  package are in non-system directories.  In this case, one can use the
  configure variables \code{LIBS} and \code{CPPFLAGS} to specify these
  locations (and set these via \option{--configure-vars}), see section
  \dQuote{Configuration variables} in \dQuote{R Installation and
    Administration} for more information.  One can also bypass the
  configure mechanism using the option \option{--no-configure}.
  
  If \option{--no-docs} is given, no help files are built.  Options
  \option{--no-text}, \option{--no-html}, and \option{--no-latex} suppress
  creating the text, HTML, and LaTeX versions, respectively.  The
  default is to build help files in all three versions.

  If the option \option{--save} is used, the installation procedure
  creates a binary image of the package code, which is then loaded when
  the package is attached, rather than evaluating the package source at
  that time.  Having a file \file{install.R} in the package directory
  makes this the default behavior for the package (option
  \option{--no-save} overrides).  You may need  \option{--save} if your
  package requires other packages to evaluate its own source.  If the
  file \file{install.R} is non-empty, it should contain R expressions to
  be executed when the package is attached, after loading the saved
  image.  Options to be passed to R when creating the save image can be
  specified via \option{--save=ARGS}.

  If the attempt to install the package fails, leftovers are removed.
  If the package was already installed, the old version is restored.

  Use \code{R CMD INSTALL --help} for more usage information.
}

\section{Packages using the methods package}{
  Packages that require the methods package, and that use functions such
  as \code{\link[methods]{setMethod}} or
  \code{\link[methods]{setClass}}, should be installed by creating a
  binary image.

  The presence of a file named
  \file{install.R} in the package's main directory causes an image to
  be saved.  Note that the file is not in the \file{R} subdirectory: all
  the code in that subdirectory is used to construct the binary image.

  Normally, the file \file{install.R} will be empty; if it does contain R expressions
  these will be evaluated when the package is attached, e.g. by a call to
  the function \code{\link{library}}.  (Specifically, the source code
  evaluated for a package with a saved image consists of a suitable
  definition of \code{.First.lib} to ensure loading of the saved
  image, followed by the R code in file \file{install.R}, if any.)

}
\seealso{
  \code{\link{REMOVE}},
  \code{\link{update.packages}} for automatic update of packages using
  the internet;
  the chapter on \dQuote{Creating R packages} in \dQuote{Writing \R
    Extensions} (see the \file{doc/manual} subdirectory of the \R source
  tree).
}
\keyword{utilities}
\eof
\name{LINK}
\alias{LINK}
\title{Create Executable Programs}
\description{
  Front-end for creating executable programs.
}
\usage{
R CMD LINK [options] linkcmd
}
\arguments{
  \item{linkcmd}{a list of commands to link together suitable object
    files (include library objects) to create the executable program.}
  \item{options}{further options to control the linking, or for
    obtaining information about usage and version.}
}
\details{
  The linker front-end is useful in particular when linking against the
  R shared library, in which case \code{linkcmd} must contain \code{-lR}
  but need not specify its library path.
  
  Currently only works if the C compiler is used for linking, and no C++
  code is used.

  Use \code{R CMD LINK --help} for more usage information.
}
\keyword{utilities}
\eof
\name{REMOVE}
\alias{REMOVE}
\title{Remove Add-on Packages}
\description{Utility for removing add-on packages.}
\usage{R CMD REMOVE [options] [-l lib] pkgs}
\arguments{
  \item{pkgs}{a list with the names of the packages to be removed.}
  \item{lib}{the path name of the \R library tree to remove from.  May
    be absolute or relative.}
  \item{options}{further options.}
}
\details{
  If used as \code{R CMD REMOVE pkgs} without explicitly specifying
  \code{lib}, packages are removed from the library tree rooted at the
  first directory given in \code{\$R\_LIBS} if this is set and non-null,
  and to the default library tree (which is rooted at
  \file{\$R\_HOME/library}) otherwise.

  To remove from the library tree \code{lib}, use
  \code{R CMD REMOVE -l lib pkgs}.

  Use \code{R CMD REMOVE --help} for more usage information.  
}
\seealso{
  \code{\link{INSTALL}}
}
\keyword{utilities}
\eof
\name{RHOME}
\alias{RHOME}
\alias{R_HOME}
\title{R Home Directory}
\description{
  Returns the location of the \R home directory, which is the root of
  the installed \R tree.
}
\usage{R RHOME}
\keyword{utilities}
\eof
\name{SHLIB}
\alias{SHLIB}
\title{Build Shared Library for Dynamic Loading}
\description{
  Compile given source files using \code{R CMD COMPILE}, and then link
  all specified object files into a shared library which can be loaded
  into R using \code{dyn.load} or \code{library.dynam}.
}
\usage{R CMD SHLIB [options] [-o libname] files}
\arguments{
  \item{files}{a list specifying the object files to be included in the
    shared library.  You can also include the name of source files, for
    which the object files are automagically made from their sources.}
  \item{libname}{the full name of the shared library to be built,
    including the extension (typically \file{.so} on Unix systems).  If
    not given, the name of the library is taken from the first file.}
  \item{options}{Further options to control the processing, or for
    obtaining information about usage and version of the utility.}
}
\seealso{
  \code{\link{COMPILE}}, \code{\link{dyn.load}}, \code{\link{library.dynam}}
}
\keyword{utilities}
\eof
\name{Signals}
\alias{Signals}
\title{Interrupting Execution of R}
\description{
  On receiving \code{SIGUSR1} \R will save the workspace and quit.
  \code{SIGUSR2} has the same result except that the \code{\link{.Last}}
  function and \code{\link{on.exit}} expressions will not be called.
}
\usage{
kill -USR1 pid
kill -USR2 pid
}
\arguments{
  \item{pid}{The process ID of the R process}
}
\section{Warning}{
  It is possible that one or more R objects will be undergoing
  modification at the time the signal is sent.  These objects could be
  saved in a corrupted form.
}
\keyword{utilities}
\eof
\name{Gnome}
\alias{GNOME}
\alias{gnome}
\title{GNOME Desktop Graphics Device}
\description{
  \code{gnome} starts a \acronym{GNOME} compatible device driver.
  \acronym{GNOME} is an acronym for \bold{G}NU \bold{N}etwork
  \bold{O}bject \bold{M}odel \bold{E}nvironment.
}
\usage{
gnome(display="", width=7, height=7, pointsize=12)
GNOME(display="", width=7, height=7, pointsize=12)
}
\arguments{
  \item{display}{the display on which the graphics window will appear.
    The default is to use the value in the user's environment variable
    \env{DISPLAY}.}
  \item{width}{the width of the plotting window in inches.}
  \item{height}{the height of the plotting window in inches.}
  \item{pointsize}{the default pointsize to be used.}
}
\references{\url{http://www.gnome.org} and \url{http://www.gtk.org} for
  the \code{GTK+} (GIMP Tool Kit) libraries.
}
\author{Lyndon Drake \email{lyndon@stat.auckland.ac.nz}}
\note{
  This is still in development state.

  The GNOME device is only available when explicitly desired at
  configure/compile time, see the toplevel \file{INSTALL} file.
}
\seealso{\code{\link{x11}}, \code{\link{Devices}}.}
\examples{
\dontrun{
gnome(width=9)
}
}
\keyword{device}
\eof
\name{gtk}
\alias{gtk}
\alias{GTK}
\title{GTK+ Graphics Device}
\description{
  This is a graphics device similar to the X11 device
  but using the Gtk widgets. This is now available via a separate
  package - gtkDevice - and can be used independently of the GNOME GUI
  for R. This package also allows a device to embedded within a
  Gtk-based GUI developed using the RGtk package.
  The gtkDevice package is available from CRAN.
}
\usage{
gtk(display="", width=7, height=7, pointsize=12)
GTK(display="", width=7, height=7, pointsize=12)
}
\arguments{
  \item{display}{the display on which the graphics window will appear.
    The default is to use the value in the user's environment variable
    \env{DISPLAY}.}
  \item{width}{the width of the plotting window in inches.}
  \item{height}{the height of the plotting window in inches.}
  \item{pointsize}{the default pointsize to be used.}
}
\author{Original version by Lyndon Drake
  \email{lyndon@stat.auckland.ac.nz}.
  Reorganization by Martyn Plummer and Duncan Temple Lang.
}
\references{
  \url{http://www.gtk.org} for the \code{GTK+} (GIMP Tool Kit) libraries.
}
\seealso{
  \code{\link{x11}},
  \code{\link{Devices}}.
}
\keyword{device}
\eof
\name{make.packages.html}
\alias{make.packages.html}
\title{Update HTML documentation files}
\usage{
make.packages.html(lib.loc = .libPaths())
}
\description{
  Functions to re-create the HTML documentation files to reflect all
  installed packages.
}
\arguments{
  \item{lib.loc}{character vector. List of libraries to be included.}
}
\details{
  This sets up the links from packages in libraries to the \file{.R}
  subdirectory of the per-sesson directory (see \code{\link{tempdir}})
  and then creates the \file{packages.html} and \file{index.txt} files
  to point to those links.

  If a package is available in more than one library tree, all the
  copies are linked, after the first with suffix \code{.1} etc.
}
\value{
  Logical, whether the function succeeded in recreating the files.
}
\seealso{
  \code{\link{help.start}}
}
\keyword{utilities}
\eof
\name{nsl}
\alias{nsl}
\title{Look up the IP Address by Hostname}
\description{
  Interface to \code{gethostbyname}.
}
\usage{
nsl(hostname)
}
\arguments{
 \item{hostname}{the name of the host.}
}
\value{
  The IP address, as a character string, or \code{NULL} if the call fails.
}
\note{
  This was included as a test of internet connectivity, to fail if
  the node running R is not connected.  It will also return \code{NULL}
  if BSD networking is not supported, including the header file
  \file{arpa/inet.h}.
}
\examples{
\dontrun{nsl("www.r-project.org")}
}
\keyword{utilities}
\eof
\name{png}
\alias{png}
\alias{jpeg}
\title{JPEG and PNG graphics devices}
\description{
  A graphics device for JPEG or PNG format bitmap files.
}
\usage{
jpeg(filename = "Rplot\%03d.jpeg", width = 480, height = 480,
     pointsize = 12, quality = 75, bg = "white", \dots)
png(filename ="Rplot\%03d.png", width = 480, height = 480,
    pointsize = 12, bg = "white", \dots)
}
\synopsis{
jpeg(filename = "Rplot\%03d.jpeg", width = 480, height = 480, pointsize = 12,
     quality = 75, gamma = 1,
     colortype = getOption("X11colortype"), maxcubesize = 256, bg = "white")
png(filename ="Rplot\%03d.png", width = 480, height = 480, pointsize = 12,
    gamma = 1, colortype = getOption("X11colortype"), maxcubesize = 256,
    bg = "white")
}
\arguments{
  \item{filename}{the name of the output file.
    The page number is substituted if an integer format is included
    in the character string. (The result must be less than \code{PATH_MAX}
    characters long, and may be truncated if not.)
    Tilde expansion is performed where supported by the platform.}
  \item{width}{the width of the device in pixels.}
  \item{height}{the height of the device in pixels.}
  \item{pointsize}{the default pointsize of plotted text.}
  \item{quality}{the \sQuote{quality} of the JPEG image, as a
    percentage.  Smaller values will give more compression but also more
    degradation of the image.}
  \item{bg}{default background colour.}
  \item{\dots}{additional arguments to the \code{\link{X11}} device.}
}
\details{
  Plots in PNG and JPEG format can easily be converted to many other
  bitmap formats, and both can be displayed in most modern web
  browsers. The PNG format is lossless and is best for line
  diagrams and blocks of solid colour. The JPEG format is lossy,
  but may be useful for image plots, for example.

  \code{png} supports transparent backgrounds: use \code{bg = "transparent"}.
  Not all PNG viewers render files with transparency correctly.
  When transparency is in use a very light grey is used as the
  background and so will appear as transparent if used in the plot.
  This allows opaque white to be used, as on the example.

  \R can be compiled without support for either or both of these
  devices: this will be reported if you attempt to use them on a system
  where they are not supported.  They will not be available if \R has
  been started with \samp{--gui=none} (and will give a different error
  message), and they may not be usable unless the X11 display is
  available to the owner of the \R process.
}
\value{
  A plot device is opened: nothing is returned to the \R interpreter.
}
\section{Warning}{
  If you plot more than one page on one of these devices and do not
  include somthing like \code{\%d} for the sequence number in
  \code{file}, the file will contain the last page plotted.
}
\note{
  These are based on the \code{\link{X11}} device, so the additional
  arguments to that device work, but are rarely appropriate.  The
  colour handling will be that of the \code{X11} device in use.
}
\author{Guido Masarotto and Brian Ripley}

\seealso{
  \code{\link{Devices}}, \code{\link{dev.print}}

  \code{\link{capabilities}} to see if these devices are
  supported by this build of \R.

  \code{\link{bitmap}} provides an alternative way to generate PNG and
  JPEG plots that does not depend on accessing the X11 display but does
  depend on having GhostScript installed.
}
\examples{
## these examples will work only if the devices are available
## and the X11 display is available.

## copy current plot to a PNG file
\dontrun{dev.print(png, file="myplot.png", width=480, height=480)

png(file="myplot.png", bg="transparent")
plot(1:10)
rect(1, 5, 3, 7, col="white")
dev.off()

jpeg(file="myplot.jpeg")
example(rect)
dev.off()
}}
\keyword{device}
\eof
\name{quartz}
\alias{quartz}
\title{MacOS X Quartz device}
\description{
  \code{quartz} starts a graphics device driver for the MacOS X System.
  This can only be done on machines that run MacOS X.
}
\usage{
quartz(display = "", width = 5, height = 5, pointsize = 12,
       family = "Helvetica", antialias = TRUE, autorefresh = TRUE)
}
\arguments{
  \item{display}{the display on which the graphics window will appear.
    The default is to use the value in the user's environment variable
    \env{DISPLAY}.}
  \item{width}{the width of the plotting window in inches.}
  \item{height}{the height of the plotting window in inches.}
  \item{pointsize}{the default pointsize to be used.}
  \item{family}{this is the family name of the Postscript font
    that will be used by the device.}
  \item{antialias}{whether to use antialiasing. It is never the case to set
     it \code{FALSE}}
  \item{autorefresh}{logical specifying if realtime refreshing should be
    done.  If \code{FALSE}, the system is charged to refresh the context
      of the device window.}
 }
\details{
  Quartz is the graphic engine based on the PDF format.  It is used
  by the graphic interface of MacOS X to render high quality graphics.
  As PDF it is device independent and can be rescaled without loss of
  definition.

  Calling \code{quartz()} sets \code{\link{.Device}} to \code{"quartz"}.
}
\seealso{
  \code{\link{Devices}}.
}
\keyword{device}
\eof
\name{system}
\alias{system}
\alias{unix}
\title{Invoke a System Command}
\description{
  \code{system} invokes the OS command specified by \code{command}.
}
\usage{
system(command, intern = FALSE, ignore.stderr = FALSE)
}
\arguments{
  \item{command}{the system command to be invoked, as a string.}
  \item{intern}{a logical, indicates whether to make the output of the
    command an \R object.}
  \item{ignore.stderr}{a logical indicating whether error messages (written
    to \file{stderr}) should be ignored.}
}
\value{
  If \code{intern=TRUE}, a character vector giving the output of the
  command, one line per character string. If the command could not be
  run or gives an error a \R error is generated.

  If \code{intern=FALSE}, the return value is an error code.
}
\details{
  If \code{intern} is \code{TRUE} then \code{popen} is used to invoke the
  command and the output collected, line by line, into an \R
  \code{\link{character}} vector which is returned as the value of
  \code{system}.  Output lines of more that 8096 characters will be split.

  If \code{intern} is \code{FALSE} then the C function \code{system}
  is used to invoke the command and the value returned by \code{system}
  is the exit status of this function.

  \code{unix} is a \emph{deprecated} alternative, available for
  backwards compatibility.
}
\seealso{\code{\link{.Platform}} for platform specific variables.}
\examples{
# list all files in the current directory using the -F flag
\dontrun{system("ls -F")}

# t1 is a character vector, each one
# representing a separate line of output from who
t1 <- system("who", TRUE)

system("ls fizzlipuzzli", TRUE, TRUE)# empty since file doesn't exist
}
\keyword{interface}
\keyword{file}
\keyword{utilities}
\eof
\name{x11}
\alias{x11}
\alias{X11}
\title{X Window System Graphics}
\description{
  \code{X11} starts a graphics device driver for the X Window System
  (version 11).  This can only be done on machines that run X.
  \code{x11} is recognized as a synonym for \code{X11}.
}
\usage{
X11(display = "", width = 7, height = 7, pointsize = 12,
    gamma = 1, colortype = getOption("X11colortype"),
    maxcubesize = 256, canvas = "white")
}
\arguments{
  \item{display}{the display on which the graphics window will appear.
    The default is to use the value in the user's environment variable
    \env{DISPLAY}.}
  \item{width}{the width of the plotting window in inches.}
  \item{height}{the height of the plotting window in inches.}
  \item{pointsize}{the default pointsize to be used.}
  \item{gamma}{the gamma correction factor.  This value is used
    to ensure that the colors displayed are linearly related to
    RGB values.  A value of around 0.5 is appropriate for many PC
    displays.  A value of 1.0 (no correction) is usually appropriate
    for high-end displays or Macintoshs.}
  \item{colortype}{the kind of color model to be used.  The
    possibilities are \code{"mono"}, \code{"gray"}, \code{"pseudo"},
    \code{"pseudo.cube"} and \code{"true"}. Ignored if an \code{X11} is
    already open.}
  \item{maxcubesize}{can be used to limit the size of color
    cube allocated for pseudocolor devices.}
  \item{canvas}{color.  The color of the canvas, which is visible only
    when the background color is transparent.}
}
\details{
  By default, an X11 device will use the best color rendering
  strategy that it can.  The choice can be overriden with the
  \code{colortype} parameter.  A value of \code{"mono"} results in
  black and white graphics, \code{"gray"} in grayscale and
  \code{"true"} in truecolor graphics (if this is possible).  The
  values \code{"pseudo"} and \code{"pseudo.cube"} provide color
  strategies for pseudocolor displays.  The first strategy provides
  on-demand color allocation which produces exact colors until
  the color resources of the display are exhausted.  The second
  causes a standard color cube to be set up, and requested colors
  are approximated by the closest value in the cube.  The default
  strategy for pseudocolor displays is \code{"pseudo"}.

  \bold{Note:} All \code{X11} devices share a \code{colortype} which is
  set by the first device to be opened.  To change the \code{colortype}
  you need to close \emph{all} open \code{X11} devices then open one
  with the desired \code{colortype}.

  With \code{colortype} equal to \code{"pseudo.cube"} or \code{"gray"}
  successively smaller palettes are tried until one is completely
  allocated. If allocation of the smallest attempt fails the device will
  revert to \code{"mono"}.
}
\seealso{
  \code{\link{Devices}}.
}
\keyword{device}
\eof
