%% From package:nlme  AIC.Rd,v 1.4 2000/07/03 18:22:45 bates
%% with additional "k = 2" argument (MM)
\name{AIC}
\title{Akaike Information Criterion}
\usage{
AIC(object, \dots, k = 2)
}
\alias{AIC}
\alias{AIC.default}
\alias{AIC.lm}% << still needed for  library(nlme)
\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 ``penalty'' per parameter to be used; the
    default \code{k = 2} is the classical AIC.}
}
\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).
}
\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{logLik}},
  \code{\link{AIC.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}
%% from package:nlme  AIC.logLik.Rd,v 1.4 2000/07/03 18:22:45 bates 
\name{AIC.logLik}
\title{AIC of a logLik Object}
\usage{
\method{AIC}{logLik}(object, \dots, k = 2)
}
\alias{AIC.logLik}
\arguments{
  \item{object}{an object inheriting from class \code{"logLik"}, usually
    resulting from applying a \code{logLik} method to a fitted model
    object.}
  \item{\dots}{further arguments to be passed to or from methods.}
  \item{k}{numeric, the ``penalty'' per parameter to be used; the
    default \code{k = 2} is the classical AIC.}
}
\description{
  see \emph{Description} in \code{\link{AIC}}.
}
\value{
  a numeric value with the corresponding 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{AIC}},
  \code{\link{logLik}}.
}
\keyword{models}
\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 ``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.
}
\seealso{
\code{\link{sqrt}} for miscellaneous and \code{\link{Special}} for special
mathematical functions.
}
\examples{
x <- -1:12
x + 1
2 * x + 3
x \%\% 2 #-- is periodic
x \%/\% 5
}
\keyword{arith}
\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)

## Check the Scaling :
for(nu in nus)
   print(all(abs(1- besselK(x,nu)*exp( x) / besselK(x,nu,expo=TRUE)) < 2e-15))
for(nu in nus)
   print(all(abs(1- besselI(x,nu)*exp(-x) / besselI(x,nu,expo=TRUE)) < 1e-15))

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)

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

 x <- seq(3,500);yl <- c(-.3, .2)
 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(300,-.08, leg=paste("nu=",nus), col = nus+2, lwd=1)

 x <- seq(10,50000,by=10);yl <- c(-.1, .1)
 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)}
 summary(bY <- besselY(2,nu = nu <- seq(0,100,len=501)))
 which(bY >= 0)
 summary(bY <- besselY(2,nu = nu <- seq(3,300,len=51)))
 summary(bI <- besselI(x = x <- 10:700, 1))
}

}
\keyword{math}

\name{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}.
}
\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}
\name{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.
}
\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
plot (0:n,     dbinom(0:n, n, pi/10, log=TRUE), type='l',
      main = "dbinom(*, log=TRUE) is better than  log(dbinom(*))")
lines(0:n, log(dbinom(0:n, n, pi/10)), col='red', lwd=2)
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}
\name{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}.
}
\seealso{
  \code{\link{dt}} for the t distribution which generalizes
  \code{dcauchy(*, l = 0, s = 1)}.
}
\examples{
all.equal(dcauchy(-1:4), 1 / (pi*(1 + (-1:4)^2)))
}
\keyword{distribution}
\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.}
  \item{ncp}{non-centrality parameter.  For \code{rnchisq}, \code{ncp=0}
    is the only possible value.}
  \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}.  It 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.
}
\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))
}
\keyword{distribution}
\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
}
\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.
}
\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}
\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.
  }
}
\seealso{
  \code{\link{data}}.
}
\examples{
stopifnot(
 nchar(letters) == 1,
 month.abb == substr(month.name, 1, 3)
)
eps <- .Machine$double.eps
all.equal(pi, 4*atan(1), tol= 2*eps)

# John Machin (1705) computed 100 decimals of pi :
all.equal(pi/4, 4*atan(1/5) - atan(1/239), 4*eps)
}
\keyword{sysdata}
\name{Control}
\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
}
\alias{if}
\alias{else}
\alias{for}
\alias{while}
\alias{repeat}
\alias{break}
\alias{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.
}
\seealso{
\code{\link{ifelse}},
\code{\link{switch}}.
}
\examples{
for(i in 1:5) print(1:i)
}
\keyword{programming}
\keyword{iteration}
\keyword{logic}
\name{DateTimeClasses}
% implementation mostly in ../R/datetime.R
\alias{DateTimeClasses}
\alias{POSIXct}
\alias{POSIXlt}
\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{as.data.frame.POSIXct}
\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}

% back-compatibility functions
\alias{-.POSIXct}
\alias{-.POSIXlt}
\alias{Ops.POSIXct}
\alias{Ops.POSIXlt}

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

summary.POSIXct(object, digits = 15, ...)
summary.POSIXlt(object, digits = 15, ...)

time + number
time - number
time1 lop time2
}
\arguments{
  \item{x, object}{An object to be printed or summarized.}
  \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 ``calendar time''
  (the \code{time\_t} data type) and ``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
  \code{"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

%% `advanced' examples:
\testonly{
str(.leap.seconds)

## Wouldn't we want a  diff.POSIXt()  method ?
(dls <- .leap.seconds[-1] - .leap.seconds[-22])
table(dls)
}
}
\keyword{utilities}
\keyword{chron}
\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}
%
\description{
  The functions 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>
}
\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.
}
\seealso{\code{\link{Deprecated}}}
\keyword{documentation}
\keyword{utilities}
\keyword{internal}
\name{Deprecated}
%------ NOTE:  ../R/Deprecated.R   must be synchronized with this!
\title{Deprecated Functions}
\alias{Deprecated}
\alias{.Deprecated}
\alias{.Alias}
\alias{reshapeWide}
\alias{reshapeLong}
%------ 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)
.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")
}
\details{
  \code{.Deprecated("<new name>")} is called from deprecated
  functions. The original help page for these functions is available at
  \code{help("oldName-deprecated")} (note the quotes).

  \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 replace by
  \code{\link{reshape}}. This has a different syntax and allows multiple
  time-varying variables.  See \code{\link{reshapeLong-deprecated}} and
  \code{\link{reshapeWide-deprecated}} for the earlier syntax.

}
\seealso{\code{\link{Defunct}},
  \code{\link{.Alias-deprecated}},\code{\link{reshapeWide-deprecated}}, \code{\link{reshapeLong-deprecated}}}
\keyword{documentation}
\keyword{utilities}
\name{Devices}
\title{List of Graphical Devices}
\usage{
#ifdef unix
x11(\dots)
#endif
#ifdef windows
windows(\dots)
#endif
#ifdef mac
macintosh(\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
#ifdef mac
    \item \code{\link{macintosh}} The graphics driver for the Macintosh
#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 \code{--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.
  }
  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.
}
\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.
#endif
}
\keyword{device}
\name{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}.
}
\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
r <- rexp(100)
all(abs(1 - dexp(1, r) / (r*exp(-r))) < 1e-14)
}
\keyword{distribution}
\name{Extract}
\title{Extract or Replace Parts of an Object}
\alias{Extract}
\alias{Subscript}
\alias{[}
\alias{[[}
\alias{$}
\alias{[<-}
\alias{[[<-}
\alias{$<-}
%- methods
\alias{[.data.frame}
\alias{[[.data.frame}
\alias{[<-.data.frame}
\alias{[[<-.data.frame}
\alias{[.factor}
\alias{[.formula}
\alias{[.ts}
\alias{[<-.factor}
\alias{[.noquote}
\alias{[<-.noquote}
\description{
  Operators act on vectors, arrays, dataframes and lists to extract or
  replace subsets.
}
\usage{
x[i]
x[i, j, \dots]
x[i, j, \dots , drop=TRUE]
x[[i]]
x[[i, j, \dots]]
x$name
}
\arguments{
  \item{i,j,name}{elements to extract or replace}
  \item{drop}{For data frames, matrices, and arrays.  If \code{TRUE} the
    result is coerced to the lowest possible dimension (see examples
    below).}
}
\details{
  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.

  These operators are generic. You can write methods to handle subsetting
  of specific classes of data.

  The \code{[[} operator requires all relevant subscripts be supplied.
  With the \code{[} operator a comma separated blank indicates that all
  entries in that dimension are selected.

  When \code{[.data.frame} is used for subsetting rows of a
  \code{\link{data.frame}}, it returns a dataframe with unique row names,
  using \code{\link{make.names}( * , unique = TRUE)}, see the \code{swiss}
  example below.

  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.

  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.
}
\seealso{
  \code{\link{list}}, \code{\link{array}}, \code{\link{matrix}}.
}
\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
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

data(swiss)
swiss[ c(1, 1:2), ]   # duplicate row, unique row names
}
\keyword{array}
\keyword{list}
\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}.

  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 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).
}
\seealso{
  \code{\link{range}}.
}
\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}
\name{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.  
}
\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}
\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 ``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 ``System and foreign language
  interfaces'' in ``Writing \R Extensions'' in the \file{doc/manual}
  subdirectory of the \R source tree).
}
%%-- 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.)

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

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

\seealso{\code{\link{dyn.load}}.}
\keyword{programming}
\name{Formaldehyde}
\title{Determination of Formaldehyde}
\usage{data(Formaldehyde)}
\alias{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.
}
\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.
}
\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}
\name{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)}.
}
\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}
\name{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{
pp <- sort(c((1:9)/10, 1 - .2^(2:8)))
print(qg <- qgeom(pp, prob = .2))
## test that qgeom is an inverse of pgeom
print(qg1 <- qgeom(pgeom(qg, prob=.2), prob =.2))
all(qg == qg1)
Ni <- rgeom(20, prob = 1/4); table(factor(Ni, 0:max(Ni)))
}
\keyword{distribution}
\name{HairEyeColor}
\alias{HairEyeColor}
\title{Hair and Eye Color of Statistics Students}
\usage{data(HairEyeColor)}
\description{
  Distribution of hair and eye color and sex in 592 statistics students.
}
\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://hotspur.psych.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://hotspur.psych.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}
\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 ``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{example(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.}

    \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{example(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...377.  For example, \code{\\366} produces the character \code{o}
    with an
    umlaut.  The third table in \code{example(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{example(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{example(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 idenitified 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 ``one'' is
    produced by \code{\\\\#N0001}.}

    \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{example(Hershey)} shows all of the available raw glyphs.}
  }
}
\references{
  \url{http://www.gnu.org/software/plotutils/plotutils.html}

}
\seealso{
  \code{\link{text}},
  \code{\link{contour}},
  \code{\link{Japanese}}
}
\examples{
str(Hershey)

######
# create tables of vector font functionality
######
make.table <- function(nr, nc) {
    savepar <- par(mar=rep(0, 4), pty="s")
    plot(c(0, nc*2 + 1), c(0, -(nr + 1)),
         type="n", xlab="", ylab="", axes=FALSE)
    savepar
}

get.r <- function(i, nr)     i \%\% nr + 1
get.c <- function(i, nr)     i \%/\% nr + 1

draw.title <- function(title, i = 0, nr, nc) {
    r <- get.r(i, nr)
    c <- get.c(i, nr)
    text((nc*2 + 1)/2, 0, title, font=2)
}

draw.sample.cell <- function(typeface, fontindex, string, i, nr) {
    r <- get.r(i, nr)
    c <- get.c(i, nr)
    text(2*(c - 1) + 1, -r, paste(typeface, fontindex))
    text(2*c, -r, string, vfont=c(typeface, fontindex), cex=1.5)
    rect(2*(c - 1) + .5, -(r - .5), 2*c + .5, -(r + .5), border="grey")
}

draw.vf.cell <- function(typeface, fontindex, string, i, nr, raw.string=NULL) {
    r <- get.r(i, nr)
    c <- get.c(i, nr)
    if (is.null(raw.string))
        raw.string <- paste("\\\\", string, sep="")
    text(2*(c - 1) + 1, -r, raw.string, col="grey")
    text(2*c, -r, string, vfont=c(typeface, fontindex))
    rect(2*(c - 1) + .5, -(r - .5), (2*c + .5), -(r + .5), border="grey")
}

nr <- 23
nc <- 1
oldpar <- make.table(nr, nc)
i <- 0
draw.title("Sample 'a' for each available font", i, nr, nc)
draw.sample.cell("serif", "plain", "a", i, nr); i <- i + 1
draw.sample.cell("serif", "italic", "a", i, nr); i <- i + 1
draw.sample.cell("serif", "bold", "a", i, nr); i <- i + 1
draw.sample.cell("serif", "bold italic", "a", i, nr); i <- i + 1
draw.sample.cell("serif", "cyrillic", "a", i, nr); i <- i + 1
draw.sample.cell("serif", "oblique cyrillic", "a", i, nr); i <- i + 1
draw.sample.cell("serif", "EUC", "a", i, nr); i <- i + 1
draw.sample.cell("sans serif", "plain", "a", i, nr); i <- i + 1
draw.sample.cell("sans serif", "italic", "a", i, nr); i <- i + 1
draw.sample.cell("sans serif", "bold", "a", i, nr); i <- i + 1
draw.sample.cell("sans serif", "bold italic", "a", i, nr); i <- i + 1
draw.sample.cell("script", "plain", "a", i, nr); i <- i + 1
draw.sample.cell("script", "italic", "a", i, nr); i <- i + 1
draw.sample.cell("script", "bold", "a", i, nr); i <- i + 1
draw.sample.cell("gothic english", "plain", "a", i, nr); i <- i + 1
draw.sample.cell("gothic german", "plain", "a", i, nr); i <- i + 1
draw.sample.cell("gothic italian", "plain", "a", i, nr); i <- i + 1
draw.sample.cell("serif symbol", "plain", "a", i, nr); i <- i + 1
draw.sample.cell("serif symbol", "italic", "a", i, nr); i <- i + 1
draw.sample.cell("serif symbol", "bold", "a", i, nr); i <- i + 1
draw.sample.cell("serif symbol", "bold italic", "a", i, nr); i <- i + 1
draw.sample.cell("sans serif symbol", "plain", "a", i, nr); i <- i + 1
draw.sample.cell("sans serif symbol", "italic", "a", i, nr); i <- i + 1

nr <- 25
nc <- 6
tf <- "serif"
fi <- "plain"
make.table(nr, nc)
i <- 0
draw.title("Symbol (incl. Greek) Escape Sequences", i, nr, nc)
%% double each backslash here in *.Rd !
## Greek alphabet in order
draw.vf.cell(tf, fi, "\\\\*A", i, nr); i<-i+1; { "Alpha"}
draw.vf.cell(tf, fi, "\\\\*B", i, nr); i<-i+1; { "Beta"}
draw.vf.cell(tf, fi, "\\\\*G", i, nr); i<-i+1; { "Gamma"}
draw.vf.cell(tf, fi, "\\\\*D", i, nr); i<-i+1; { "Delta"}
draw.vf.cell(tf, fi, "\\\\*E", i, nr); i<-i+1; { "Epsilon"}
draw.vf.cell(tf, fi, "\\\\*Z", i, nr); i<-i+1; { "Zeta"}
draw.vf.cell(tf, fi, "\\\\*Y", i, nr); i<-i+1; { "Eta"}
draw.vf.cell(tf, fi, "\\\\*H", i, nr); i<-i+1; { "Theta"}
draw.vf.cell(tf, fi, "\\\\*I", i, nr); i<-i+1; { "Iota"}
draw.vf.cell(tf, fi, "\\\\*K", i, nr); i<-i+1; { "Kappa"}
draw.vf.cell(tf, fi, "\\\\*L", i, nr); i<-i+1; { "Lambda"}
draw.vf.cell(tf, fi, "\\\\*M", i, nr); i<-i+1; { "Mu"}
draw.vf.cell(tf, fi, "\\\\*N", i, nr); i<-i+1; { "Nu"}
draw.vf.cell(tf, fi, "\\\\*C", i, nr); i<-i+1; { "Xi"}
draw.vf.cell(tf, fi, "\\\\*O", i, nr); i<-i+1; { "Omicron"}
draw.vf.cell(tf, fi, "\\\\*P", i, nr); i<-i+1; { "Pi"}
draw.vf.cell(tf, fi, "\\\\*R", i, nr); i<-i+1; { "Rho"}
draw.vf.cell(tf, fi, "\\\\*S", i, nr); i<-i+1; { "Sigma"}
draw.vf.cell(tf, fi, "\\\\*T", i, nr); i<-i+1; { "Tau"}
draw.vf.cell(tf, fi, "\\\\*U", i, nr); i<-i+1; { "Upsilon"}
draw.vf.cell(tf, fi, "\\\\+U", i, nr); i<-i+1; { "Upsilon1"}
draw.vf.cell(tf, fi, "\\\\*F", i, nr); i<-i+1; { "Phi"}
draw.vf.cell(tf, fi, "\\\\*X", i, nr); i<-i+1; { "Chi"}
draw.vf.cell(tf, fi, "\\\\*Q", i, nr); i<-i+1; { "Psi"}
draw.vf.cell(tf, fi, "\\\\*W", i, nr); i<-i+1; { "Omega"}
#
draw.vf.cell(tf, fi, "\\\\*a", i, nr); i<-i+1; { "alpha"}
draw.vf.cell(tf, fi, "\\\\*b", i, nr); i<-i+1; { "beta"}
draw.vf.cell(tf, fi, "\\\\*g", i, nr); i<-i+1; { "gamma"}
draw.vf.cell(tf, fi, "\\\\*d", i, nr); i<-i+1; { "delta"}
draw.vf.cell(tf, fi, "\\\\*e", i, nr); i<-i+1; { "epsilon"}
draw.vf.cell(tf, fi, "\\\\*z", i, nr); i<-i+1; { "zeta"}
draw.vf.cell(tf, fi, "\\\\*y", i, nr); i<-i+1; { "eta"}
draw.vf.cell(tf, fi, "\\\\*h", i, nr); i<-i+1; { "theta"}
draw.vf.cell(tf, fi, "\\\\+h", i, nr); i<-i+1; { "theta1"}
draw.vf.cell(tf, fi, "\\\\*i", i, nr); i<-i+1; { "iota"}
draw.vf.cell(tf, fi, "\\\\*k", i, nr); i<-i+1; { "kappa"}
draw.vf.cell(tf, fi, "\\\\*l", i, nr); i<-i+1; { "lambda"}
draw.vf.cell(tf, fi, "\\\\*m", i, nr); i<-i+1; { "mu"}
draw.vf.cell(tf, fi, "\\\\*n", i, nr); i<-i+1; { "nu"}
draw.vf.cell(tf, fi, "\\\\*c", i, nr); i<-i+1; { "xi"}
draw.vf.cell(tf, fi, "\\\\*o", i, nr); i<-i+1; { "omicron"}
draw.vf.cell(tf, fi, "\\\\*p", i, nr); i<-i+1; { "pi"}
draw.vf.cell(tf, fi, "\\\\*r", i, nr); i<-i+1; { "rho"}
draw.vf.cell(tf, fi, "\\\\*s", i, nr); i<-i+1; { "sigma"}
draw.vf.cell(tf, fi, "\\\\ts", i, nr); i<-i+1; { "sigma1"}
draw.vf.cell(tf, fi, "\\\\*t", i, nr); i<-i+1; { "tau"}
draw.vf.cell(tf, fi, "\\\\*u", i, nr); i<-i+1; { "upsilon"}
draw.vf.cell(tf, fi, "\\\\*f", i, nr); i<-i+1; { "phi"}
draw.vf.cell(tf, fi, "\\\\+f", i, nr); i<-i+1; { "phi1"}
draw.vf.cell(tf, fi, "\\\\*x", i, nr); i<-i+1; { "chi"}
draw.vf.cell(tf, fi, "\\\\*q", i, nr); i<-i+1; { "psi"}
draw.vf.cell(tf, fi, "\\\\*w", i, nr); i<-i+1; { "omega"}
draw.vf.cell(tf, fi, "\\\\+p", i, nr); i<-i+1; { "omega1"}
#
draw.vf.cell(tf, fi, "\\\\fa", i, nr); i<-i+1; { "universal"}
draw.vf.cell(tf, fi, "\\\\te", i, nr); i<-i+1; { "existential"}
draw.vf.cell(tf, fi, "\\\\st", i, nr); i<-i+1; { "suchthat"}
draw.vf.cell(tf, fi, "\\\\**", i, nr); i<-i+1; { "asteriskmath"}
draw.vf.cell(tf, fi, "\\\\=~", i, nr); i<-i+1; { "congruent"}
draw.vf.cell(tf, fi, "\\\\tf", i, nr); i<-i+1; { "therefore"}
draw.vf.cell(tf, fi, "\\\\pp", i, nr); i<-i+1; { "perpendicular"}
draw.vf.cell(tf, fi, "\\\\ul", i, nr); i<-i+1; { "underline"}
draw.vf.cell(tf, fi, "\\\\rx", i, nr); i<-i+1; { "radicalex"}

draw.vf.cell(tf, fi, "\\\\ap", i, nr); i<-i+1; { "similar"}
draw.vf.cell(tf, fi, "\\\\fm", i, nr); i<-i+1; { "minute"}
draw.vf.cell(tf, fi, "\\\\<=", i, nr); i<-i+1; { "lessequal"}
draw.vf.cell(tf, fi, "\\\\f/", i, nr); i<-i+1; { "fraction"}
draw.vf.cell(tf, fi, "\\\\if", i, nr); i<-i+1; { "infinity"}
draw.vf.cell(tf, fi, "\\\\Fn", i, nr); i<-i+1; { "florin"}
draw.vf.cell(tf, fi, "\\\\CL", i, nr); i<-i+1; { "club"}
draw.vf.cell(tf, fi, "\\\\DI", i, nr); i<-i+1; { "diamond"}
draw.vf.cell(tf, fi, "\\\\HE", i, nr); i<-i+1; { "heart"}
draw.vf.cell(tf, fi, "\\\\SP", i, nr); i<-i+1; { "spade"}
draw.vf.cell(tf, fi, "\\\\<>", i, nr); i<-i+1; { "arrowboth"}
draw.vf.cell(tf, fi, "\\\\<-", i, nr); i<-i+1; { "arrowleft"}
draw.vf.cell(tf, fi, "\\\\ua", i, nr); i<-i+1; { "arrowup"}
draw.vf.cell(tf, fi, "\\\\->", i, nr); i<-i+1; { "arrowright"}
draw.vf.cell(tf, fi, "\\\\da", i, nr); i<-i+1; { "arrowdown"}
draw.vf.cell(tf, fi, "\\\\de", i, nr); i<-i+1; { "degree"}
draw.vf.cell(tf, fi, "\\\\+-", i, nr); i<-i+1; { "plusminus"}
draw.vf.cell(tf, fi, "\\\\sd", i, nr); i<-i+1; { "second"}
draw.vf.cell(tf, fi, "\\\\>=", i, nr); i<-i+1; { "greaterequal"}
draw.vf.cell(tf, fi, "\\\\mu", i, nr); i<-i+1; { "multiply"}
draw.vf.cell(tf, fi, "\\\\pt", i, nr); i<-i+1; { "proportional"}
draw.vf.cell(tf, fi, "\\\\pd", i, nr); i<-i+1; { "partialdiff"}
draw.vf.cell(tf, fi, "\\\\bu", i, nr); i<-i+1; { "bullet"}
draw.vf.cell(tf, fi, "\\\\di", i, nr); i<-i+1; { "divide"}
draw.vf.cell(tf, fi, "\\\\!=", i, nr); i<-i+1; { "notequal"}
draw.vf.cell(tf, fi, "\\\\==", i, nr); i<-i+1; { "equivalence"}
draw.vf.cell(tf, fi, "\\\\~~", i, nr); i<-i+1; { "approxequal"}
draw.vf.cell(tf, fi, "\\\\..", i, nr); i<-i+1; { "ellipsis"}
draw.vf.cell(tf, fi, "\\\\an", i, nr); i<-i+1; { "arrowhorizex"}
draw.vf.cell(tf, fi, "\\\\CR", i, nr); i<-i+1; { "carriagereturn"}
draw.vf.cell(tf, fi, "\\\\Ah", i, nr); i<-i+1; { "aleph"}
draw.vf.cell(tf, fi, "\\\\Im", i, nr); i<-i+1; { "Ifraktur"}
draw.vf.cell(tf, fi, "\\\\Re", i, nr); i<-i+1; { "Rfraktur"}
draw.vf.cell(tf, fi, "\\\\wp", i, nr); i<-i+1; { "weierstrass"}
draw.vf.cell(tf, fi, "\\\\c*", i, nr); i<-i+1; { "circlemultiply"}
draw.vf.cell(tf, fi, "\\\\c+", i, nr); i<-i+1; { "circleplus"}
draw.vf.cell(tf, fi, "\\\\es", i, nr); i<-i+1; { "emptyset"}
draw.vf.cell(tf, fi, "\\\\ca", i, nr); i<-i+1; { "cap"}
draw.vf.cell(tf, fi, "\\\\cu", i, nr); i<-i+1; { "cup"}
draw.vf.cell(tf, fi, "\\\\SS", i, nr); i<-i+1; { "superset"}
draw.vf.cell(tf, fi, "\\\\ip", i, nr); i<-i+1; { "reflexsuperset"}
draw.vf.cell(tf, fi, "\\\\n<", i, nr); i<-i+1; { "notsubset"}
draw.vf.cell(tf, fi, "\\\\SB", i, nr); i<-i+1; { "subset"}
draw.vf.cell(tf, fi, "\\\\ib", i, nr); i<-i+1; { "reflexsubset"}
draw.vf.cell(tf, fi, "\\\\mo", i, nr); i<-i+1; { "element"}
draw.vf.cell(tf, fi, "\\\\nm", i, nr); i<-i+1; { "notelement"}
draw.vf.cell(tf, fi, "\\\\/_", i, nr); i<-i+1; { "angle"}
draw.vf.cell(tf, fi, "\\\\gr", i, nr); i<-i+1; { "nabla"}
draw.vf.cell(tf, fi, "\\\\rg", i, nr); i<-i+1; { "registerserif"}
draw.vf.cell(tf, fi, "\\\\co", i, nr); i<-i+1; { "copyrightserif"}
draw.vf.cell(tf, fi, "\\\\tm", i, nr); i<-i+1; { "trademarkserif"}
draw.vf.cell(tf, fi, "\\\\PR", i, nr); i<-i+1; { "product"}
draw.vf.cell(tf, fi, "\\\\sr", i, nr); i<-i+1; { "radical"}
draw.vf.cell(tf, fi, "\\\\md", i, nr); i<-i+1; { "dotmath"}
draw.vf.cell(tf, fi, "\\\\no", i, nr); i<-i+1; { "logicalnot"}
draw.vf.cell(tf, fi, "\\\\AN", i, nr); i<-i+1; { "logicaland"}
draw.vf.cell(tf, fi, "\\\\OR", i, nr); i<-i+1; { "logicalor"}
draw.vf.cell(tf, fi, "\\\\hA", i, nr); i<-i+1; { "arrowdblboth"}
draw.vf.cell(tf, fi, "\\\\lA", i, nr); i<-i+1; { "arrowdblleft"}
draw.vf.cell(tf, fi, "\\\\uA", i, nr); i<-i+1; { "arrowdblup"}
draw.vf.cell(tf, fi, "\\\\rA", i, nr); i<-i+1; { "arrowdblright"}
draw.vf.cell(tf, fi, "\\\\dA", i, nr); i<-i+1; { "arrowdbldown"}
draw.vf.cell(tf, fi, "\\\\lz", i, nr); i<-i+1; { "lozenge"}
draw.vf.cell(tf, fi, "\\\\la", i, nr); i<-i+1; { "angleleft"}
draw.vf.cell(tf, fi, "\\\\RG", i, nr); i<-i+1; { "registersans"}
draw.vf.cell(tf, fi, "\\\\CO", i, nr); i<-i+1; { "copyrightsans"}
draw.vf.cell(tf, fi, "\\\\TM", i, nr); i<-i+1; { "trademarksans"}
draw.vf.cell(tf, fi, "\\\\SU", i, nr); i<-i+1; { "summation"}
draw.vf.cell(tf, fi, "\\\\lc", i, nr); i<-i+1; { "bracketlefttp"}
draw.vf.cell(tf, fi, "\\\\lf", i, nr); i<-i+1; { "bracketleftbt"}
draw.vf.cell(tf, fi, "\\\\ra", i, nr); i<-i+1; { "angleright"}
draw.vf.cell(tf, fi, "\\\\is", i, nr); i<-i+1; { "integral"}
draw.vf.cell(tf, fi, "\\\\rc", i, nr); i<-i+1; { "bracketrighttp"}
draw.vf.cell(tf, fi, "\\\\rf", i, nr); i<-i+1; { "bracketrightbt"}
draw.vf.cell(tf, fi, "\\\\~=", i, nr); i<-i+1; { "congruent"}
draw.vf.cell(tf, fi, "\\\\pr", i, nr); i<-i+1; { "minute"}
draw.vf.cell(tf, fi, "\\\\in", i, nr); i<-i+1; { "infinity"}
draw.vf.cell(tf, fi, "\\\\n=", i, nr); i<-i+1; { "notequal"}
draw.vf.cell(tf, fi, "\\\\dl", i, nr); i<-i+1; { "nabla"}

nr <- 25
nc <- 4
make.table(nr, nc)
i <- 0
draw.title("ISO Latin-1 Escape Sequences", i, nr, nc)
draw.vf.cell(tf, fi, "\\\\r!", i, nr); i<-i+1; { "exclamdown"}
draw.vf.cell(tf, fi, "\\\\ct", i, nr); i<-i+1; { "cent"}
draw.vf.cell(tf, fi, "\\\\Po", i, nr); i<-i+1; { "sterling"}
draw.vf.cell(tf, fi, "\\\\Ye", i, nr); i<-i+1; { "yen"}
draw.vf.cell(tf, fi, "\\\\bb", i, nr); i<-i+1; { "brokenbar"}
draw.vf.cell(tf, fi, "\\\\sc", i, nr); i<-i+1; { "section"}
draw.vf.cell(tf, fi, "\\\\ad", i, nr); i<-i+1; { "dieresis"}
draw.vf.cell(tf, fi, "\\\\co", i, nr); i<-i+1; { "copyright"}
draw.vf.cell(tf, fi, "\\\\Of", i, nr); i<-i+1; { "ordfeminine"}
draw.vf.cell(tf, fi, "\\\\no", i, nr); i<-i+1; { "logicalnot"}
draw.vf.cell(tf, fi, "\\\\hy", i, nr); i<-i+1; { "hyphen"}
draw.vf.cell(tf, fi, "\\\\rg", i, nr); i<-i+1; { "registered"}
draw.vf.cell(tf, fi, "\\\\a-", i, nr); i<-i+1; { "macron"}
draw.vf.cell(tf, fi, "\\\\de", i, nr); i<-i+1; { "degree"}
draw.vf.cell(tf, fi, "\\\\+-", i, nr); i<-i+1; { "plusminus"}
draw.vf.cell(tf, fi, "\\\\S2", i, nr); i<-i+1; { "twosuperior"}
draw.vf.cell(tf, fi, "\\\\S3", i, nr); i<-i+1; { "threesuperior"}
draw.vf.cell(tf, fi, "\\\\aa", i, nr); i<-i+1; { "acute"}
draw.vf.cell(tf, fi, "\\\\*m", i, nr); i<-i+1; { "mu"}
draw.vf.cell(tf, fi, "\\\\md", i, nr); i<-i+1; { "periodcentered"}
draw.vf.cell(tf, fi, "\\\\S1", i, nr); i<-i+1; { "onesuperior"}
draw.vf.cell(tf, fi, "\\\\Om", i, nr); i<-i+1; { "ordmasculine"}
draw.vf.cell(tf, fi, "\\\\14", i, nr); i<-i+1; { "onequarter"}
draw.vf.cell(tf, fi, "\\\\12", i, nr); i<-i+1; { "onehalf"}
draw.vf.cell(tf, fi, "\\\\34", i, nr); i<-i+1; { "threequarters"}
draw.vf.cell(tf, fi, "\\\\r?", i, nr); i<-i+1; { "questiondown"}
draw.vf.cell(tf, fi, "\\\\`A", i, nr); i<-i+1; { "Agrave"}
draw.vf.cell(tf, fi, "\\\\'A", i, nr); i<-i+1; { "Aacute"}
draw.vf.cell(tf, fi, "\\\\^A", i, nr); i<-i+1; { "Acircumflex"}
draw.vf.cell(tf, fi, "\\\\~A", i, nr); i<-i+1; { "Atilde"}
draw.vf.cell(tf, fi, "\\\\:A", i, nr); i<-i+1; { "Adieresis"}
draw.vf.cell(tf, fi, "\\\\oA", i, nr); i<-i+1; { "Aring"}
draw.vf.cell(tf, fi, "\\\\AE", i, nr); i<-i+1; { "AE"}
draw.vf.cell(tf, fi, "\\\\,C", i, nr); i<-i+1; { "Ccedilla"}
draw.vf.cell(tf, fi, "\\\\`E", i, nr); i<-i+1; { "Egrave"}
draw.vf.cell(tf, fi, "\\\\'E", i, nr); i<-i+1; { "Eacute"}
draw.vf.cell(tf, fi, "\\\\^E", i, nr); i<-i+1; { "Ecircumflex"}
draw.vf.cell(tf, fi, "\\\\:E", i, nr); i<-i+1; { "Edieresis"}
draw.vf.cell(tf, fi, "\\\\`I", i, nr); i<-i+1; { "Igrave"}
draw.vf.cell(tf, fi, "\\\\'I", i, nr); i<-i+1; { "Iacute"}
draw.vf.cell(tf, fi, "\\\\^I", i, nr); i<-i+1; { "Icircumflex"}
draw.vf.cell(tf, fi, "\\\\:I", i, nr); i<-i+1; { "Idieresis"}
draw.vf.cell(tf, fi, "\\\\~N", i, nr); i<-i+1; { "Ntilde"}
draw.vf.cell(tf, fi, "\\\\`O", i, nr); i<-i+1; { "Ograve"}
draw.vf.cell(tf, fi, "\\\\'O", i, nr); i<-i+1; { "Oacute"}
draw.vf.cell(tf, fi, "\\\\^O", i, nr); i<-i+1; { "Ocircumflex"}
draw.vf.cell(tf, fi, "\\\\~O", i, nr); i<-i+1; { "Otilde"}
draw.vf.cell(tf, fi, "\\\\:O", i, nr); i<-i+1; { "Odieresis"}
draw.vf.cell(tf, fi, "\\\\mu", i, nr); i<-i+1; { "multiply"}
draw.vf.cell(tf, fi, "\\\\/O", i, nr); i<-i+1; { "Oslash"}
draw.vf.cell(tf, fi, "\\\\`U", i, nr); i<-i+1; { "Ugrave"}
draw.vf.cell(tf, fi, "\\\\'U", i, nr); i<-i+1; { "Uacute"}
draw.vf.cell(tf, fi, "\\\\^U", i, nr); i<-i+1; { "Ucircumflex"}
draw.vf.cell(tf, fi, "\\\\:U", i, nr); i<-i+1; { "Udieresis"}
draw.vf.cell(tf, fi, "\\\\'Y", i, nr); i<-i+1; { "Yacute"}
draw.vf.cell(tf, fi, "\\\\ss", i, nr); i<-i+1; { "germandbls"} # WRONG!
draw.vf.cell(tf, fi, "\\\\`a", i, nr); i<-i+1; { "agrave"}
draw.vf.cell(tf, fi, "\\\\'a", i, nr); i<-i+1; { "aacute"}
draw.vf.cell(tf, fi, "\\\\^a", i, nr); i<-i+1; { "acircumflex"}
draw.vf.cell(tf, fi, "\\\\~a", i, nr); i<-i+1; { "atilde"}
draw.vf.cell(tf, fi, "\\\\:a", i, nr); i<-i+1; { "adieresis"}
draw.vf.cell(tf, fi, "\\\\oa", i, nr); i<-i+1; { "aring"}
draw.vf.cell(tf, fi, "\\\\ae", i, nr); i<-i+1; { "ae"}
draw.vf.cell(tf, fi, "\\\\,c", i, nr); i<-i+1; { "ccedilla"}
draw.vf.cell(tf, fi, "\\\\`e", i, nr); i<-i+1; { "egrave"}
draw.vf.cell(tf, fi, "\\\\'e", i, nr); i<-i+1; { "eacute"}
draw.vf.cell(tf, fi, "\\\\^e", i, nr); i<-i+1; { "ecircumflex"}
draw.vf.cell(tf, fi, "\\\\:e", i, nr); i<-i+1; { "edieresis"}
draw.vf.cell(tf, fi, "\\\\`i", i, nr); i<-i+1; { "igrave"}
draw.vf.cell(tf, fi, "\\\\'i", i, nr); i<-i+1; { "iacute"}
draw.vf.cell(tf, fi, "\\\\^i", i, nr); i<-i+1; { "icircumflex"}
draw.vf.cell(tf, fi, "\\\\:i", i, nr); i<-i+1; { "idieresis"}
draw.vf.cell(tf, fi, "\\\\~n", i, nr); i<-i+1; { "ntilde"}
draw.vf.cell(tf, fi, "\\\\`o", i, nr); i<-i+1; { "ograve"}
draw.vf.cell(tf, fi, "\\\\'o", i, nr); i<-i+1; { "oacute"}
draw.vf.cell(tf, fi, "\\\\^o", i, nr); i<-i+1; { "ocircumflex"}
draw.vf.cell(tf, fi, "\\\\~o", i, nr); i<-i+1; { "otilde"}
draw.vf.cell(tf, fi, "\\\\:o", i, nr); i<-i+1; { "odieresis"}
draw.vf.cell(tf, fi, "\\\\di", i, nr); i<-i+1; { "divide"}
draw.vf.cell(tf, fi, "\\\\/o", i, nr); i<-i+1; { "oslash"}
draw.vf.cell(tf, fi, "\\\\`u", i, nr); i<-i+1; { "ugrave"}
draw.vf.cell(tf, fi, "\\\\'u", i, nr); i<-i+1; { "uacute"}
draw.vf.cell(tf, fi, "\\\\^u", i, nr); i<-i+1; { "ucircumflex"}
draw.vf.cell(tf, fi, "\\\\:u", i, nr); i<-i+1; { "udieresis"}
draw.vf.cell(tf, fi, "\\\\'y", i, nr); i<-i+1; { "yacute"}
draw.vf.cell(tf, fi, "\\\\:y", i, nr); i<-i+1; { "ydieresis"}

nr <- 25
nc <- 2
make.table(nr, nc)
i <- 0
draw.title("Special Escape Sequences", i, nr, nc)
draw.vf.cell(tf, fi, "\\\\AR", i, nr); i<-i+1; { "aries"}
draw.vf.cell(tf, fi, "\\\\TA", i, nr); i<-i+1; { "taurus"}
draw.vf.cell(tf, fi, "\\\\GE", i, nr); i<-i+1; { "gemini"}
draw.vf.cell(tf, fi, "\\\\CA", i, nr); i<-i+1; { "cancer"}
draw.vf.cell(tf, fi, "\\\\LE", i, nr); i<-i+1; { "leo"}
draw.vf.cell(tf, fi, "\\\\VI", i, nr); i<-i+1; { "virgo"}
draw.vf.cell(tf, fi, "\\\\LI", i, nr); i<-i+1; { "libra"}
draw.vf.cell(tf, fi, "\\\\SC", i, nr); i<-i+1; { "scorpio"}
draw.vf.cell(tf, fi, "\\\\SG", i, nr); i<-i+1; { "sagittarius"}
draw.vf.cell(tf, fi, "\\\\CP", i, nr); i<-i+1; { "capricornus"}
draw.vf.cell(tf, fi, "\\\\AQ", i, nr); i<-i+1; { "aquarius"}
draw.vf.cell(tf, fi, "\\\\PI", i, nr); i<-i+1; { "pisces"}
draw.vf.cell(tf, fi, "\\\\~-", i, nr); i<-i+1; { "modifiedcongruent"}
draw.vf.cell(tf, fi, "\\\\hb", i, nr); i<-i+1; { "hbar"}
draw.vf.cell(tf, fi, "\\\\IB", i, nr); i<-i+1; { "interbang"}
draw.vf.cell(tf, fi, "\\\\Lb", i, nr); i<-i+1; { "lambdabar"}
draw.vf.cell(tf, fi, "\\\\UD", i, nr); i<-i+1; { "undefined"}
draw.vf.cell(tf, fi, "\\\\SO", i, nr); i<-i+1; { "sun"}
draw.vf.cell(tf, fi, "\\\\ME", i, nr); i<-i+1; { "mercury"}
draw.vf.cell(tf, fi, "\\\\VE", i, nr); i<-i+1; { "venus"}
draw.vf.cell(tf, fi, "\\\\EA", i, nr); i<-i+1; { "earth"}
draw.vf.cell(tf, fi, "\\\\MA", i, nr); i<-i+1; { "mars"}
draw.vf.cell(tf, fi, "\\\\JU", i, nr); i<-i+1; { "jupiter"}
draw.vf.cell(tf, fi, "\\\\SA", i, nr); i<-i+1; { "saturn"}
draw.vf.cell(tf, fi, "\\\\UR", i, nr); i<-i+1; { "uranus"}
draw.vf.cell(tf, fi, "\\\\NE", i, nr); i<-i+1; { "neptune"}
draw.vf.cell(tf, fi, "\\\\PL", i, nr); i<-i+1; { "pluto"}
draw.vf.cell(tf, fi, "\\\\LU", i, nr); i<-i+1; { "moon"}
draw.vf.cell(tf, fi, "\\\\CT", i, nr); i<-i+1; { "comet"}
draw.vf.cell(tf, fi, "\\\\ST", i, nr); i<-i+1; { "star"}
draw.vf.cell(tf, fi, "\\\\AS", i, nr); i<-i+1; { "ascendingnode"}
draw.vf.cell(tf, fi, "\\\\DE", i, nr); i<-i+1; { "descendingnode"}
draw.vf.cell(tf, fi, "\\\\s-", i, nr); i<-i+1; { "s1"}
draw.vf.cell(tf, fi, "\\\\dg", i, nr); i<-i+1; { "dagger"}
draw.vf.cell(tf, fi, "\\\\dd", i, nr); i<-i+1; { "daggerdbl"}
draw.vf.cell(tf, fi, "\\\\li", i, nr); i<-i+1; { "line integral"}
draw.vf.cell(tf, fi, "\\\\-+", i, nr); i<-i+1; { "minusplus"}
draw.vf.cell(tf, fi, "\\\\||", i, nr); i<-i+1; { "parallel"}
draw.vf.cell(tf, fi, "\\\\rn", i, nr); i<-i+1; { "overscore"}
draw.vf.cell(tf, fi, "\\\\ul", i, nr); i<-i+1; { "underscore"}

nr <- 25
nc <- 3
make.table(nr, nc)
code <- c(300:307,310:317,320:327,330:337,340:347,350:357,360:367,370:377,
          243,263)
string <- c(
"\\300","\\301","\\302","\\303","\\304","\\305","\\306","\\307",
"\\310","\\311","\\312","\\313","\\314","\\315",
"\\316","\\317","\\320","\\321","\\322","\\323",
"\\324","\\325","\\326","\\327","\\330","\\331",
"\\332","\\333","\\334","\\335","\\336","\\337",
"\\340","\\341","\\342","\\343","\\344","\\345","\\346","\\347",
"\\350","\\351","\\352","\\353","\\354","\\355",
"\\356","\\357","\\360","\\361","\\362","\\363",
"\\364","\\365","\\366","\\367","\\370","\\371",
"\\372","\\373","\\374","\\375","\\376","\\377","\\243","\\263")
draw.title("Cyrillic Octal Codes", i = 0, nr ,nc)
for (i in 1:66)
    draw.vf.cell(tf, "cyrillic", string[i], i-1, nr,
                 raw.string=paste("\\\\", as.character(code[i]), sep=""))

nr <- 25
nc <- 3
make.table(nr, nc)
code <- c(252,254,256,262:269,275,278:281,284,745,746,750:768,796:802,
          804:807,809,814:828,830:834,840:844)
draw.title("Raw Hershey Escape Sequences", i=0, nr, nc)
for (i in 1:75)
    draw.vf.cell(tf, fi, paste("\\\\#H",formatC(code[i],wid=4,flag=0),sep=""),
                 i-1, nr)
make.table(nr, nc)
code <- c(845:847,850:856,860:874,899:909,2296:2299,2318:2332,2367:2382,
          4014,4109)
draw.title("More Raw Hershey Escape Sequences", i=0, nr, nc)
for (i in 1:73)
    draw.vf.cell(tf, fi, paste("\\\\#H",formatC(code[i],wid=4,flag=0),sep=""),
                 i-1, nr)

par(oldpar)
}
\keyword{aplot}
\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}}.
}
\examples{
Ceps <- .Machine$double.eps # ``Computer epsilon''
x <- seq(-3, 3, len=200)
stopifnot(
 abs(cosh(x) - (exp(x) + exp(-x))/2) < 20*Ceps,
 abs(sinh(x) - (exp(x) - exp(-x))/2) < 20*Ceps,
 Mod(cosh(x) - cos(1i*x))	< 20*Ceps,
 Mod(sinh(x) - sin(1i*x)/1i) 	< 20*Ceps,
 abs(tanh(x)*cosh(x) - sinh(x)) < 20*Ceps
)

## Inverse:
all(abs(asinh(sinh(x)) - x) < 10*Ceps)
x[abs(acosh(cosh(x)) - abs(x)) > 100*Ceps] #- imprecise for small x
all(abs(atanh(tanh(x)) - x) < 100*Ceps)

all(abs(asinh(x) - log(x + sqrt(x^2 + 1))) < 10*Ceps)
cx <- cosh(x)
all(abs(acosh(cx) - log(cx + sqrt(cx^2 - 1))) < 1000*Ceps)
}
\keyword{math}
\name{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}
\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}

\name{InsectSprays}
\title{Effectiveness of Insect Sprays}
\usage{data(InsectSprays)}
\alias{InsectSprays}
\description{
  The counts of insects in agricultural experimental units treated with
  different insecticides.
}
\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}
\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}
\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.

  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{example(Japanese)} shows tables of the escape
  sequences for the available Japanese characters.
}
\seealso{
  \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")

######
# create tables of Japanese characters
######
make.table <- function(nr, nc) {
    opar <- par(mar=rep(0, 4), pty="s")
    plot(c(0, nc*(10\%/\%nc) + 1), c(0, -(nr + 1)),
         type="n", xlab="", ylab="", axes=FALSE)
    invisible(opar)
}

get.r <- function(i, nr)   i \%\% nr + 1
get.c <- function(i, nr)   i \%/\% nr + 1
Esc2 <- function(str)	   paste("\\\\", str, sep="")

draw.title <- function(title, nc)
    text((nc*(10\%/\%nc) + 1)/2, 0, title, font=2)

draw.vf.cell <- function(typeface, fontindex, string, i, nr, raw.string=NULL) {
    r <- get.r(i, nr)
    c <- get.c(i, nr)
    x0 <- 2*(c - 1)
    if (is.null(raw.string)) raw.string <- Esc2(string)
    text(x0 + 1.1, -r, raw.string, col="grey")
    text(x0 + 2,   -r, string, vfont=c(typeface, fontindex))
    rect(x0 +  .5, -(r - .5), x0 + 2.5, -(r + .5), border="grey")
}

draw.vf.cell2 <- function(string, alt, i, nr) {
    r <- get.r(i, nr)
    c <- get.c(i, nr)
    x0 <- 3*(c - 1)
    text(x0 + 1.1, -r, Esc2(string <- Esc2(string)), col="grey")
    text(x0 + 2.2, -r, Esc2(Esc2(alt)), col="grey", cex=.6)
    text(x0 + 3,   -r, string, vfont=c("serif", "plain"))
    rect(x0 +  .5, -(r - .5), x0 + 3.5, -(r + .5), border="grey")
}

tf <- "serif"
fi <- "plain"
nr <- 25
nc <- 4
oldpar <- make.table(nr, nc)
index <- 0
digits <- c(0:9,"a","b","c","d","e","f")
% "\" : double once for Rd, once for R.
draw.title("Hiragana : \\\\\\\\#J24nn", nc)
for (i in 2:7) {
    for (j in 1:16) {
	if (!((i == 2 && j == 1) || (i == 7 && j > 4))) {
	    draw.vf.cell(tf, fi, paste("\\\\#J24", i, digits[j], sep=""),
	                 index, nr)
            index <- index + 1
	}
    }
}

nr <- 25
nc <- 4
make.table(nr, nc)
index <- 0
digits <- c(0:9,"a","b","c","d","e","f")
draw.title("Katakana : \\\\\\\\#J25nn", nc)
for (i in 2:7) {
    for (j in 1:16) {
	if (!((i == 2 && j == 1) || (i == 7 && j > 7))) {
	    draw.vf.cell(tf, fi, paste("\\\\#J25", i, digits[j], sep=""),
	                 index, nr)
            index <- index + 1
	}
    }
}

nr <- 26
nc <- 3
make.table(nr, nc)
i <- 0
draw.title("Kanji (1)", nc)
draw.vf.cell2("#J3021", "#N0043", i, nr); i <- i + 1
draw.vf.cell2("#J3026", "#N2829", i, nr); i <- i + 1
draw.vf.cell2("#J302d", "#N0062", i, nr); i <- i + 1
draw.vf.cell2("#J3035", "#N0818", i, nr); i <- i + 1
draw.vf.cell2("#J303f", "#N1802", i, nr); i <- i + 1
draw.vf.cell2("#J3045", "#N2154", i, nr); i <- i + 1
draw.vf.cell2("#J304c", "#N0401", i, nr); i <- i + 1
draw.vf.cell2("#J3057", "#N2107", i, nr); i <- i + 1
draw.vf.cell2("#J3059", "#N0138", i, nr); i <- i + 1
draw.vf.cell2("#J305b", "#N3008", i, nr); i <- i + 1
draw.vf.cell2("#J305e", "#N3579", i, nr); i <- i + 1
draw.vf.cell2("#J3061", "#N4214", i, nr); i <- i + 1
draw.vf.cell2("#J306c", "#N0001", i, nr); i <- i + 1
draw.vf.cell2("#J3070", "#N3294", i, nr); i <- i + 1
draw.vf.cell2("#J3078", "#N1026", i, nr); i <- i + 1
draw.vf.cell2("#J307a", "#N1562", i, nr); i <- i + 1
draw.vf.cell2("#J3122", "#N5006", i, nr); i <- i + 1
draw.vf.cell2("#J3126", "#N0878", i, nr); i <- i + 1
draw.vf.cell2("#J3127", "#N1280", i, nr); i <- i + 1
draw.vf.cell2("#J3129", "#N3673", i, nr); i <- i + 1
draw.vf.cell2("#J312b", "#N5042", i, nr); i <- i + 1
draw.vf.cell2("#J3132", "#N2629", i, nr); i <- i + 1
draw.vf.cell2("#J313b", "#N2973", i, nr); i <- i + 1
draw.vf.cell2("#J313f", "#N4725", i, nr); i <- i + 1
draw.vf.cell2("#J3140", "#N5046", i, nr); i <- i + 1
draw.vf.cell2("#J314a", "#N0130", i, nr); i <- i + 1
draw.vf.cell2("#J3155", "#N2599", i, nr); i <- i + 1
draw.vf.cell2("#J315f", "#N0617", i, nr); i <- i + 1
draw.vf.cell2("#J3173", "#N4733", i, nr); i <- i + 1
draw.vf.cell2("#J3176", "#N1125", i, nr); i <- i + 1
draw.vf.cell2("#J3177", "#N2083", i, nr); i <- i + 1
draw.vf.cell2("#J317e", "#N1504", i, nr); i <- i + 1
draw.vf.cell2("#J3221", "#N1885", i, nr); i <- i + 1
draw.vf.cell2("#J3223", "#N2361", i, nr); i <- i + 1
draw.vf.cell2("#J3226", "#N2922", i, nr); i <- i + 1
draw.vf.cell2("#J322b", "#N5399", i, nr); i <- i + 1
draw.vf.cell2("#J322f", "#N0551", i, nr); i <- i + 1
draw.vf.cell2("#J3235", "#N0260", i, nr); i <- i + 1
draw.vf.cell2("#J3239", "#N2634", i, nr); i <- i + 1
draw.vf.cell2("#J323b", "#N5110", i, nr); i <- i + 1
draw.vf.cell2("#J323c", "#N0009", i, nr); i <- i + 1
draw.vf.cell2("#J323d", "#N0350", i, nr); i <- i + 1
draw.vf.cell2("#J323f", "#N0409", i, nr); i <- i + 1
draw.vf.cell2("#J3241", "#N0422", i, nr); i <- i + 1
draw.vf.cell2("#J3243", "#N0716", i, nr); i <- i + 1
draw.vf.cell2("#J3244", "#N0024", i, nr); i <- i + 1
draw.vf.cell2("#J3246", "#N0058", i, nr); i <- i + 1
draw.vf.cell2("#J3248", "#N1311", i, nr); i <- i + 1
draw.vf.cell2("#J324a", "#N3272", i, nr); i <- i + 1
draw.vf.cell2("#J324c", "#N0107", i, nr); i <- i + 1
draw.vf.cell2("#J324f", "#N2530", i, nr); i <- i + 1
draw.vf.cell2("#J3250", "#N2743", i, nr); i <- i + 1
draw.vf.cell2("#J3256", "#N3909", i, nr); i <- i + 1
draw.vf.cell2("#J3259", "#N3956", i, nr); i <- i + 1
draw.vf.cell2("#J3261", "#N4723", i, nr); i <- i + 1
draw.vf.cell2("#J3267", "#N2848", i, nr); i <- i + 1
draw.vf.cell2("#J3268", "#N0050", i, nr); i <- i + 1
draw.vf.cell2("#J3272", "#N4306", i, nr); i <- i + 1
draw.vf.cell2("#J3273", "#N1028", i, nr); i <- i + 1
draw.vf.cell2("#J3323", "#N2264", i, nr); i <- i + 1
draw.vf.cell2("#J3324", "#N2553", i, nr); i <- i + 1
draw.vf.cell2("#J3326", "#N2998", i, nr); i <- i + 1
draw.vf.cell2("#J3328", "#N3537", i, nr); i <- i + 1
draw.vf.cell2("#J332b", "#N4950", i, nr); i <- i + 1
draw.vf.cell2("#J332d", "#N4486", i, nr); i <- i + 1
draw.vf.cell2("#J3330", "#N1168", i, nr); i <- i + 1
draw.vf.cell2("#J3346", "#N1163", i, nr); i <- i + 1
draw.vf.cell2("#J334b", "#N2254", i, nr); i <- i + 1
draw.vf.cell2("#J3351", "#N4301", i, nr); i <- i + 1
draw.vf.cell2("#J3353", "#N4623", i, nr); i <- i + 1
draw.vf.cell2("#J3357", "#N5088", i, nr); i <- i + 1
draw.vf.cell2("#J3358", "#N1271", i, nr); i <- i + 1
draw.vf.cell2("#J335a", "#N2324", i, nr); i <- i + 1
draw.vf.cell2("#J3364", "#N0703", i, nr); i <- i + 1
draw.vf.cell2("#J3424", "#N2977", i, nr); i <- i + 1
draw.vf.cell2("#J3428", "#N1322", i, nr); i <- i + 1

make.table(nr, nc)
i <- 0
draw.title("Kanji (2)", nc)
draw.vf.cell2("#J342c", "#N1466", i, nr); i <- i + 1
draw.vf.cell2("#J3433", "#N1492", i, nr); i <- i + 1
draw.vf.cell2("#J3434", "#N0790", i, nr); i <- i + 1
draw.vf.cell2("#J3436", "#N1731", i, nr); i <- i + 1
draw.vf.cell2("#J3437", "#N1756", i, nr); i <- i + 1
draw.vf.cell2("#J3445", "#N2988", i, nr); i <- i + 1
draw.vf.cell2("#J3449", "#N3416", i, nr); i <- i + 1
draw.vf.cell2("#J3454", "#N4750", i, nr); i <- i + 1
draw.vf.cell2("#J3456", "#N4949", i, nr); i <- i + 1
draw.vf.cell2("#J3458", "#N4958", i, nr); i <- i + 1
draw.vf.cell2("#J346f", "#N0994", i, nr); i <- i + 1
draw.vf.cell2("#J3470", "#N1098", i, nr); i <- i + 1
draw.vf.cell2("#J3476", "#N1496", i, nr); i <- i + 1
draw.vf.cell2("#J347c", "#N3785", i, nr); i <- i + 1
draw.vf.cell2("#J3521", "#N2379", i, nr); i <- i + 1
draw.vf.cell2("#J3522", "#N1582", i, nr); i <- i + 1
draw.vf.cell2("#J3524", "#N2480", i, nr); i <- i + 1
draw.vf.cell2("#J3525", "#N2507", i, nr); i <- i + 1
draw.vf.cell2("#J352d", "#N4318", i, nr); i <- i + 1
draw.vf.cell2("#J3530", "#N4610", i, nr); i <- i + 1
draw.vf.cell2("#J3534", "#N5276", i, nr); i <- i + 1
draw.vf.cell2("#J3535", "#N5445", i, nr); i <- i + 1
draw.vf.cell2("#J3546", "#N3981", i, nr); i <- i + 1
draw.vf.cell2("#J3555", "#N4685", i, nr); i <- i + 1
draw.vf.cell2("#J355a", "#N0154", i, nr); i <- i + 1
draw.vf.cell2("#J355b", "#N0885", i, nr); i <- i + 1
draw.vf.cell2("#J355d", "#N1560", i, nr); i <- i + 1
draw.vf.cell2("#J3565", "#N2941", i, nr); i <- i + 1
draw.vf.cell2("#J3566", "#N3314", i, nr); i <- i + 1
draw.vf.cell2("#J3569", "#N3496", i, nr); i <- i + 1
draw.vf.cell2("#J356d", "#N2852", i, nr); i <- i + 1
draw.vf.cell2("#J356e", "#N1051", i, nr); i <- i + 1
draw.vf.cell2("#J356f", "#N1387", i, nr); i <- i + 1
draw.vf.cell2("#J3575", "#N4109", i, nr); i <- i + 1
draw.vf.cell2("#J3577", "#N4548", i, nr); i <- i + 1
draw.vf.cell2("#J357b", "#N5281", i, nr); i <- i + 1
draw.vf.cell2("#J357e", "#N0295", i, nr); i <- i + 1
draw.vf.cell2("#J3621", "#N0431", i, nr); i <- i + 1
draw.vf.cell2("#J3626", "#N0581", i, nr); i <- i + 1
draw.vf.cell2("#J362d", "#N1135", i, nr); i <- i + 1
draw.vf.cell2("#J362f", "#N1571", i, nr); i <- i + 1
draw.vf.cell2("#J3635", "#N2052", i, nr); i <- i + 1
draw.vf.cell2("#J3636", "#N2378", i, nr); i <- i + 1
draw.vf.cell2("#J364a", "#N0103", i, nr); i <- i + 1
draw.vf.cell2("#J364b", "#N2305", i, nr); i <- i + 1
draw.vf.cell2("#J364c", "#N2923", i, nr); i <- i + 1
draw.vf.cell2("#J3651", "#N1065", i, nr); i <- i + 1
draw.vf.cell2("#J3661", "#N4671", i, nr); i <- i + 1
draw.vf.cell2("#J3662", "#N4815", i, nr); i <- i + 1
draw.vf.cell2("#J3664", "#N4855", i, nr); i <- i + 1
draw.vf.cell2("#J3665", "#N0146", i, nr); i <- i + 1
draw.vf.cell2("#J3671", "#N3128", i, nr); i <- i + 1
draw.vf.cell2("#J3675", "#N3317", i, nr); i <- i + 1
draw.vf.cell2("#J367e", "#N1386", i, nr); i <- i + 1
draw.vf.cell2("#J3738", "#N0449", i, nr); i <- i + 1
draw.vf.cell2("#J3739", "#N0534", i, nr); i <- i + 1
draw.vf.cell2("#J373e", "#N2937", i, nr); i <- i + 1
draw.vf.cell2("#J373f", "#N1077", i, nr); i <- i + 1
draw.vf.cell2("#J3741", "#N1589", i, nr); i <- i + 1
draw.vf.cell2("#J3742", "#N1602", i, nr); i <- i + 1
draw.vf.cell2("#J374f", "#N0195", i, nr); i <- i + 1
draw.vf.cell2("#J3750", "#N3523", i, nr); i <- i + 1
draw.vf.cell2("#J3757", "#N4312", i, nr); i <- i + 1
draw.vf.cell2("#J375a", "#N4620", i, nr); i <- i + 1
draw.vf.cell2("#J3767", "#N2412", i, nr); i <- i + 1
draw.vf.cell2("#J3768", "#N2509", i, nr); i <- i + 1
draw.vf.cell2("#J376a", "#N3313", i, nr); i <- i + 1
draw.vf.cell2("#J376b", "#N3540", i, nr); i <- i + 1
draw.vf.cell2("#J376c", "#N4205", i, nr); i <- i + 1
draw.vf.cell2("#J376e", "#N2169", i, nr); i <- i + 1
draw.vf.cell2("#J3777", "#N1045", i, nr); i <- i + 1
draw.vf.cell2("#J3824", "#N2868", i, nr); i <- i + 1
draw.vf.cell2("#J3826", "#N3180", i, nr); i <- i + 1
draw.vf.cell2("#J3828", "#N3543", i, nr); i <- i + 1
draw.vf.cell2("#J382b", "#N4284", i, nr); i <- i + 1
draw.vf.cell2("#J3833", "#N5220", i, nr); i <- i + 1

make.table(nr, nc)
i <- 0
draw.title("Kanji (3)", nc)
draw.vf.cell2("#J3835", "#N0275", i, nr); i <- i + 1
draw.vf.cell2("#J3836", "#N0825", i, nr); i <- i + 1
draw.vf.cell2("#J3839", "#N1568", i, nr); i <- i + 1
draw.vf.cell2("#J383a", "#N2637", i, nr); i <- i + 1
draw.vf.cell2("#J383b", "#N2656", i, nr); i <- i + 1
draw.vf.cell2("#J383d", "#N2943", i, nr); i <- i + 1
draw.vf.cell2("#J3840", "#N4309", i, nr); i <- i + 1
draw.vf.cell2("#J3842", "#N4987", i, nr); i <- i + 1
draw.vf.cell2("#J3845", "#N0770", i, nr); i <- i + 1
draw.vf.cell2("#J3847", "#N1036", i, nr); i <- i + 1
draw.vf.cell2("#J384c", "#N1567", i, nr); i <- i + 1
draw.vf.cell2("#J384d", "#N1817", i, nr); i <- i + 1
draw.vf.cell2("#J384e", "#N2044", i, nr); i <- i + 1
draw.vf.cell2("#J385d", "#N5415", i, nr); i <- i + 1
draw.vf.cell2("#J385e", "#N0015", i, nr); i <- i + 1
draw.vf.cell2("#J3861", "#N0162", i, nr); i <- i + 1
draw.vf.cell2("#J3865", "#N1610", i, nr); i <- i + 1
draw.vf.cell2("#J3866", "#N1628", i, nr); i <- i + 1
draw.vf.cell2("#J386c", "#N4374", i, nr); i <- i + 1
draw.vf.cell2("#J3872", "#N0290", i, nr); i <- i + 1
draw.vf.cell2("#J3877", "#N1358", i, nr); i <- i + 1
draw.vf.cell2("#J3878", "#N0579", i, nr); i <- i + 1
draw.vf.cell2("#J387d", "#N0868", i, nr); i <- i + 1
draw.vf.cell2("#J387e", "#N0101", i, nr); i <- i + 1
draw.vf.cell2("#J3929", "#N1451", i, nr); i <- i + 1
draw.vf.cell2("#J3931", "#N1683", i, nr); i <- i + 1
draw.vf.cell2("#J393d", "#N2343", i, nr); i <- i + 1
draw.vf.cell2("#J3943", "#N0092", i, nr); i <- i + 1
draw.vf.cell2("#J394d", "#N3684", i, nr); i <- i + 1
draw.vf.cell2("#J3954", "#N4213", i, nr); i <- i + 1
draw.vf.cell2("#J3955", "#N1641", i, nr); i <- i + 1
draw.vf.cell2("#J395b", "#N4843", i, nr); i <- i + 1
draw.vf.cell2("#J395d", "#N4883", i, nr); i <- i + 1
draw.vf.cell2("#J395f", "#N4994", i, nr); i <- i + 1
draw.vf.cell2("#J3960", "#N1459", i, nr); i <- i + 1
draw.vf.cell2("#J3961", "#N5188", i, nr); i <- i + 1
draw.vf.cell2("#J3962", "#N5248", i, nr); i <- i + 1
draw.vf.cell2("#J3966", "#N0882", i, nr); i <- i + 1
draw.vf.cell2("#J3967", "#N0383", i, nr); i <- i + 1
draw.vf.cell2("#J3971", "#N1037", i, nr); i <- i + 1
draw.vf.cell2("#J3975", "#N5403", i, nr); i <- i + 1
draw.vf.cell2("#J397c", "#N5236", i, nr); i <- i + 1
draw.vf.cell2("#J397e", "#N4660", i, nr); i <- i + 1
draw.vf.cell2("#J3a21", "#N2430", i, nr); i <- i + 1
draw.vf.cell2("#J3a23", "#N0352", i, nr); i <- i + 1
draw.vf.cell2("#J3a2c", "#N2261", i, nr); i <- i + 1
draw.vf.cell2("#J3a38", "#N1455", i, nr); i <- i + 1
draw.vf.cell2("#J3a39", "#N3662", i, nr); i <- i + 1
draw.vf.cell2("#J3a42", "#N1515", i, nr); i <- i + 1
draw.vf.cell2("#J3a46", "#N0035", i, nr); i <- i + 1
draw.vf.cell2("#J3a47", "#N2146", i, nr); i <- i + 1
draw.vf.cell2("#J3a59", "#N3522", i, nr); i <- i + 1
draw.vf.cell2("#J3a5f", "#N1055", i, nr); i <- i + 1
draw.vf.cell2("#J3a6e", "#N0407", i, nr); i <- i + 1
draw.vf.cell2("#J3a72", "#N2119", i, nr); i <- i + 1
draw.vf.cell2("#J3a79", "#N2256", i, nr); i <- i + 1
draw.vf.cell2("#J3b2e", "#N3113", i, nr); i <- i + 1
draw.vf.cell2("#J3b30", "#N0008", i, nr); i <- i + 1
draw.vf.cell2("#J3b33", "#N1407", i, nr); i <- i + 1
draw.vf.cell2("#J3b36", "#N2056", i, nr); i <- i + 1
draw.vf.cell2("#J3b3b", "#N3415", i, nr); i <- i + 1
draw.vf.cell2("#J3b40", "#N4789", i, nr); i <- i + 1
draw.vf.cell2("#J3b45", "#N0362", i, nr); i <- i + 1
draw.vf.cell2("#J3b4d", "#N1025", i, nr); i <- i + 1
draw.vf.cell2("#J3b4e", "#N1160", i, nr); i <- i + 1
draw.vf.cell2("#J3b4f", "#N1208", i, nr); i <- i + 1
draw.vf.cell2("#J3b52", "#N1264", i, nr); i <- i + 1
draw.vf.cell2("#J3b54", "#N0284", i, nr); i <- i + 1
draw.vf.cell2("#J3b57", "#N3001", i, nr); i <- i + 1
draw.vf.cell2("#J3b58", "#N1904", i, nr); i <- i + 1
draw.vf.cell2("#J3b59", "#N2039", i, nr); i <- i + 1
draw.vf.cell2("#J3b5e", "#N2211", i, nr); i <- i + 1
draw.vf.cell2("#J3b5f", "#N2429", i, nr); i <- i + 1
draw.vf.cell2("#J3b60", "#N2439", i, nr); i <- i + 1
draw.vf.cell2("#J3b61", "#N2478", i, nr); i <- i + 1
draw.vf.cell2("#J3b64", "#N3265", i, nr); i <- i + 1

make.table(nr, nc)
i <- 0
draw.title("Kanji (4)", nc)
draw.vf.cell2("#J3b65", "#N3492", i, nr); i <- i + 1
draw.vf.cell2("#J3b66", "#N3510", i, nr); i <- i + 1
draw.vf.cell2("#J3b6a", "#N3845", i, nr); i <- i + 1
draw.vf.cell2("#J3b73", "#N2435", i, nr); i <- i + 1
draw.vf.cell2("#J3b75", "#N5428", i, nr); i <- i + 1
draw.vf.cell2("#J3b76", "#N0272", i, nr); i <- i + 1
draw.vf.cell2("#J3b7a", "#N1281", i, nr); i <- i + 1
draw.vf.cell2("#J3b7d", "#N1903", i, nr); i <- i + 1
draw.vf.cell2("#J3b7e", "#N2126", i, nr); i <- i + 1
draw.vf.cell2("#J3c21", "#N0638", i, nr); i <- i + 1
draw.vf.cell2("#J3c27", "#N3209", i, nr); i <- i + 1
draw.vf.cell2("#J3c28", "#N3228", i, nr); i <- i + 1
draw.vf.cell2("#J3c2a", "#N3697", i, nr); i <- i + 1
draw.vf.cell2("#J3c2b", "#N3841", i, nr); i <- i + 1
draw.vf.cell2("#J3c2d", "#N3860", i, nr); i <- i + 1
draw.vf.cell2("#J3c2f", "#N5375", i, nr); i <- i + 1
draw.vf.cell2("#J3c30", "#N1556", i, nr); i <- i + 1
draw.vf.cell2("#J3c34", "#N4619", i, nr); i <- i + 1
draw.vf.cell2("#J3c37", "#N0261", i, nr); i <- i + 1
draw.vf.cell2("#J3c3c", "#N1300", i, nr); i <- i + 1
draw.vf.cell2("#J3c3e", "#N2631", i, nr); i <- i + 1
draw.vf.cell2("#J3c41", "#N4518", i, nr); i <- i + 1
draw.vf.cell2("#J3c42", "#N1297", i, nr); i <- i + 1
draw.vf.cell2("#J3c4d", "#N4603", i, nr); i <- i + 1
draw.vf.cell2("#J3c50", "#N2074", i, nr); i <- i + 1
draw.vf.cell2("#J3c54", "#N3685", i, nr); i <- i + 1
draw.vf.cell2("#J3c56", "#N4608", i, nr); i <- i + 1
draw.vf.cell2("#J3c5c", "#N1377", i, nr); i <- i + 1
draw.vf.cell2("#J3c61", "#N4809", i, nr); i <- i + 1
draw.vf.cell2("#J3c63", "#N3926", i, nr); i <- i + 1
draw.vf.cell2("#J3c67", "#N0285", i, nr); i <- i + 1
draw.vf.cell2("#J3c68", "#N3699", i, nr); i <- i + 1
draw.vf.cell2("#J3c6a", "#N1827", i, nr); i <- i + 1
draw.vf.cell2("#J3c6f", "#N3295", i, nr); i <- i + 1
draw.vf.cell2("#J3c72", "#N2573", i, nr); i <- i + 1
draw.vf.cell2("#J3c73", "#N5186", i, nr); i <- i + 1
draw.vf.cell2("#J3c7e", "#N0622", i, nr); i <- i + 1
draw.vf.cell2("#J3d29", "#N3273", i, nr); i <- i + 1
draw.vf.cell2("#J3d2a", "#N3521", i, nr); i <- i + 1
draw.vf.cell2("#J3d2e", "#N3863", i, nr); i <- i + 1
draw.vf.cell2("#J3d39", "#N4798", i, nr); i <- i + 1
draw.vf.cell2("#J3d3d", "#N0768", i, nr); i <- i + 1
draw.vf.cell2("#J3d3e", "#N1613", i, nr); i <- i + 1
draw.vf.cell2("#J3d44", "#N3597", i, nr); i <- i + 1
draw.vf.cell2("#J3d45", "#N0224", i, nr); i <- i + 1
draw.vf.cell2("#J3d50", "#N0097", i, nr); i <- i + 1
draw.vf.cell2("#J3d51", "#N1621", i, nr); i <- i + 1
draw.vf.cell2("#J3d55", "#N2122", i, nr); i <- i + 1
draw.vf.cell2("#J3d60", "#N0791", i, nr); i <- i + 1
draw.vf.cell2("#J3d63", "#N3509", i, nr); i <- i + 1
draw.vf.cell2("#J3d68", "#N1162", i, nr); i <- i + 1
draw.vf.cell2("#J3d6b", "#N2138", i, nr); i <- i + 1
draw.vf.cell2("#J3d71", "#N3719", i, nr); i <- i + 1
draw.vf.cell2("#J3d77", "#N1185", i, nr); i <- i + 1
draw.vf.cell2("#J3d7c", "#N4993", i, nr); i <- i + 1
draw.vf.cell2("#J3e26", "#N0321", i, nr); i <- i + 1
draw.vf.cell2("#J3e2e", "#N1355", i, nr); i <- i + 1
draw.vf.cell2("#J3e2f", "#N0166", i, nr); i <- i + 1
draw.vf.cell2("#J3e3d", "#N2137", i, nr); i <- i + 1
draw.vf.cell2("#J3e3e", "#N2212", i, nr); i <- i + 1
draw.vf.cell2("#J3e46", "#N2772", i, nr); i <- i + 1
draw.vf.cell2("#J3e4b", "#N3192", i, nr); i <- i + 1
draw.vf.cell2("#J3e4e", "#N3280", i, nr); i <- i + 1
draw.vf.cell2("#J3e57", "#N1638", i, nr); i <- i + 1
draw.vf.cell2("#J3e5a", "#N4341", i, nr); i <- i + 1
draw.vf.cell2("#J3e5d", "#N4472", i, nr); i <- i + 1
draw.vf.cell2("#J3e65", "#N0798", i, nr); i <- i + 1
draw.vf.cell2("#J3e68", "#N0223", i, nr); i <- i + 1
draw.vf.cell2("#J3e6c", "#N1113", i, nr); i <- i + 1
draw.vf.cell2("#J3e6f", "#N1364", i, nr); i <- i + 1
draw.vf.cell2("#J3e75", "#N2839", i, nr); i <- i + 1
draw.vf.cell2("#J3e78", "#N4002", i, nr); i <- i + 1
draw.vf.cell2("#J3f22", "#N2303", i, nr); i <- i + 1
draw.vf.cell2("#J3f27", "#N3889", i, nr); i <- i + 1
draw.vf.cell2("#J3f29", "#N5154", i, nr); i <- i + 1
draw.vf.cell2("#J3f2d", "#N0403", i, nr); i <- i + 1

make.table(nr, nc)
i <- 0
draw.title("Kanji (5)", nc)
draw.vf.cell2("#J3f34", "#N1645", i, nr); i <- i + 1
draw.vf.cell2("#J3f36", "#N1920", i, nr); i <- i + 1
draw.vf.cell2("#J3f37", "#N2080", i, nr); i <- i + 1
draw.vf.cell2("#J3f39", "#N2301", i, nr); i <- i + 1
draw.vf.cell2("#J3f3f", "#N0783", i, nr); i <- i + 1
draw.vf.cell2("#J3f43", "#N3837", i, nr); i <- i + 1
draw.vf.cell2("#J3f48", "#N4601", i, nr); i <- i + 1
draw.vf.cell2("#J3f49", "#N4646", i, nr); i <- i + 1
draw.vf.cell2("#J3f4a", "#N4709", i, nr); i <- i + 1
draw.vf.cell2("#J3f4c", "#N5055", i, nr); i <- i + 1
draw.vf.cell2("#J3f4d", "#N0339", i, nr); i <- i + 1
draw.vf.cell2("#J3f5e", "#N1034", i, nr); i <- i + 1
draw.vf.cell2("#J3f62", "#N0211", i, nr); i <- i + 1
draw.vf.cell2("#J3f65", "#N2482", i, nr); i <- i + 1
draw.vf.cell2("#J3f69", "#N3676", i, nr); i <- i + 1
draw.vf.cell2("#J3f74", "#N2057", i, nr); i <- i + 1
draw.vf.cell2("#J402d", "#N1666", i, nr); i <- i + 1
draw.vf.cell2("#J402e", "#N1799", i, nr); i <- i + 1
draw.vf.cell2("#J4030", "#N2436", i, nr); i <- i + 1
draw.vf.cell2("#J4031", "#N2121", i, nr); i <- i + 1
draw.vf.cell2("#J4032", "#N2143", i, nr); i <- i + 1
draw.vf.cell2("#J4035", "#N0027", i, nr); i <- i + 1
draw.vf.cell2("#J4038", "#N2991", i, nr); i <- i + 1
draw.vf.cell2("#J403e", "#N4273", i, nr); i <- i + 1
draw.vf.cell2("#J4044", "#N5076", i, nr); i <- i + 1
draw.vf.cell2("#J4045", "#N5077", i, nr); i <- i + 1
draw.vf.cell2("#J404e", "#N2108", i, nr); i <- i + 1
draw.vf.cell2("#J404f", "#N2194", i, nr); i <- i + 1
draw.vf.cell2("#J4050", "#N3176", i, nr); i <- i + 1
draw.vf.cell2("#J4051", "#N3306", i, nr); i <- i + 1
draw.vf.cell2("#J4056", "#N4534", i, nr); i <- i + 1
draw.vf.cell2("#J405a", "#N0667", i, nr); i <- i + 1
draw.vf.cell2("#J405c", "#N1951", i, nr); i <- i + 1
draw.vf.cell2("#J405e", "#N1855", i, nr); i <- i + 1
draw.vf.cell2("#J4063", "#N5044", i, nr); i <- i + 1
draw.vf.cell2("#J4064", "#N3539", i, nr); i <- i + 1
draw.vf.cell2("#J4065", "#N3855", i, nr); i <- i + 1
draw.vf.cell2("#J4068", "#N0571", i, nr); i <- i + 1
draw.vf.cell2("#J4069", "#N0156", i, nr); i <- i + 1
draw.vf.cell2("#J406e", "#N1447", i, nr); i <- i + 1
draw.vf.cell2("#J4070", "#N1823", i, nr); i <- i + 1
draw.vf.cell2("#J407e", "#N3580", i, nr); i <- i + 1
draw.vf.cell2("#J4125", "#N3873", i, nr); i <- i + 1
draw.vf.cell2("#J4130", "#N0595", i, nr); i <- i + 1
draw.vf.cell2("#J4133", "#N2770", i, nr); i <- i + 1
draw.vf.cell2("#J4134", "#N0384", i, nr); i <- i + 1
draw.vf.cell2("#J4147", "#N3511", i, nr); i <- i + 1
draw.vf.cell2("#J4148", "#N3520", i, nr); i <- i + 1
draw.vf.cell2("#J4150", "#N0859", i, nr); i <- i + 1
draw.vf.cell2("#J4158", "#N1402", i, nr); i <- i + 1
draw.vf.cell2("#J415b", "#N1728", i, nr); i <- i + 1
draw.vf.cell2("#J4161", "#N2100", i, nr); i <- i + 1
draw.vf.cell2("#J416a", "#N2241", i, nr); i <- i + 1
draw.vf.cell2("#J416d", "#N3567", i, nr); i <- i + 1
draw.vf.cell2("#J4170", "#N3939", i, nr); i <- i + 1
draw.vf.cell2("#J4175", "#N4234", i, nr); i <- i + 1
draw.vf.cell2("#J4176", "#N4539", i, nr); i <- i + 1
draw.vf.cell2("#J417c", "#N0540", i, nr); i <- i + 1
draw.vf.cell2("#J417d", "#N1137", i, nr); i <- i + 1
draw.vf.cell2("#J4224", "#N4701", i, nr); i <- i + 1
draw.vf.cell2("#J4226", "#N0509", i, nr); i <- i + 1
draw.vf.cell2("#J422b", "#N0196", i, nr); i <- i + 1
draw.vf.cell2("#J422c", "#N2632", i, nr); i <- i + 1
draw.vf.cell2("#J422d", "#N4546", i, nr); i <- i + 1
draw.vf.cell2("#J422e", "#N4700", i, nr); i <- i + 1
draw.vf.cell2("#J4233", "#N3544", i, nr); i <- i + 1
draw.vf.cell2("#J4236", "#N0590", i, nr); i <- i + 1
draw.vf.cell2("#J4238", "#N1267", i, nr); i <- i + 1
draw.vf.cell2("#J423e", "#N0361", i, nr); i <- i + 1
draw.vf.cell2("#J423f", "#N1169", i, nr); i <- i + 1
draw.vf.cell2("#J4240", "#N1172", i, nr); i <- i + 1
draw.vf.cell2("#J424a", "#N2313", i, nr); i <- i + 1
draw.vf.cell2("#J424e", "#N0405", i, nr); i <- i + 1
draw.vf.cell2("#J4250", "#N2067", i, nr); i <- i + 1
draw.vf.cell2("#J4256", "#N1743", i, nr); i <- i + 1
draw.vf.cell2("#J4265", "#N0364", i, nr); i <- i + 1

make.table(nr, nc)
i <- 0
draw.title("Kanji (6)", nc)
draw.vf.cell2("#J4267", "#N1171", i, nr); i <- i + 1
draw.vf.cell2("#J4268", "#N3385", i, nr); i <- i + 1
draw.vf.cell2("#J426a", "#N2164", i, nr); i <- i + 1
draw.vf.cell2("#J426c", "#N2655", i, nr); i <- i + 1
draw.vf.cell2("#J4274", "#N2503", i, nr); i <- i + 1
draw.vf.cell2("#J4323", "#N4721", i, nr); i <- i + 1
draw.vf.cell2("#J432b", "#N4458", i, nr); i <- i + 1
draw.vf.cell2("#J432f", "#N4384", i, nr); i <- i + 1
draw.vf.cell2("#J4331", "#N0139", i, nr); i <- i + 1
draw.vf.cell2("#J433a", "#N1418", i, nr); i <- i + 1
draw.vf.cell2("#J433b", "#N3172", i, nr); i <- i + 1
draw.vf.cell2("#J4346", "#N1575", i, nr); i <- i + 1
draw.vf.cell2("#J434b", "#N2996", i, nr); i <- i + 1
draw.vf.cell2("#J434d", "#N0488", i, nr); i <- i + 1
draw.vf.cell2("#J434e", "#N3169", i, nr); i <- i + 1
draw.vf.cell2("#J434f", "#N1056", i, nr); i <- i + 1
draw.vf.cell2("#J4356", "#N3644", i, nr); i <- i + 1
draw.vf.cell2("#J4359", "#N4722", i, nr); i <- i + 1
draw.vf.cell2("#J435d", "#N3366", i, nr); i <- i + 1
draw.vf.cell2("#J4362", "#N3325", i, nr); i <- i + 1
draw.vf.cell2("#J4363", "#N3940", i, nr); i <- i + 1
draw.vf.cell2("#J4365", "#N3665", i, nr); i <- i + 1
draw.vf.cell2("#J4366", "#N0081", i, nr); i <- i + 1
draw.vf.cell2("#J4368", "#N1291", i, nr); i <- i + 1
draw.vf.cell2("#J436b", "#N0053", i, nr); i <- i + 1
draw.vf.cell2("#J436c", "#N2236", i, nr); i <- i + 1
draw.vf.cell2("#J436e", "#N4115", i, nr); i <- i + 1
draw.vf.cell2("#J442b", "#N3788", i, nr); i <- i + 1
draw.vf.cell2("#J442c", "#N2702", i, nr); i <- i + 1
draw.vf.cell2("#J4436", "#N4543", i, nr); i <- i + 1
draw.vf.cell2("#J4439", "#N4938", i, nr); i <- i + 1
draw.vf.cell2("#J443b", "#N5340", i, nr); i <- i + 1
draw.vf.cell2("#J443e", "#N0775", i, nr); i <- i + 1
draw.vf.cell2("#J444c", "#N4703", i, nr); i <- i + 1
draw.vf.cell2("#J4463", "#N0406", i, nr); i <- i + 1
draw.vf.cell2("#J446a", "#N1296", i, nr); i <- i + 1
draw.vf.cell2("#J446c", "#N1508", i, nr); i <- i + 1
draw.vf.cell2("#J446d", "#N1514", i, nr); i <- i + 1
draw.vf.cell2("#J4472", "#N1914", i, nr); i <- i + 1
draw.vf.cell2("#J4478", "#N3285", i, nr); i <- i + 1
draw.vf.cell2("#J4479", "#N3581", i, nr); i <- i + 1
draw.vf.cell2("#J4526", "#N1987", i, nr); i <- i + 1
draw.vf.cell2("#J452a", "#N3097", i, nr); i <- i + 1
draw.vf.cell2("#J452f", "#N0931", i, nr); i <- i + 1
draw.vf.cell2("#J4534", "#N4844", i, nr); i <- i + 1
draw.vf.cell2("#J4535", "#N0588", i, nr); i <- i + 1
draw.vf.cell2("#J4537", "#N0016", i, nr); i <- i + 1
draw.vf.cell2("#J453e", "#N4615", i, nr); i <- i + 1
draw.vf.cell2("#J4540", "#N0804", i, nr); i <- i + 1
draw.vf.cell2("#J4544", "#N2994", i, nr); i <- i + 1
draw.vf.cell2("#J4545", "#N5050", i, nr); i <- i + 1
draw.vf.cell2("#J454c", "#N1614", i, nr); i <- i + 1
draw.vf.cell2("#J4559", "#N1511", i, nr); i <- i + 1
draw.vf.cell2("#J455a", "#N1050", i, nr); i <- i + 1
draw.vf.cell2("#J455f", "#N1161", i, nr); i <- i + 1
draw.vf.cell2("#J4561", "#N0665", i, nr); i <- i + 1
draw.vf.cell2("#J4563", "#N1109", i, nr); i <- i + 1
draw.vf.cell2("#J4567", "#N0230", i, nr); i <- i + 1
draw.vf.cell2("#J456c", "#N0213", i, nr); i <- i + 1
draw.vf.cell2("#J4574", "#N2745", i, nr); i <- i + 1
draw.vf.cell2("#J4576", "#N1359", i, nr); i <- i + 1
draw.vf.cell2("#J4579", "#N3396", i, nr); i <- i + 1
draw.vf.cell2("#J4626", "#N4465", i, nr); i <- i + 1
draw.vf.cell2("#J4630", "#N0730", i, nr); i <- i + 1
draw.vf.cell2("#J4631", "#N0619", i, nr); i <- i + 1
draw.vf.cell2("#J4633", "#N1354", i, nr); i <- i + 1
draw.vf.cell2("#J463b", "#N4724", i, nr); i <- i + 1
draw.vf.cell2("#J463c", "#N4853", i, nr); i <- i + 1
draw.vf.cell2("#J4643", "#N2860", i, nr); i <- i + 1
draw.vf.cell2("#J4649", "#N4375", i, nr); i <- i + 1
draw.vf.cell2("#J465e", "#N2160", i, nr); i <- i + 1
draw.vf.cell2("#J4662", "#N0082", i, nr); i <- i + 1
draw.vf.cell2("#J466e", "#N0778", i, nr); i <- i + 1
draw.vf.cell2("#J4671", "#N5038", i, nr); i <- i + 1
draw.vf.cell2("#J4673", "#N0273", i, nr); i <- i + 1
draw.vf.cell2("#J4679", "#N3724", i, nr); i <- i + 1

make.table(nr, nc)
i <- 0
draw.title("Kanji (7)", nc)
draw.vf.cell2("#J467c", "#N2097", i, nr); i <- i + 1
draw.vf.cell2("#J467e", "#N0574", i, nr); i <- i + 1
draw.vf.cell2("#J4721", "#N1189", i, nr); i <- i + 1
draw.vf.cell2("#J472e", "#N2797", i, nr); i <- i + 1
draw.vf.cell2("#J472f", "#N0188", i, nr); i <- i + 1
draw.vf.cell2("#J4733", "#N2808", i, nr); i <- i + 1
draw.vf.cell2("#J4734", "#N3472", i, nr); i <- i + 1
draw.vf.cell2("#J4748", "#N2529", i, nr); i <- i + 1
draw.vf.cell2("#J474f", "#N5191", i, nr); i <- i + 1
draw.vf.cell2("#J4769", "#N3275", i, nr); i <- i + 1
draw.vf.cell2("#J4772", "#N3095", i, nr); i <- i + 1
draw.vf.cell2("#J477e", "#N5385", i, nr); i <- i + 1
draw.vf.cell2("#J4821", "#N0049", i, nr); i <- i + 1
draw.vf.cell2("#J482c", "#N0577", i, nr); i <- i + 1
draw.vf.cell2("#J482f", "#N3092", i, nr); i <- i + 1
draw.vf.cell2("#J483e", "#N0132", i, nr); i <- i + 1
draw.vf.cell2("#J483f", "#N0817", i, nr); i <- i + 1
draw.vf.cell2("#J4841", "#N1469", i, nr); i <- i + 1
draw.vf.cell2("#J484c", "#N3865", i, nr); i <- i + 1
draw.vf.cell2("#J4856", "#N4811", i, nr); i <- i + 1
draw.vf.cell2("#J4860", "#N1604", i, nr); i <- i + 1
draw.vf.cell2("#J4866", "#N2470", i, nr); i <- i + 1
draw.vf.cell2("#J4869", "#N3109", i, nr); i <- i + 1
draw.vf.cell2("#J4873", "#N5080", i, nr); i <- i + 1
draw.vf.cell2("#J4874", "#N5152", i, nr); i <- i + 1
draw.vf.cell2("#J4878", "#N1383", i, nr); i <- i + 1
draw.vf.cell2("#J4879", "#N1631", i, nr); i <- i + 1
draw.vf.cell2("#J487e", "#N3658", i, nr); i <- i + 1
draw.vf.cell2("#J4921", "#N5421", i, nr); i <- i + 1
draw.vf.cell2("#J492e", "#N3397", i, nr); i <- i + 1
draw.vf.cell2("#J4934", "#N0033", i, nr); i <- i + 1
draw.vf.cell2("#J4938", "#N2359", i, nr); i <- i + 1
draw.vf.cell2("#J4939", "#N0131", i, nr); i <- i + 1
draw.vf.cell2("#J493d", "#N0108", i, nr); i <- i + 1
draw.vf.cell2("#J4942", "#N3042", i, nr); i <- i + 1
draw.vf.cell2("#J4943", "#N3271", i, nr); i <- i + 1
draw.vf.cell2("#J494a", "#N0923", i, nr); i <- i + 1
draw.vf.cell2("#J4954", "#N0017", i, nr); i <- i + 1
draw.vf.cell2("#J495b", "#N1468", i, nr); i <- i + 1
draw.vf.cell2("#J4963", "#N2832", i, nr); i <- i + 1
draw.vf.cell2("#J4969", "#N4488", i, nr); i <- i + 1
draw.vf.cell2("#J4977", "#N5148", i, nr); i <- i + 1
draw.vf.cell2("#J497d", "#N1484", i, nr); i <- i + 1
draw.vf.cell2("#J4a23", "#N4255", i, nr); i <- i + 1
draw.vf.cell2("#J4a26", "#N0173", i, nr); i <- i + 1
draw.vf.cell2("#J4a2a", "#N2857", i, nr); i <- i + 1
draw.vf.cell2("#J4a2c", "#N0578", i, nr); i <- i + 1
draw.vf.cell2("#J4a38", "#N2064", i, nr); i <- i + 1
draw.vf.cell2("#J4a39", "#N4959", i, nr); i <- i + 1
draw.vf.cell2("#J4a3f", "#N0026", i, nr); i <- i + 1
draw.vf.cell2("#J4a42", "#N0589", i, nr); i <- i + 1
draw.vf.cell2("#J4a44", "#N4945", i, nr); i <- i + 1
draw.vf.cell2("#J4a46", "#N3461", i, nr); i <- i + 1
draw.vf.cell2("#J4a50", "#N0511", i, nr); i <- i + 1
draw.vf.cell2("#J4a51", "#N0306", i, nr); i <- i + 1
draw.vf.cell2("#J4a52", "#N2842", i, nr); i <- i + 1
draw.vf.cell2("#J4a55", "#N4661", i, nr); i <- i + 1
draw.vf.cell2("#J4a6c", "#N2466", i, nr); i <- i + 1
draw.vf.cell2("#J4a7c", "#N2084", i, nr); i <- i + 1
draw.vf.cell2("#J4a7d", "#N2082", i, nr); i <- i + 1
draw.vf.cell2("#J4b21", "#N2535", i, nr); i <- i + 1
draw.vf.cell2("#J4b26", "#N3749", i, nr); i <- i + 1
draw.vf.cell2("#J4b4c", "#N0751", i, nr); i <- i + 1
draw.vf.cell2("#J4b4f", "#N5404", i, nr); i <- i + 1
draw.vf.cell2("#J4b5c", "#N0096", i, nr); i <- i + 1
draw.vf.cell2("#J4b63", "#N5390", i, nr); i <- i + 1
draw.vf.cell2("#J4b68", "#N2467", i, nr); i <- i + 1
draw.vf.cell2("#J4b74", "#N0855", i, nr); i <- i + 1
draw.vf.cell2("#J4b7c", "#N0007", i, nr); i <- i + 1
draw.vf.cell2("#J4c23", "#N0913", i, nr); i <- i + 1
draw.vf.cell2("#J4c24", "#N0179", i, nr); i <- i + 1
draw.vf.cell2("#J4c29", "#N1316", i, nr); i <- i + 1
draw.vf.cell2("#J4c35", "#N2773", i, nr); i <- i + 1
draw.vf.cell2("#J4c37", "#N3164", i, nr); i <- i + 1
draw.vf.cell2("#J4c3e", "#N1170", i, nr); i <- i + 1
draw.vf.cell2("#J4c40", "#N2110", i, nr); i <- i + 1

make.table(nr, nc)
i <- 0
draw.title("Kanji (8)", nc)
draw.vf.cell2("#J4c4c", "#N5087", i, nr); i <- i + 1
draw.vf.cell2("#J4c53", "#N2473", i, nr); i <- i + 1
draw.vf.cell2("#J4c5a", "#N2170", i, nr); i <- i + 1
draw.vf.cell2("#J4c5c", "#N3127", i, nr); i <- i + 1
draw.vf.cell2("#J4c64", "#N4944", i, nr); i <- i + 1
draw.vf.cell2("#J4c67", "#N4940", i, nr); i <- i + 1
draw.vf.cell2("#J4c6b", "#N0298", i, nr); i <- i + 1
draw.vf.cell2("#J4c70", "#N3168", i, nr); i <- i + 1
draw.vf.cell2("#J4c72", "#N1598", i, nr); i <- i + 1
draw.vf.cell2("#J4c74", "#N4074", i, nr); i <- i + 1
draw.vf.cell2("#J4c78", "#N2233", i, nr); i <- i + 1
draw.vf.cell2("#J4c7d", "#N2534", i, nr); i <- i + 1
draw.vf.cell2("#J4d2d", "#N3727", i, nr); i <- i + 1
draw.vf.cell2("#J4d30", "#N2565", i, nr); i <- i + 1
draw.vf.cell2("#J4d3a", "#N5030", i, nr); i <- i + 1
draw.vf.cell2("#J4d3c", "#N1167", i, nr); i <- i + 1
draw.vf.cell2("#J4d3e", "#N0408", i, nr); i <- i + 1
draw.vf.cell2("#J4d4f", "#N2659", i, nr); i <- i + 1
draw.vf.cell2("#J4d51", "#N2993", i, nr); i <- i + 1
draw.vf.cell2("#J4d53", "#N3656", i, nr); i <- i + 1
draw.vf.cell2("#J4d55", "#N4001", i, nr); i <- i + 1
draw.vf.cell2("#J4d57", "#N4274", i, nr); i <- i + 1
draw.vf.cell2("#J4d5b", "#N5012", i, nr); i <- i + 1
draw.vf.cell2("#J4d63", "#N3680", i, nr); i <- i + 1
draw.vf.cell2("#J4d68", "#N0202", i, nr); i <- i + 1
draw.vf.cell2("#J4d6b", "#N5049", i, nr); i <- i + 1
draw.vf.cell2("#J4d70", "#N3856", i, nr); i <- i + 1
draw.vf.cell2("#J4d71", "#N0199", i, nr); i <- i + 1
draw.vf.cell2("#J4d72", "#N1431", i, nr); i <- i + 1
draw.vf.cell2("#J4d78", "#N3264", i, nr); i <- i + 1
draw.vf.cell2("#J4d7d", "#N2942", i, nr); i <- i + 1
draw.vf.cell2("#J4e24", "#N4813", i, nr); i <- i + 1
draw.vf.cell2("#J4e25", "#N5040", i, nr); i <- i + 1
draw.vf.cell2("#J4e26", "#N5005", i, nr); i <- i + 1
draw.vf.cell2("#J4e28", "#N0319", i, nr); i <- i + 1
draw.vf.cell2("#J4e29", "#N3343", i, nr); i <- i + 1
draw.vf.cell2("#J4e2e", "#N2576", i, nr); i <- i + 1
draw.vf.cell2("#J4e32", "#N3191", i, nr); i <- i + 1
draw.vf.cell2("#J4e33", "#N3471", i, nr); i <- i + 1
draw.vf.cell2("#J4e35", "#N5440", i, nr); i <- i + 1
draw.vf.cell2("#J4e3e", "#N0034", i, nr); i <- i + 1
draw.vf.cell2("#J4e41", "#N3468", i, nr); i <- i + 1
draw.vf.cell2("#J4e49", "#N3885", i, nr); i <- i + 1
draw.vf.cell2("#J4e4c", "#N2141", i, nr); i <- i + 1
draw.vf.cell2("#J4e4f", "#N0715", i, nr); i <- i + 1
draw.vf.cell2("#J4e53", "#N2210", i, nr); i <- i + 1
draw.vf.cell2("#J4e55", "#N2807", i, nr); i <- i + 1
draw.vf.cell2("#J4e58", "#N4630", i, nr); i <- i + 1
draw.vf.cell2("#J4e60", "#N5138", i, nr); i <- i + 1
draw.vf.cell2("#J4e63", "#N0428", i, nr); i <- i + 1
draw.vf.cell2("#J4e64", "#N0642", i, nr); i <- i + 1
draw.vf.cell2("#J4e6d", "#N5048", i, nr); i <- i + 1
draw.vf.cell2("#J4e6e", "#N5056", i, nr); i <- i + 1
draw.vf.cell2("#J4e73", "#N2438", i, nr); i <- i + 1
draw.vf.cell2("#J4f22", "#N4702", i, nr); i <- i + 1
draw.vf.cell2("#J4f27", "#N2750", i, nr); i <- i + 1
draw.vf.cell2("#J4f29", "#N4561", i, nr); i <- i + 1
draw.vf.cell2("#J4f37", "#N3683", i, nr); i <- i + 1
draw.vf.cell2("#J4f3b", "#N0283", i, nr); i <- i + 1
draw.vf.cell2("#J4f40", "#N4391", i, nr); i <- i + 1
draw.vf.cell2("#J4f42", "#N3268", i, nr); i <- i + 1
draw.vf.cell2("#J4f43", "#N4358", i, nr); i <- i + 1
draw.vf.cell2("#J4f44", "#N0054", i, nr); i <- i + 1
draw.vf.cell2("#J4f47", "#N1710", i, nr); i <- i + 1

draw.vf.cell2("#J534c", "#N0973", i, nr); i <- i + 1
draw.vf.cell2("#J5879", "#N1794", i, nr); i <- i + 1
draw.vf.cell2("#J5960", "#N1942", i, nr); i <- i + 1
draw.vf.cell2("#J626f", "#N3200", i, nr); i <- i + 1
draw.vf.cell2("#J6446", "#N3458", i, nr); i <- i + 1
draw.vf.cell2("#J6647", "#N5083", i, nr); i <- i + 1
draw.vf.cell2("#J6d55", "#N4633", i, nr); i <- i + 1

par(oldpar)
}
\keyword{aplot}
\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
\testonly{detach("package:eda")}
}
\keyword{programming}
\name{LifeCycleSavings}
\title{Intercountry Life-Cycle Savings Data}
\usage{data(LifeCycleSavings)}
\alias{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).
}
\description{
  Data on the savings ratio 1960--1970.
}
\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., E. 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}
\name{log}
\title{Logarithms and Exponentials}
\usage{
log(x, base = exp(1))
log10(x)
log2(x)
exp(x)
log1p(x)
}
\alias{log}
\alias{log1p}
\alias{log10}
\alias{log2}
\alias{exp}
\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{log(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.
}
\value{
  A vector of the same length as \code{x} containing the transformed
  values.  \code{log(0)} gives \code{-Inf} (when available).
}
\seealso{
  \code{\link{Trig}},
  \code{\link{sqrt}},
  \code{\link{Arithmetic}}.
}
\examples{
log(exp(3))
all.equal(log(1:10), log(1:10, exp(1)))
log10(30) == log(30, 10)
log10(1e7)# = 7
log2(2^pi) == 2^log2(pi)
Mod(pi - log(exp(pi*1i)) / 1i) < .Machine$double.eps
Mod(1+exp(pi*1i)) < .Machine$double.eps

x <- 10^-(1+2*1:9)
cbind(x, log(1+x), log1p(x))
}
\keyword{math}
\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.

  \code{xor} indicates elementwise exclusive OR.
}
\seealso{\code{\link{TRUE}} or \code{\link{logical}}.}
\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"
}
\keyword{logic}
\name{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}.
}
\examples{
eps <- 100 * .Machine$double.eps
x <- c(0:4, rlogis(100))
all.equal(plogis(x),                 1 / (1 + exp(-x)), tol = eps)
all.equal(plogis(x, lower=FALSE),   exp(-x)/ (1 + exp(-x)), tol = eps)
all.equal(plogis(x, lower=FALSE, log=TRUE), -log(1 + exp(x)),  tol = eps)
all.equal(dlogis(x), exp(x) * (1 + exp(x))^-2, tol = eps)

var(rlogis(4000, 0, s = 5))# approximately (+/- 3)
pi^2/3 * 5^2
}
\keyword{distribution}
\name{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)}.
}
\seealso{
  \code{\link{dnorm}} for the normal distribution.
}
\examples{
dlnorm(1) == dnorm(0)
x <- rlnorm(1000)       # not yet always :
all(abs(x  -  qlnorm(plnorm(x))) < 1e4 * .Machine$double.eps * x)
}
\keyword{distribution}
\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.
}
\examples{
xx <- -9:9
plot(xx, sqrt(abs(xx)),  col = "red")
lines(spline(xx, sqrt(abs(xx)), n=101), col = "pink")
}
\keyword{math}
\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 \code{--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 \code{--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 ``\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
  ``\emph{heap}'' of ``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 \code{--*-nsize} options can be used to specify the number of cons
  cells and the \code{--*-vsize} options specify the size of the vector heap in
  bytes.  Both options must be integers or integers followed by \code{M},
  \code{K}, or \code{k} meaning \emph{Mega} (\eqn{2^{20} = 1048576}),
  (computer) \emph{Kilo} (\eqn{2^{10} = 1024}), or regular \emph{kilo}
  (1000).

  The \code{--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 \code{--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 \code{--min-nsize} and \code{--min-vsize} can be changed by
%  setting the environment variables \code{R_NSIZE} and \code{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 \code{--nsize} and \code{--vsize}
  are equivalent to \code{--min-nsize} and \code{--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}
\name{NA}
\title{Not Available / ``Missing'' Values}
\usage{
NA
is.na(x)
is.na.data.frame(x)

is.na(x) <- value
}
\alias{NA}
\alias{is.na}
\alias{is.na.data.frame}
\alias{is.na<-}
\alias{is.na<-.default}
\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} returns a logical vector
of the same ``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 generic function \code{is.na<-} sets elements to \code{NA}.
}
\arguments{
  \item{x}{an \R object to be tested.}
  \item{value}{a suitable index vector for use with \code{x}.}
}
\details{
  For character vectors the value \code{"NA"} represents missingness.

  \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.
}
\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))       #> F TRUE
is.na(paste(c(1,NA)))#> F FALSE
\testonly{
 is.na(list())# logical(0)
 ll <- list(pi,"C",NaN,Inf, 1:3, c(0,NA), NA)
 is.na (ll)
 is.nan(ll)
}
}
\keyword{NA}
\keyword{logic}
\keyword{manip}
\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.
}
\arguments{
  \item{x}{an object to be tested or coerced.}
  \item{\dots}{ignored.}
}
\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}
\name{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}
\name{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{
  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)
}
\keyword{distribution}
\name{OrchardSprays}
\title{Potency of Orchard Sprays}
\usage{data(OrchardSprays)}
\alias{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
  }
}
\description{
  An experiment was conducted to assess the potency of various
  constituents of orchard sprays in repelling honeybees, using a
  Latin square design.
}
\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{* \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}
\name{Paren}
\title{Parentheses and Braces}
\usage{
( \dots )

{ \dots }
}
\alias{(}
\alias{{}
\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.
}
\seealso{
  \code{\link{if}}, \code{\link{return}}, etc for other objects used in
  the \R language itself.
}
\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}
\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.

  Use
#ifdef unix
  \code{R CMD foo --help}
#endif
#ifdef windows
  \code{Rcmd foo --help}
#endif
  to obtain usage information on utility \code{foo}.
}
#ifdef windows
\note{
  These may not work correctly under Windows 95/98/ME because of
  problems Perl has launching programs on those limited OSes.
}
#endif
\seealso{
  The chapter ``Processing Rd format'' in ``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}
\name{PlantGrowth}
\alias{PlantGrowth}
\title{Results from an Experiment on Plant Growth}
\usage{data(PlantGrowth)}
\description{
  Results from an experiment to compare yields (as measured by dried
  weight of plants) obtained under a control and two different treatment
  conditions.
}
\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 `ctrl', `trt1', and `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}
\name{Platform}
\title{Platform Specific Variables}
\usage{
.Platform
Platform()
}
\alias{.Platform}
\alias{Platform}
\description{
  \code{.Platform} is a list with functions and variables as
  components.  This provides means to write OS portable \R
  code.
}
\details{
  Currently, \code{.Platform <- Platform()} when \R starts up.
}
\value{
  \code{.Platform} is 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 the following values is returned:
  \code{"unix"},  \code{"mac"}, or  \code{"windows"} (in historical order).}
  \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{Sys.info}} which gives more details about the OS,
  \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}
\name{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")
\testonly{dpois(c(0, 1, 0.17, 0.77), 1)}
}
\keyword{distribution}
\name{Primitive}
\title{Call a ``Primitive'' Internal Function}
\usage{
.Primitive(name)
}
\alias{.Primitive}
\arguments{
\item{name}{name of the \R function.}
}
\description{
  \code{.Primitive} returns an entry point to a ``primitive''
  (internally implemented) function.

  The advantage of \code{.Primitive} over \code{\link{.Internal}}
  functions is the potential efficiency of argument passing.
}
\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}
\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 ``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 ``seeds'' and to an integer array of ``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}
\name{Random}
\alias{.Random.seed}
\alias{RNG}
\alias{RNGkind}
\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{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)
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{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{"Marsaglia-Multicarry"}.
  \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 ``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 ``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{"user-supplied":}}{
    Use a user-supplied generator. See \code{\link{Random.user}} for details.
    }
  }

  \code{normal.kind} can be \code{"Kinderman-Ramage"} (the default) or
  \code{"Ahrens-Dieter"} or \code{"Box-Muller"} or \code{"user-supplied"}.

  \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{"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}.
}
\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 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{set.seed} returns \code{NULL}, invisibly.
}
\references{
  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}.
}
\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}
\name{RdUtils}
\alias{Rdconv}
\alias{Rdindex}
\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 Rdindex [options] files
R CMD Rd2dvi [options] files
R CMD Rd2txt [options] file
R CMD Sd2Rd [options] file
#endif
#ifdef windows
Rcmd Rdconv [options] file
Rcmd Rdindex [options] files
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) format 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{Rdindex} creates an index table from Rd files.

  \code{Sd2Rd} converts S version 3 documentation format 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}.  
}
\seealso{
  The chapter ``Processing Rd format'' in ``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}
\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}

\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}
\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{trunc.default}
\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,
  \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 ``close to zero'' values
  are ``zapped'', i.e., treated as \code{0}.
}
\arguments{
  \item{x}{a numeric vector.}
  \item{digits}{integer indicating the precision to be used.}
}
\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))
stopifnot(
 trunc(x1) == as.integer(x1),
 non.int == (ceiling(x1) != trunc(x1) | trunc(x1) != floor(x1)),
 (signif(x1, 1) != round(x1,1)) == (non.int & abs(x1) > 1)
)

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}
\name{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}
\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{
  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))

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)
}
par(mfrow = c(2, 2))
}
\keyword{math}
\name{Startup}
\alias{Startup}
\alias{Rprofile}
\alias{.Rprofile}
\alias{Rprofile.site}
\alias{Renviron.site}
\alias{.Renviron}
\alias{.First}
\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 \code{--no-environ} was given, \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
  \code{R\_ENVIRON}; if this is unset,
  \file{\$R\_HOME/etc/Renviron.site}
  is used.  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 \code{--no-site-file} was given.  The name of this file is
  taken from the value of the \code{R\_PROFILE} environment variable.
  If this variable is unset, the default is
  \file{\$R\_HOME/etc/Rprofile.site}.
  This code is loaded into package \code{base}.

  Then, unless \code{--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 \code{--no-restore-data} was specified, or
  \code{--no-restore}).
  
  Finally, if a function \code{.First} exists, it is executed as
  \code{.First()}.

  The functions \code{.First} and \code{\link{.Last}} can be defined
  in the appropriate startup profiles or reside in \file{.RData}.

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

  The command-line flag \code{--vanilla} implies \code{--no-init-file},
  \code{--no-restore} and \code{--no-environ}.
}
\details{
  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 to a Unix shell.  In particular
  quotes are stripped, and backslashes are removed except inside quotes.
}
\note{
  Prior to \R version 1.4.0, the environment files searched were
  \file{.Renviron} in the current directory, the file pointed to by
  \code{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.
}
\examples{
\dontrun{## Some examples with a Unix flavour
# ~/.Renviron
R_LIBS=~/R/library
PAGER=/usr/local/bin/less

# .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")

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

## then we get
> cat(Sys.getenv("FOOBAR"), "\n")
coo\bardoh\exabc"def'
}}
\keyword{environment}
\name{Sys.info}
\alias{Sys.info}
\title{Extract System and User Information}
\description{
  Reports system and user information.
}
\usage{
Sys.info()
}
\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.
}
\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 and 2000 systems.
#endif
}
\note{
  The meaning of OS ``release'' and ``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.)
}
\author{B. D. Ripley}

\seealso{\code{\link{.Platform}}}

\examples{
Sys.info()
## An alternative (and probably better) way to get the login name on Unix
Sys.getenv("LOGNAME")
}
\keyword{utilities}
\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}.
}
\author{B. D. Ripley}

\note{This function is not 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}
\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}
\name{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, 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 \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{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)")
}
\keyword{distribution}
\name{Titanic}
\alias{Titanic}
\title{Survival of passengers on the Titanic}
\usage{data(Titanic)}
\description{
  This data set provides information on the fate of passengers on the
  fatal maiden voyage of the ocean liner `Titanic', summarized according
  to economic status (class), sex, age and survival.
}
\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 ``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 `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 `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 `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}
\name{ToothGrowth}
\title{The Effect of Vitamin C on Tooth Growth in Guinea Pigs}
\usage{data(ToothGrowth)}
\alias{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.
}
\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).
}
\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: given is supplement type")
}
\keyword{datasets}
\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}).
}
\examples{
cos(0) == 1
sin(3*pi/2) == cos(pi)
x <- rnorm(99)
all.equal( sin(-x), - sin(x))
all.equal( cos(-x), cos(x))
x <- abs(x); y <- abs(rnorm(x))
all(abs(atan2(y, x) - atan(y/x)) <= .Machine$double.eps)# TRUE
table(abs(atan2(y, x) - atan(y/x)) / .Machine$double.eps) # depends!

x <- 1:99/100
all(Mod(1 - (cos(x) + 1i*sin(x)) / exp(1i*x)) < 1.1 * .Machine$double.eps)
 2* abs(1 - x / acos(cos(x))) / .Machine$double.eps #-- depends ?
all(abs(1 - x / asin(sin(x))) <= .Machine$double.eps) # TRUE
all(abs(1 - x / atan(tan(x))) <= .Machine$double.eps) # TRUE
}
\keyword{math}
\name{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, 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{
system.time(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}
\name{UCBAdmissions}
\alias{UCBAdmissions}
\title{Student Admissions at UC Berkeley}
\usage{data(UCBAdmissions)}
\description{
  Aggregate data on applicants to graduate school at Berkeley for the
  six largest departments in 1973 classified by admission and sex.
}
\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
  ``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 ``fourfold display'' for 2-by-2-by-\eqn{k} tables.  See the
  home page of Michael Friendly
  (\url{http://hotspur.psych.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}
\name{USArrests}
\title{Violent Crime Rates by US State}
\usage{data(USArrests)}
\alias{USArrests}
\format{A data frame with 50 observations on 5 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).
}
\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.
}
\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}
\name{USJudgeRatings}
\alias{USJudgeRatings}
\title{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.
  }
}
\description{
  Lawyers' ratings of state judges in the US Superior Court
}
\source{
  New Haven Register, 14 January, 1977 (from John Hartigan).
}
\examples{
data(USJudgeRatings)
pairs(USJudgeRatings, main = "USJudgeRatings data")
}
\keyword{datasets}
\name{USPersonalExpenditure}
\title{Personal Expenditure Data}
\usage{data(USPersonalExpenditure)}
\alias{USPersonalExpenditure}
\format{A matrix with 5 rows and 5 columns.}
\source{The World Almanac and Book of Facts, 1962, page 756.}
\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.
}
\references{
  Tukey, J. W. (1977) \emph{Exploratory Data Analysis.}
  Addison-Wesley.

  McNeil, D. R. (1977) \emph{Interactive Data Analysis.}  Wiley.
}
\examples{
data(USPersonalExpenditure)
USPersonalExpenditure
require(eda)
medpolish(log10(USPersonalExpenditure))
}
\keyword{datasets}
\name{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.
}
\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
 runif(10, 2,2) == 2
\testonly{
 stopifnot(punif(u) == u, dunif(u) == 1,
           runif(100, 2,2) == 2)#-> TRUE [bug in R version <= 0.63.1]
}
var(runif(10000))#- ~ = 1/12 = .08333
}
\keyword{distribution}
\name{VADeaths}
\title{Death Rate Data}
\usage{data(VADeaths)}
\alias{VADeaths}
\format{A matrix with 5 rows and 5 columns.}
\description{
  Death rates per 100 in Virginia in 1940.
}
\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}
\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 an \code{\link{.Alias}} to it for
    S compatibility), whereas \code{R.version.string} is 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"}.}
}
\seealso{
\code{\link{machine}}.
}
\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}
\name{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))}{%
    Var(X) = b^2*(Gamma(1 + 2/a) - Gamma(1 + 1/a))}.
}
\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}
\name{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.
}
\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)
all(fx == dwilcox(x, 6, 4))
Fx <- pwilcox(x, 4, 6)
all(abs(Fx - cumsum(fx)) < 10 * .Machine$double.eps)

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

  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
\testonly{
for(m in 1:5) {
  cat("\n",m,":\n"); print(as.vector(abbreviate(state.name, minl=m)))}
}
}
\keyword{character}
\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.  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 alway 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.
}
\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}
% file add1.Rd
% copyright (C) 1998 B. D. Ripley
%
\name{add1}
\title{Add or Drop All Possible Single Terms to a Model}
\usage{
add1(object, scope, \dots)
add1.default(object, scope, scale = 0, test = c("none", "Chisq"),
             k = 2, trace = FALSE, \dots)
add1.lm(object, scope, scale = 0, test = c("none", "Chisq", "F"),
        x = NULL, k = 2, \dots)
add1.glm(object, scope, scale = 0, test = c("none", "Chisq", "F"),
         x = NULL, k = 2, \dots)

drop1(object, scope, \dots)
drop1.default(object, scope, scale = 0, test = c("none", "Chisq"),
              k = 2, trace = FALSE, \dots)
drop1.lm(object, scope, scale = 0, all.cols = TRUE,
         test=c("none", "Chisq", "F"),k = 2, \dots)
drop1.glm(object, scope, scale = 0, test = c("none", "Chisq", "F"),
          k = 2, \dots)
}
\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}
\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{B. D. Ripley}
\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}}.}
\examples{
example(step)#-> swiss
add1(lm1, ~ I(Education^2) + .^2)
drop1(lm1, test="F")

example(glm)
drop1(glm.D93, test="Chisq")
drop1(glm.D93, test="F")
}
\keyword{models}
\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)
aggregate.default(x, \dots)
aggregate.data.frame(x, by, FUN, \dots)
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.}
  \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 functions 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}}.
}
\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))
\testonly{## regression test for PR#376
aggregate(ts(1:20), nfreq=1/3)
}}
\keyword{category}
\keyword{array}
\name{airmiles}
\title{Commercial Airline Mileage}
\usage{data(airmiles)}
\alias{airmiles}
\format{
  A time-series of 24 observations; yearly, 1937--1960.
}
\source{F.A.A. Statistical Handbook of Aviation.}
\description{
  The revenue passenger miles flown by commercial airlines in
  the United States for each year from 1937 to 1960.
}
\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}
\name{airquality}
\title{New York Air Quality Measurements}
\usage{data(airquality)}
\alias{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)
  }
}
\description{
  Daily air quality measurements in New York, May to September 1973.
}
\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}
% file alias.Rd
% copyright (C) 1998 B. D. Ripley
%
\name{alias}
\title{Find Aliases (Dependencies) in a Model}
\usage{
alias(object, \dots)
alias.formula(object, data, \dots)
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{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.
}
\examples{
## From Venables and Ripley (1997) p.210.
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)

## The next line is optional (for fractions package which gives neater
## results.)
has.VR <- require(MASS, quietly = TRUE)

op <- options(contrasts=c("contr.helmert", "contr.poly"))
npk.aov <- aov(yield ~ block + N*P*K, npk)
alias(npk.aov)
if(has.VR) detach(package:MASS)
options(op)# reset
}
\author{B.D. Ripley}
\keyword{models}
\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}.
}
\seealso{\code{\link{any}}, the ``complement'' of \code{all}, and
  \code{\link{stopifnot}(*)} which is an \code{all(*)}
  ``insurance''.
}
\examples{
range(x <- sort(round(rnorm(10) - 1.2,1)))
if(all(x < 0)) cat("all x values are negative\n")
}
\keyword{logic}
\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)

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 ``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, comparisons are after scaling 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
}
\seealso{\code{\link{==}}, and \code{\link{all}} for exact equality testing.}
\examples{
all.equal(pi, 355/113) # not precise enough (default tol) > relative error

stopifnot(
all.equal(gamma(2:14),   cumprod(1:13))) # TRUE, but

all      (gamma(2:14) == cumprod(1:13)) # FALSE, since not exactly
all.equal(gamma(2:14),   cumprod(1:13), 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}


\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}
\name{anova}
\alias{anova}
\alias{anova.mlm}
% others in ./lm.summaries.Rd
\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 ``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.
}
\seealso{
  \code{\link{coefficients}}, \code{\link{effects}},
  \code{\link{fitted.values}}, \code{\link{residuals}}, \code{\link{summary}}.
}
\keyword{regression}
\keyword{models}
\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.
}
\seealso{
  \code{\link{glm}}, \code{\link{anova}}.
}
\examples{
## --- Continuing the Example from  ``?glm'':%\code{\link{glm}}:
\testonly{example("glm", echo = FALSE)}
anova(glm.D93)
anova(glm.D93, test = "Cp")
anova(glm.D93, test = "Chisq")
}
\keyword{models}
\keyword{regression}

\name{anova.lm}
\title{ANOVA for Linear Model Fits}
\usage{
anova(object, \dots)
anova.lmlist(object, \dots, scale = 0, test = "F")
}
\alias{anova.lm}
\alias{anova.lm.null}
\alias{anova.lmlist}
\alias{anovalist.lm}
\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.
}
\seealso{
  The model fitting function \code{\link{lm}}.
}
\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}
\name{anscombe}
\title{Anscombe's Quartet of ``Identical'' Simple Linear Regressions}
\usage{data(anscombe)}
\alias{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.
}
\description{
  Four \eqn{x}-\eqn{y} datasets which have the same traditional
  statistical properties (mean, variance, correlation, regression line,
  etc.), yet are quite different.
}
\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}
\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}.
}
\seealso{\code{\link{all}}, the ``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}
\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{summary.aov}
\alias{summary.aovlist}
\alias{print.summary.aov}
\alias{print.summary.aovlist}
\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.
}
\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.
}
\author{B. D. Ripley}
\seealso{
  \code{\link{lm}}, \code{\link{alias}}, \code{\link{proj}},
  \code{\link{model.tables}}
}
\examples{
## From Venables and Ripley (1997) p.210.
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}
\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.
}
\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])

%-----------
\testonly{
%-----------
# check the names

x <- array(1:24, c(4, 6))
nms <- list(happy=letters[1:4], sad=LETTERS[1:6])

dimnames(x) <- nms
tmp <- aperm(x, c(2, 1))
stopifnot(all.equal(dimnames(tmp), nms[c(2, 1)]))

dimnames(x) <- c(nms[1], list(NULL))
tmp <- aperm(x, c(2, 1))
stopifnot(all.equal(dimnames(tmp), c(list(NULL), nms[1])))

names(nms) <- c("happy", "sad")
dimnames(x) <- nms
tmp <- aperm(x, c(2, 1))
stopifnot(all.equal(names(dimnames(tmp)), names(nms[c(2, 1)])))

dimnames(x) <- c(nms[1], list(NULL))
tmp <- aperm(x, c(2, 1))
stopifnot(all.equal(names(dimnames(tmp)), c("", names(nms)[1])))

# check resize

stopifnot(all(dim(aperm(x, c(2, 1), FALSE))==dim(x)))
stopifnot(is.null(dimnames(aperm(x, c(2, 1), FALSE))))

# check the types

x <- array(1:24, c(4, 6))
stopifnot(all.equal(aperm(x, c(2, 1)), t(x)))
stopifnot(is.integer(aperm(x, c(2, 1))))

x <- x + 0.0
stopifnot(all.equal(aperm(x, c(2, 1)), t(x)))
stopifnot(is.double(aperm(x, c(2, 1))))

x <- x + 0.0i
stopifnot(all.equal(aperm(x, c(2, 1)), t(x)))

x[] <- LETTERS[1:24]
stopifnot(all.equal(aperm(x, c(2, 1)), t(x)))

x <- array(list("fred"), c(4, 6))
x[[3, 4]] <- 1:10
stopifnot(all.equal(aperm(x, c(2, 1)), t(x)))
}%end{testonly}
}
\keyword{array}
\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}.
}
\examples{
stopifnot(
    append(1:5, 0:1, after=3)
 == append(1:3, c(0:1, 4:5)))
}
\keyword{manip}
\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}.}
}
\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 the calls to \code{FUN} return vectors of different lengths,
  \code{apply} returns a list of length \code{dim(X)[MARGIN]}.
}
\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

\testonly{
 apply(x,  2, summary) # 6 x n matrix
 apply(x,  1, quantile)# 5 x n matrix

 d.arr <- 2:5
 arr <- array(1:prod(d.arr), d.arr,
          list(NULL,letters[1:d.arr[2]],NULL,paste("V",4+1:d.arr[4],sep="")))
 aa <- array(1:20,c(2,2,5))
 stopifnot(
	apply(arr, 1:2, sum) == t(apply(arr, 2:1, sum)),
	aa == apply(aa,2:3,function(x) x),
        all.equal(apply(apply(aa,2:3, sum),2,sum),
                  10+16*0:4, tol=4*.Machine$double.eps)
 )
 marg <- list(1:2, 2:3, c(2,4), c(1,3), 2:4, 1:3, 1:4)
 for(m in marg) print(apply(arr, print(m), sum))
 for(m in marg) ## 75% of the time here was spent on the names
   print(dim(apply(arr, print(m), quantile, names=FALSE)) == c(5,d.arr[m]))
}
}
\keyword{iteration}
\keyword{array}
\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, xout, method="linear", n=50,
          yleft, yright, rule = 1, f=0, ties = mean)
approxfun(x, y,       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.
}
\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}
\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 to 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{
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)

apropos(".", mode="list")

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

# everything
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}
\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.
}
\seealso{
  \code{\link{formals}},
  \code{\link{help}}.
}
\examples{
args(c)            # -> NULL (c is a `primitive' function)
args(plot.default)
}
\keyword{documentation}
\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.
}
\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
}
\keyword{array}
\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.
}
\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}
\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 \code{\link[date:as.date]{date}}), \code{"chron"} and
  \code{"dates"} (from package \code{\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}}.)
}
\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. 
#ifdef mac
  Under MacOS only the current timezone \code{""} and UTC (or GMT)
  are supported.
#endif
}
\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
\testonly{
 stopifnot(range(z) == z,
           min(z) == z,
           max(z) == z,
           mean(z) == z)
}
(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}
\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
as.environment("package:ctest")
}
\keyword{data}
\keyword{environment}
\name{as.function}
\title{Convert Object to Function}
\usage{
as.function(x, \dots)

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}%-- one or more ...
\name{assign}
\alias{assign}
\alias{<-}
\alias{=}
\alias{<<-}
\alias{->}
\alias{->>}
\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)
x <- value
x <<- value
value -> x
value ->> x

x = value
}
\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.
}
\section{Assignment Operators}{
  There are three different assignment
  operators. 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 differs 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.
}
\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}.
}

\seealso{
  \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}
\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://hotspur.psych.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}
\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}{``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). For this reason \code{attach}
  can lead to confusion.
}
\value{
  The \code{\link{environment}} is returned invisibly with a
  \code{"name"} attribute.
}
\seealso{
  \code{\link{library}}, \code{\link{detach}}, \code{\link{search}},
  \code{\link{objects}}, \code{\link{environment}}.
}
\examples{
data(women)
summary(women$height) ## refers to variable `height' in the dataframe
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}
\name{attenu}
\title{The Joyner-Boore Attenuation Data}
\usage{data(attenu)}
\alias{attenu}
\format{A dataframe 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.
}
\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.
}
\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 ``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}
\name{attitude}
\alias{attitude}
\title{Attitudes Toward Supervisors}
\usage{data(attitude)}
\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.}
\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.\cr
  (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}
\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.}
}
\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.
}
\seealso{
  \code{\link{attributes}}
}
\examples{
# create a 2 by 5 matrix
x <- 1:10
attr(x,"dim") <- c(2, 5)
}
\keyword{attribute}
\name{attributes}
\title{Object Attribute Lists}
\usage{
attributes(obj)
attributes(obj) <- list
mostattributes(obj) <- list
}
\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}
}
\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.
}
\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}
\name{autoload}
\title{On-demand Loading of Packages}
\usage{
autoload(name, package,...)
autoloader(name, package,...)
.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.
}
\seealso{
\code{\link{delay}}, \code{\link{library}}
}
\examples{
autoload("line","eda")
search()
ls("Autoloads")
all(ls("Autoloads") == ls(envir = .AutoloadEnv))
data(cars)
plot(cars)
z<-line(cars)
abline(coef(z))
search()
detach("package:eda")
search()
z<-line(cars)
search()
}
\keyword{data}
\keyword{programming}

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

\name{axis.POSIXct}
\alias{axis.POSIXct}
\alias{plot.POSIXct}
\alias{plot.POSIXlt}
\title{Date-time Plotting Functions}
\description{
  Functions to manipulate objects of classes \code{"POSIXlt"} and
  \code{"POSIXct"} representing calendar dates and times (to the nearest
  second). 
}
\usage{
plot.POSIXct(x, y, xlab = "", ...)
plot.POSIXlt(x, y, xlab = "", ...)
axis.POSIXct(side, x, at, format, ...)
}
\synopsis{
plot.POSIXct(x, y, xlab = "", xaxt = par("xaxt"), ...)
plot.POSIXlt(x, y, xlab = "", 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.}
}
\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{
if(require(MASS, quietly = TRUE)) {
data(beav1)
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)
detach(package:MASS)
}

plot(.leap.seconds, 1:22, type="n", yaxt="n",
     xlab="leap seconds", ylab="", bty="n")
rug(.leap.seconds)
}
\keyword{utilities}
\keyword{chron}
\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 = 0,
     pos = NA, outer = FALSE, font = NA, vfont = NULL, \dots)
}
\arguments{
  \item{side}{an integer specifying which side of the plot the axis is
    to be drawn on.}
  \item{at}{the points at which tick-marks are to be drawn. Non-finite
    (infinite, \code{NaN} or \code{NA}) values are omitted.}
  \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{\dots}{graphical parameters may also be passed as arguments to
    this function.}
}
\value{
  This function is invoked for its side effect, which is to add an axis
  to an already existing plot.  The axis is placed as follows: 1=below,
  2=left, 3=above and 4=right.
}
\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.
}
\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), type = 's', xaxt='n', col = 'red')
axis(1, 1:7, LETTERS[1:7], col.axis = 'blue')
\testonly{ # test sorting of labels
Y <- c(10.50, 4.0, 13.75, 7.25)
plot(1:4, Y, xlim=c(0,5), ylim=c(0,15))
axis(side=4, at=Y, labels=LETTERS[1:4])
}
}
\keyword{aplot}
\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 ``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{
  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)
( y2 <- backsolve(r, x, transpose = TRUE)) # 8 -12 -5
all(t(r) \%*\% y2 == x)# exactly on Linux (Pentium)
all(y  == backsolve(t(r), x, upper = FALSE, transpose = TRUE))
all(y2 == backsolve(t(r), x, upper = FALSE, transpose = FALSE))
}
\keyword{algebra}
\keyword{array}
\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 ``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]{bandwith.nrd}}, \code{\link[MASS]{ucv}},
  \code{\link[MASS]{bcv}} and \code{\link[MASS]{width.SJ}} in
  \code{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. (1999)
\emph{Modern Applied Statistics with S-PLUS.}
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}
\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,
        axes = TRUE, axisnames = TRUE,
        cex.axis = par("cex.axis"), cex.names = par("cex.axis"),
        inside = TRUE, plot = TRUE, \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 ``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{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 names.}
  \item{inside}{logical.  If \code{TRUE}, the lines which  divide
    adjacent bars will be drawn.}
  \item{plot}{logical.  If \code{FALSE}, nothing is plotted.}
  \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{apply(mp, 2, mean)} for the
  midpoints of each \emph{group} of bars, see example.
}
\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 <- apply(VADeaths, 2, sum)
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 = apply(mp, 2, mean), line = -2,
      text = paste("Mean", formatC(apply(hh, 2, mean))), 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))
}
\keyword{hplot}
\name{bindenv}
\title{Binding and Environment Adjustments}
\usage{
lockEnvironment(env, bindings = FALSE)
environmentIsLocked(env)
lockBinding(sym, env)
bindingIsLocked(sym, env)
makeActiveBinding(sym, fun, env)
bindingIsActive(sym, env)
}
\alias{bindenv}
\alias{lockEnvironment}
\alias{environmentIsLocked}
\alias{lockBinding}
\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

# 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}
\name{birthday}
\alias{qbirthday}
\alias{pbirthday}
\title{Probability of coincidences}
\description{
Computes approximate answers to a generalised "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. "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}%-- one or more ...
\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) <- list
}
\arguments{
  \item{fun}{a function object or a character string naming the function
    to be manipulated.
    If not specified, the function calling \code{body} is used.}
  \item{list}{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.
}
\seealso{
  \code{\link{alist}},
  \code{\link{args}},
  \code{\link{function}}.
}
\examples{
body(body)
f <- function(x) x^5
body(f) <- expression(5^x)
f(3) # = 125
str(body(f))
}
\keyword{programming}
\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.
}
\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='137', col = 'red')
}
\keyword{aplot}
\name{boxplot}
\alias{boxplot}
\alias{boxplot.default}
\title{Box Plots}
\description{
  Produce box-and-whisker plot(s) of the given (grouped) values.
}
\usage{
\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{x, \dots}{for specifying data from which the boxplots are to be
    produced as well as for giving graphical parameters.  The named
    arguments in this (more precisely, in \code{list(x, ...)}) are
    treated as graphical parameters in addition to the ones given by
    argument \code{pars}.  The other arguments specify the 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{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}{graphical parameters can also be passed as arguments to
    \code{boxplot}.}
  \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}
}
\seealso{
  \code{\link{boxplot.formula}} for the formula interface;
  \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}
\name{boxplot.formula}
\alias{boxplot.formula}
\title{Formula Notation for Box Plots}
\description{
  Produce box-and-whisker plot(s) of the given (grouped) values using
  formula notation.
}
\usage{
\method{boxplot}{formula}(formula, data = NULL, \dots, subset)
}
\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{\dots}{arguments to the default boxplot method and graphical
    parameters may also be passed as arguments, see \code{\link{par}}.}
  \item{subset}{an optional vector specifying a subset of observations
    to be used for plotting.}
}
\details{
  This is a method of the generic function \code{\link{boxplot}}.  It
  operates by setting up the data from the formula specification, and
  then calling \code{\link{boxplot.default}}.
}
\seealso{
  \code{\link{boxplot.default}}
}
\examples{
data(OrchardSprays)
boxplot(decrease ~ treatment, data = OrchardSprays,
        log = "y", col="bisque")
}
\keyword{hplot}
\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 ``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
    interquartile coef 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 ``hinge'', the median, the upper ``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 ``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 ``hinge''s are versions of the first 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.
}
\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):
\testonly{
 ## 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}
\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.
}
\seealso{
  \code{\link{debug}}, and
  \code{\link{traceback}} for the stack on error.
}
\keyword{programming}
\keyword{environment}
\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 ``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 `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 \code{--vanilla} option may help in isolating a
  bug.  This ensures that the site profile and saved data files are not
  read.

  On some systems 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}.
}
\seealso{R FAQ} 
\author{This help page is adapted from the Emacs manual}
\keyword{utilities}
\keyword{error}
\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 ``internal''
    functions (which can be called via \code{\link{.Internal}}) should
    be returned.}
}
\keyword{utilities}
\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 ``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}).}
}
\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.
}
\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}
\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, ...)
}
\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}
\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.}
}
\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")

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}
\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.}
}
\value{
  \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 not possible to coerce objects to mode call (objects either are
  calls or they are not calls).  \code{as.call} returns its argument if
  it is a call and otherwise terminates with an error message.
}
\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}}.
}
\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}
\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 \code{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?}
    \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 \code{--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 60059.}
    }
}
\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}
\name{cars}
\title{Stopping Distances of Cars}
\usage{data(cars)}
\alias{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.
}
\description{
  The data give the speed of cars and the distances taken to stop.
  Note that the data were recorded in the 1920s.
}
\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)
}
\keyword{datasets}
\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)
case.names.lm(object, full = FALSE, \dots)

variable.names(object, \dots)
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}
\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 \code{\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 \code{"\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}).
}
\seealso{
  \code{\link{print}}, \code{\link{format}}, and \code{\link{paste}}
  which concatenates into a string.
}
\examples{
\testonly{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}
\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.  There may be methods
  for other \R classes.
}
\usage{
cbind(\dots, deparse.level = 1)
rbind(\dots, deparse.level = 1)
}
\arguments{
  \item{\dots}{vectors or matrices.}
  \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.

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

  \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.
}
\examples{
form <- y ~ a + b + c
as.character(form)  ## length 3
deparse(form)       ## like the input
}
\keyword{character}
\keyword{classes}
\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}

\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}
\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
    ``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}
\name{chickwts}
\title{Chicken Weights by Feed Type}
\usage{data(chickwts)}
\alias{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}, p.214.
} 
\description{
  An experiment was conducted to measure and compare the effectiveness
  of various feed supplements on the growth rate of chickens.
}
\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}
\name{chol}
\alias{chol}
\title{The Choleski Decomposition}
\description{
  Compute the Choleski factorization of a symmetric (Hermitian),
  positive definite square matrix.
}
\usage{
chol(x)
}
\arguments{
  \item{x}{a symmetric, positive definite matrix.}
}
\value{
  The upper triangular factor of the Choleski decomposition, i.e., the
  matrix \eqn{R} such that \eqn{R'R = x} (see example).
}
\details{
  Note that only the upper triangular part of \code{x} is
  used such that the above only holds when \code{x} \emph{is} symmetric.

  If the matrix is not positive-definite an error is generated.
  A non-negative definite but not strictly positive-definite matrix
  may or may not give an error depending on the numerical errors.
}
\references{
  Dongarra, J. J., Bunch, J. R., Moler, C. B. and Stewart, G. W. (1978)
  \emph{LINPACK Users Guide.}  Philadelphia: SIAM Publications.
}
\seealso{
  \code{\link{chol2inv}} for its \emph{inverse},
  \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'
all(abs(m  -  t(cm) \%*\% cm) < 100* .Machine$double.eps) # TRUE
}
\keyword{algebra}
\keyword{array}
\name{chol2inv}
\alias{chol2inv}
\title{Inverse from Choleski Decomposition}
\description{
  Invert a symmetric, positive definite square matrix from its Choleski
  decomposition.
}
\usage{
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.}
}
\value{
  The inverse of the decomposed matrix.
}
\references{
  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{solve}}.}
\examples{
cma <- chol(ma  <- cbind(1, 1:3, c(1,3,7)))
t(cma) \%*\% cma # = ma
all.equal(diag(3), ma \%*\% chol2inv(cma))
}
\keyword{algebra}
\keyword{array}
\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 components \code{x} and \code{y}}
}
\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).

  `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{
  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.
}
\author{B. D. Ripley}

\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}
\name{class}
\title{Object Classes}
\usage{
class(x)
class(x) <- names
unclass(x)
inherits(x, what, which = FALSE)
}
\alias{class}
\alias{class<-}
\alias{unclass}
\alias{inherits}
\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.
}
\arguments{
  \item{x}{an objects}
  \item{what}{a character vector naming classes.}
  \item{which}{logical affecting return value: see Details.}
}

\details{
  An \R ``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 ``inherits'' from.  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.

  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
  information 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}.
}
\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}
\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}
\name{co2}
\title{Mauna Loa Atmospheric CO2 Concentration}
\usage{data(co2)}
\alias{co2}
\format{
  A time series of 468 observations; monthly from 1959 to 1997.
}
\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.
}
\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}
\name{codes}
\alias{codes}
\alias{codes.factor}
\alias{codes.ordered}
\alias{codes<-}
\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.
}
\usage{
codes(x, \dots)
codes(x) <- value
}
\arguments{
  \item{x}{an object from which to extract or set the codes.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\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{
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}


\name{coefficients}
\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.
}
\examples{
x <- 1:5; coef(lm(c(1:3,7,6) ~ x))
}
\keyword{regression}
\keyword{models}
\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}.
}
\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}
\name{col2rgb}
\alias{col2rgb}
\title{Color to RGB Conversion}
\description{
  ``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 ``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:7)# the ones from the palette()
stopifnot(col2rgb(0) ==  # col = 0 is the background color:
    print(col2rgb(par("bg"))))

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

stopifnot(col2rgb("#08a0ff") == c(8, 160, 255))
## 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=""))
stopifnot(grC["red",] == grC["green",],
          grC["red",] == grC["blue",],
          grC["red", 1:4] == c(0,3,5,8))
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}
\name{row/colnames}
\title{Row and Columnn Names}
\alias{rownames}
\alias{rownames<-}
\alias{colnames}
\alias{colnames<-}
\usage{
rownames(x, do.NULL = TRUE, prefix = "row")
rownames(x) <- namevector

colnames(x, do.NULL = TRUE, prefix = "col")
colnames(x) <- namevector
}
\description{
  Retrieve or set the row or column names of an object (the first or
  second component of its \code{\link{dimnames}}).
}
\arguments{
  \item{x}{}
  \item{do.NULL}{logical. Should this create names if they are \code{NULL}?}
  \item{prefix}{for created names.}
}
\details{
  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
  \code{dimnames(x)[[i]]} (\code{i =} 1 or 2) is \code{NULL}. 
}
\seealso{\code{\link{dimnames}}, \code{\link{case.names}},
    \code{\link{variable.names}}.
}
\examples{
m0 <- matrix(NA, 4, 0)
m2 <- cbind(1,1:4)
rownames(m0)
\testonly{
        rownames(m0, do.NULL = FALSE)
        colnames(m0, do.NULL = FALSE)
}
colnames(m2, do.NULL = FALSE)
colnames(m2) <- c("x","Y")
rownames(m2) <- rownames(m2, do.NULL = FALSE, prefix = "Obs.")
m2
}
\keyword{array}
\keyword{manip}
\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 ``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}
\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()
}
%- maybe also `usage' for other objects documented here.
\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.
}
\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}
\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 ``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}
\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}
\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.)

  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.
}
\examples{
( z <- 0i ^ (-3:3) )
stopifnot(Re(z) == 0 ^ (-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)

all(Mod ( 1 -  sin(z) / ( (exp(1i*z)-exp(-1i*z))/(2*1i) ))
    < 100*.Machine$double.eps)
## 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}
\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.
}
\author{B.D. Ripley}
\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}
\name{connections}
\alias{connections}
\alias{connection}
\alias{file}
\alias{pipe}
\alias{fifo}
\alias{gzfile}
\alias{url}
\alias{socketConnection}
\alias{open}
\alias{open.connection}
\alias{isOpen}
\alias{isIncomplete}
\alias{close}
\alias{close.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)
url(description, open = "", blocking = TRUE,
    encoding = getOption("encoding"))
socketConnection(host = "localhost", port, server = FALSE,
                 blocking = FALSE, open = "a+",
                 encoding = getOption("encoding"))

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

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{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 `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{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{\dots}{arguments passed to or from other methods.}
}
\details{
  The first six 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
  \code{gzip}: such connections can only be binary.

  All platforms support 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.

  \code{close} closes and destroys a connection.

  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.}
    \item{\code{"r+"}, \code{"r+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.

  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()}.
}
\note{
  \R's connections are modelled on those in S version 4 (see Chambers,
  1998). However \R also goes well beyond the Svr4 model, for example
  in output text connections and URL, gzfile 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{"*"}.
}
\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{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.
}

\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")

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

## 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
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}
\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}}.
}
\seealso{
  \code{\link{filled.contour}} for ``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}
\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, 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{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.

  Note that as from \R version 0.62.2, \code{contr.poly} returns
  contrasts based on orthogonal (rather than raw) polynomials.
}
\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}.
}
\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}
\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) <- ctr
}
\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{ctr}{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.
}
\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 <- factor(ff))
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}
\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}
\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 ``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}
\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 \file{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}
\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 ``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).
}
\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{
  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(long ~ lat | depth, data = quakes)
given.depth <- co.intervals(quakes$depth, number=4, overlap=.1)
coplot(long ~ lat | depth, data = quakes, given.v=given.depth, rows=1)

## Conditioning on 2 variables:
ll.dm <- long ~ lat | 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
coplot(breaks ~ 1:54 | wool * tension, data = warpbreaks, show.given = 0:1)
coplot(breaks ~ 1:54 | 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}
\name{copyright}
\title{Copyrights of Files Used to Build R}
\alias{copyright}
\alias{copyrights}
\description{
    \R is released under the `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}
\name{cor}
\title{Correlation, Variance and Covariance (Matrices)}
\usage{
var(x, y = NULL, na.rm = FALSE, use)
cor(x, y = NULL, use = "all.obs")
cov(x, y = NULL, use = "all.obs")
}
\alias{var}
\alias{cor}
\alias{cov}
\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.
}
\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{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{na.rm}{logical. Should missing values be removed?}
}
\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} 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, and from \R 1.2.3 fail if \code{x} has length zero.
}
\seealso{\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

\testonly{
 stopifnot(  is.na(var(1)),
           !is.nan(var(1)))

 zz <- c(-1.30167, -0.4957, -1.46749, 0.46927)
 r <- cor(zz,zz); r - 1
 stopifnot(r <= 1) # fails in R <= 1.3.x, for versions of Linux and Solaris
}
## Correlation Matrix of Multivariate sample:
data(longley)
(Cl <- cor(longley))
## Graphical Correlation Matrix:
symnum(Cl) # highly correlated

##--- Missing value treatment:
data(swiss)
C1 <- cov(swiss)
range(eigen(C1, only=TRUE)$val) # 6.19  1921
swiss[1,2] <- swiss[7,3] <- swiss[25,5] <- NA # create 3 "missing"
\dontrun{
 C2 <- cov(swiss) # Error: missing obs...
}
C2 <- cov(swiss, use = "complete")
range(eigen(C2, only=TRUE)$val) # 6.46  1930
C3 <- cov(swiss, use = "pairwise")
range(eigen(C3, only=TRUE)$val) # 6.19  1938
}
\keyword{univar}
\keyword{multivariate}
\keyword{array}
\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}
\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}
\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=x)
}
\arguments{
  \item{x, y}{matrices.}
}
\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}
\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}.
}
\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}
\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 a function which will be plotted.}
  \item{x}{a `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 ``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}
\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, \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{"secs"}, \code{"mins"},
    \code{"hours"}, \code{"days"}, \code{"weeks"}, \code{"months"}
    or \code{"years"}.
 }
 \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{start.on.monday}{logical. If \code{breaks = "weeks"}, should the
    week start on Mondays or Sundays?}
  \item{\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}
\name{cut}
\title{Convert Numeric to Factor}
\usage{
cut(x, \dots)
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 `x[i]' equal to the
    lowest (or highest, for \code{right = FALSE}) `breaks' value should be
    included.}
  \item{right}{logical, indicating if the intervals should 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.
}
\seealso{
  \code{\link{split}} for splitting a variable according to a group factor;
  \code{\link{factor}}, \code{\link{tabulate}}, \code{\link{table}}.
}
\examples{
Z <- rnorm(10000)
table(cut(Z, br = -6:6))
system.time(print(sum(table(cut(Z, br = -6:6, labels=FALSE)))))
system.time(print(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}
\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"))
}
\arguments{
  \item{\dots}{a sequence of names or 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.}
}
\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{.RData} or \file{.rda} are
    \code{\link{load}()}ed.

    \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{.tab} 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} are read using
    \code{\link{read.table}(\dots, header = TRUE, sep = ";")},
    and also result in a data frame.
  }

  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.

  If no data sets are specified, \code{data} lists the available data
  sets.  It looks for a file \file{00Index} in a \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 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 datasets 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.
}
\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}
\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 ``class'' of \code{x}.

  The ``class'' is the (first element) of the \code{\link{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.)
}
\seealso{
  \code{\link{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)
}
\keyword{classes}
\keyword{methods}
\name{data.frame}
\title{Data Frames}
\alias{data.frame}
\alias{as.data.frame}
\alias{is.data.frame}
\alias{row.names}
\alias{row.names.data.frame}
\alias{row.names.default}
\alias{row.names<-}
\alias{row.names<-.data.frame}
\alias{row.names<-.default}
%- methods:
\alias{plot.data.frame}
%
\alias{[.AsIs}
\alias{as.data.frame.AsIs}
% FIXME: I(.) is not documented enough; "AsIs" does not appear anywhere
\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}
\alias{xpdrows.data.frame}
\description{
  These functions create or manipulate 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)

as.data.frame(x, row.names = NULL, optional = FALSE)
is.data.frame(x)

row.names(x)
row.names(x) <- names
}
\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}{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.}
  \item{optional}{logical. If \code{TRUE}, setting row names is
    optional.}
  \item{x}{object of class \code{data.frame}.}
}
\value{
  For \code{data.frame(.)} a data frame, a matrix-like stucture whose
  columns may be of differing types (numeric, factor and character).

  \code{as.data.frame} is generic function with many methods.   It
  attempts to coerce its argument to be a data frame.

  \code{is.data.frame} returns \code{TRUE} if its argument is a data
  frame and \code{FALSE} otherwise.

  \code{row.names} can be used to set and retrieve the row names of a
  data frame, similarly to \code{\link{rownames}} for arrays (and
  it is a generic function that calls \code{rownames} for an
  array argument.}

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

  \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.
}
\details{
  Character variables passed to \code{data.frame} are converted to
  factor columns unless protected by \code{\link{I}}. It also applies to
  adding columns to a data frame.

  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,
  with the exception of matrices of class \code{\link{model.matrix}}.
}
\note{
  In versions of \R prior to 1.4.0 (and in S3) logical columns were
  converted to factors.
}
\seealso{
  \code{\link{print.data.frame}},
  \code{\link{read.table}},
  \code{\link{Math.data.frame}} etc, about
  \emph{Group} methods for \code{data.frame}s;
  \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 dataframe with 10 rows
(d.0 <- d[FALSE, ]) # <0 rows> dataframe  (3 cols)
(d00 <- d0[FALSE,])  # NULL dataframe with 0 rows
\testonly{% failed before ver. 1.4:
(d000 <- data.frame()) #but not quite the same as d00:
!identical(d00, d000)
dput(d00)
dput(d000)
stopifnot(identical(d, cbind(d, d0)),
          identical(d, cbind(d0, d)),
          identical(d, rbind(d,d.0)),
          identical(d, rbind(d.0,d)),
          identical(d, rbind(d00,d)),
          identical(d, rbind(d,d00)),

          TRUE )
## These are not true: dim is ok, but names() not {seen via dput}
##          identical(d0, rbind(d0,d00)),
#         identical(d0, rbind(d00,d0)),
#          identical(d00,rbind(d00,d00)),
#          identical(d00,cbind(d00,d00)),


}
}
\keyword{classes}
\keyword{methods}
\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 codes.
}
\usage{
data.matrix(frame)
}
\arguments{
  \item{frame}{a data frame whose components are either logical vectors,
    factors or numeric vectors.}
}
\seealso{
  \code{\link{as.matrix}},
  \code{\link{codes}},
  \code{\link{data.frame}},
  \code{\link{matrix}}.
}
\keyword{array}
\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{...}{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
  ``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}
\name{date}
\alias{date}
\title{System Date and Time}
\usage{date()}
\description{Returns a character string of the current system date and
    time.}
\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.
}
\examples{
(d <- date())
nchar(d) == 24
}
\keyword{utilities}
\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.
    \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}
\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.
}
\keyword{programming}
\keyword{environment}
\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.
}
\author{B. D. Ripley}
\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.
}
\seealso{
  \code{\link{options}} for setting \code{error} options.
}
\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}
\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}
\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}
\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.

  \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)
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}
\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.  If omitted, the
    list of available topics is displayed.}
  \item{device}{the graphics device to be used.}
  \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.}
  \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 instead of name.}
  \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{
% Most demos are strictly tested anyway, since R 1.3.0,
% make sure, the others are run here: 
demo() # for attached packages

## All available demos:
demo(package = .packages(all.available = TRUE))

demo(lm.glm)
\testonly{
demo(nlm)
}
\dontrun{
 ch <- "scoping"
 demo(ch, character = TRUE)
}
}
\keyword{documentation}
\keyword{utilities}
\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 ``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 ``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 ``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{
  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

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}
\name{deparse}
\alias{deparse}
\title{Expression Deparsing}
\description{
  Turn unevaluated expressions into character strings.
}
\usage{deparse(expr, width.cutoff = 60)}
\arguments{
  \item{expr}{any \R expression.}
  \item{width.cutoff}{integer in \eqn{[20, 500]} determining the cutoff
    at which line-breaking is tried.}
}
\details{
  This function turns unevaluated expressions (where ``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}.
}
\seealso{
  \code{\link{substitute}},
  \code{\link{parse}},
  \code{\link{expression}}.
}
\examples{
deparse(args(lm))
deparse(args(lm), width = 100)
myplot <-
function(x, y)
    plot(x, y, xlab=deparse(substitute(x)),
        ylab=deparse(substitute(y)))
}
\keyword{programming}
\keyword{manip}
\keyword{data}
\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 \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.
}
\seealso{
  \code{\link{nlm}} and \code{\link{optim}} for numeric minimization
  which could make use of derivatives,
  \code{\link[nls]{nls}} in package \code{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)
stopifnot(eval(D.sc) ==
          attr(eval(dxy),"gradient")[,"x"])

## function returned:
deriv((ff <- y ~ sin(cos(x) * y)), c("x","y"), func = TRUE)
stopifnot(all.equal(deriv(ff, c("x","y"), func = TRUE ),
                    deriv(ff, c("x","y"), func = function(x,y){ } )))
## 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}


\name{det}
\title{Calculate the Determinant of a Matrix}
\alias{det}
\usage{
det(x, method = c("qr","eigenvalues"))
}
\description{
  \code{det} calculates the determinant of a matrix either by QR
  decomposition or from the eigenvalues, see \code{\link{qr}} and
  \code{\link{eigen}}.
  }
\arguments{
  \item{x}{numeric matrix.}
  \item{method}{\code{"qr"} (default) or \code{"eigenvalues"}}
}
\note{
  Often, computing the determinant is \emph{not} what you should be doing
  to solve a given problem.

  The \code{"qr"} method is much faster for large matrices.
}
\seealso{\code{\link{eigen}}, \code{\link{qr}}, \code{\link{svd}}}
\examples{
(x <- matrix(1:4, ncol=2))
det(x)
det(x, method="eigenvalues")

det(print(cbind(1,1:3,c(2,0,1))))
}
\keyword{array}
\name{detach}
\title{Detach Objects from the Search Path}
\usage{
detach(name, pos = 2)
}
\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.
  }
}
\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 \code{base}
  package (the last item in the search list).
}
\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()))

library(mva)
detach(2)# `pos' used for `name'
}
\keyword{data}
\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}
\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)
}
\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}
}
\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}).

  \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 "inhibit"
  then recording is turned off.
}
\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}
\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 ``printing''.

  You will need a recent version of \code{ghostscript} (5.10 and
  later have been tested): the full path to the executable can be set by
  the environment variable \code{"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 \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.
}
\author{B. D. Ripley}

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

\keyword{utilities}
\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)
deviance.lm (object, \dots)
deviance.glm(object, \dots)
deviance.mlm(object, \dots)
deviance.default(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.

  There is no default method for this function.
}
\value{
  The value of the deviance extracted from the object \code{object}.
}
\seealso{
  \code{\link{df.residual}},
  \code{\link{extractAIC}},
  \code{\link{glm}},
  \code{\link{lm}}.
}
\keyword{models}
\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}
\name{diag}
\title{Matrix Diagonals}
\synopsis{
diag(x = 1, nrow, ncol = n)
diag(x) <- value
}
\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.}
}
\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. 
}
\seealso{
\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

\testonly{
diag(array(1:4, dim=5))
## test behaviour with 0 rows or columns
diag(0)
z <- matrix(0, 0, 4)
diag(z)
diag(z) <- numeric(0)
z
}
}
\keyword{array}
\name{diff}
\alias{diff}
\alias{diff.default}
\title{Lagged Differences}
\description{
  Returns suitably lagged and iterated differences.
}
\usage{
diff(x, \dots)
diff.default(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 one for
  class \code{\link{ts}} objects.  \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.
}
\seealso{
  \code{\link{diff.ts}}.
}
\examples{
diff(1:10, 2)
diff(1:10, 2, 2)
x <- cumsum(cumsum(1:10))
stopifnot(diff(x, lag = 2) == x[(1+2):10] - x[1:(10 - 2)],
          diff(x, lag = 2) == (3:10)^2,
          diff(diff(x))    == diff(x, differences = 2))
}
\keyword{ts}
\keyword{arith}
\name{difftime}
\alias{difftime}
\alias{print.difftime}
\alias{round.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"))
\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{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.

  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"}.
}
\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)
}
\keyword{utilities}
\keyword{chron}
\name{dim}
\alias{dim}
\alias{dim.data.frame}
\alias{dim<-}
\title{Dimensions of an Object}
\usage{
dim(x)
dim(x) <- values
}
\description{
  Retrieve or set the dimension of an object.
}
\arguments{
  \item{x}{an \R object, for example a matrix, array or data frame.}
}
\details{
  The functions \code{dim} and \code{dim<-} are generic.

  For an array (and hence in particular, for a matrix) they retrieve or
  set the \code{dim} attribute of the object.  It is always
  \code{\link{integer}} or \code{\link{NULL}}.

  \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 ``rows'' and ``columns'').
}
\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}
\name{dimnames}
\title{Dimnames of an Object}
\alias{dimnames}
\alias{dimnames<-}
\alias{dimnames.data.frame}
\alias{dimnames<-.data.frame}
\usage{
dimnames(x)
dimnames(x) <- nlist
}
\description{
  Retrieve or set the dimnames of an object.
}
\arguments{
  \item{x}{an \R object, for example a matrix, array or data frame.}
  \item{nlist}{a list of the length \code{dim(x)} whose components
    are either null or character vectors the length of the appropriate
    dimension of \code{x}.}
}
\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{nlist} 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}}.
}
\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}
\name{discoveries}
\title{Numbers of Important Discoveries}
\usage{data(discoveries)}
\alias{discoveries}
\format{A time series of 100 values.}
\source{
  The World Almanac and Book of Facts, 1975 Edition, pages 315--318.
}
\description{
  The numbers of ``great'' inventions and scientific
  discoveries in each year from 1860 to 1959.
}
\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}
\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.
}
\seealso{
  \code{\link{call}} which creates an unevaluated call.
}
\examples{
do.call("complex", list(imag = 1:3))
}
\keyword{programming}
\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",
         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 to be used.}
  \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{main}{overall title for the plot.}
  \item{xlab}{title for the x axis.}
  \item{ylab}{title for the y axis.}
  \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{
  Cleveland, W. S. (1985)
  \emph{The Elements of Graphing Data.}
  Monterey, CA: Wadsworth.
}
\examples{
data(VADeaths)
dotchart(VADeaths, main = "Death Rates in Virginia - 1940")
dotchart(t(VADeaths), main = "Death Rates in Virginia - 1940")
}
\keyword{hplot}
\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.

  \code{is.double} returns \code{TRUE} or \code{FALSE} depending on
  whether its argument is of double type or not.
}
\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.
}
\seealso{
  \code{\link{integer}}.
}
\examples{
is.double(1)
all(double(3) == 0)
}
\keyword{classes}
\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
    \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 transder 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.

#endif
  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"}.

  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}.
#ifdef windows

  There is an alternative method if you have Internet Explorer 4 or
  later installed.   You can use the flag \code{--internet2}, when
  the `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
}
\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.
}
\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}
\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).
}
\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}
\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}
% file dummy.coef.Rd
% copyright (C) 1998 B. D. Ripley
%
\name{dummy.coef}
\title{Extract Coefficients in Original Coding}
\usage{
dummy.coef(object, \dots)
dummy.coef.lm(object, use.na = FALSE, \dots)
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.
}
\author{B.D. Ripley}

\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 (1997) p.210.
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}
\name{dump}
\title{Text Representations of R Objects}
\usage{
dump(list, file="dumpdata.R", append=FALSE)
}
\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}.}
}
\details{
  At present the implementation of \code{dump} is very
  incomplete and it really only works for functions and
  simple vectors.

  The function \code{\link{save}} is designed to be used for
  transporting \R data between machines.
}
\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}
\name{duplicated}
\alias{duplicated}
\alias{duplicated.default}
\alias{duplicated.data.frame}
\title{Determine Duplicate Elements}
\usage{
duplicated(x, incomparables = FALSE)
}
\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.
}
\arguments{
  \item{x}{an atomic vector or a data fram.e}
  \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.}
}
\details{
  This is a generic function with methods for vectors and data frames.
  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.
}
\seealso{\code{\link{unique}}.}
\examples{
x <- c(9:20, 1:5, 3:7, 0:8)
## extract unique elements
(xu <- x[!duplicated(x)])
stopifnot(xu == unique(x), # but unique(x) is more efficient
          0:20 == sort(x[!duplicated(x)]))

data(iris)
stopifnot(duplicated(iris)[143] == TRUE)
}
\keyword{logic}
\keyword{manip}
\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 `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 ``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 `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
}
\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.
}
\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 libraries.
#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  FALSE
library(mva)
is.loaded(symbol.For("hcass2")) #-> TRUE
\testonly{detach("package:mva")}
}
\keyword{interface}
\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 \code{EDITOR}
    or \code{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.

  \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}
\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 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.
}
\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}.
}
\seealso{\code{\link{data.entry}}, \code{\link{edit}}}
\examples{
\dontrun{
data(InsectSprays)
edit(InsectSprays)
edit(InsectSprays, factor.mode="numeric")
}
}

\keyword{utilities}
% file eff.aovlist.Rd
% copyright (C) 1998 B. D. Ripley
%
\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.
}
\author{B.D. Ripley}
\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 (1997) p.210.
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}
\name{effects}
\title{Effects from Fitted Model}
\usage{
effects(object, \dots)
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 method for
  objects inheriting from class \code{"lm"}.
}
\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).
}
\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 ``corresponding''
  coefficients will be in a different order if pivoting occurred.
}
\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}
\name{eigen}
\alias{eigen}
\alias{La.eigen}
\title{Spectral Decomposition of a Matrix}
\usage{
eigen(x, symmetric, only.values = 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{method}{The LAPACK routine to use in the real symmetric case.}
}
\description{
  Function \code{eigen} computes eigenvalues and eigenvectors by providing an
  interface to the EISPACK routines \code{RS}, \code{RG}, \code{CH}
  and \code{CG}.

  Function \code{La.eigen} uses the LAPACK routines DSYEV/DSYEVR,
  DGEEV, ZHEEV and ZGEEV.
}
\details{
  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{La.eigen} is preferred to \code{eigen} 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.

  Computing the eigenvectors is the slow part for large matrices.

  Using \code{method="dsyevr"} requires IEEE 754 arithmetic.  Should
  this not be supported on your platform, \code{method="dsyev"} is
  used, with a warning.
}
\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)} the choice of length of the
    eigenvectors is not defined by LINPACK. 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{
  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

Meps <- .Machine$double.eps
set.seed(123, kind="default")  # force a particular seed
m <- matrix(round(rnorm(25),3), 5,5)
sm <- m + t(m) #- symmetric matrix
em <- eigen(sm); V <- em$vect
print(lam <- em$values) # ordered DEcreasingly

stopifnot(
 abs(sm \%*\% V - V \%*\% diag(lam))          < 60*Meps,
 abs(sm       - V \%*\% diag(lam) \%*\% t(V)) < 60*Meps)

##------- Symmetric = FALSE:  -- different to above : ---

em <- eigen(sm, symmetric = FALSE); V2 <- em$vect
print(lam2 <- em$values) # ordered decreasingly in ABSolute value !
                         # and V2 is not normalized (where V is):
print(i <- rev(order(lam2)))
stopifnot(abs(lam - lam2[i]) < 60 * Meps)

zapsmall(Diag <- t(V2) \%*\% V2) # orthogonal, but not normalized
print(norm2V <- apply(V2 * V2, 2, sum))
stopifnot( abs(1- norm2V / diag(Diag)) < 60*Meps)

V2n <- sweep(V2,2, STATS= sqrt(norm2V), FUN="/")## V2n are now Normalized EV
apply(V2n * V2n, 2, sum)
##[1] 1 1 1 1 1

## Both are now TRUE:
stopifnot(abs(sm \%*\% V2n - V2n \%*\% diag(lam2))            < 60*Meps,
          abs(sm         - V2n \%*\% diag(lam2) \%*\% t(V2n)) < 60*Meps)

## Re-ordered as with symmetric:
sV <- V2n[,i]
slam <- lam2[i]
all(abs(sm \%*\% sV -  sV \%*\% diag(slam))             < 60*Meps)
all(abs(sm        -  sV \%*\% diag(slam) \%*\% t(sV)) < 60*Meps)
## sV  *is* now equal to V  -- up to sign (+-) and rounding errors
all(abs(c(1 - abs(sV / V)))       <     1000*Meps) # TRUE (P ~ 0.95)

}
\keyword{algebra}
\keyword{array}
\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 assignment 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.
}
\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}
\name{esoph}
\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{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 + codes(tobgp)
                                         + codes(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}
\name{euro}
\alias{euro}
\alias{euro.cross}
\title{Euro Conversion Rates}
\usage{data(euro)}
\description{Conversion rates between the various Euro currencies.}
\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))
\testonly{
 stopifnot(euro == signif(euro,6), 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}
\name{eurodist}
\alias{eurodist}
\title{Distances Between Cities in Europe}
\usage{data(eurodist)}
\description{
  The data give the road distances (in km) between 21 cities in Europe.
  The data are taken from a table in ``The Cambridge Encyclopaedia''.
}
\format{
  A \code{dist} object based on 21 objects.  (You must have the 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}
\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 ``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.
}
\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 dataframes 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}
\name{example}
\title{Run an Examples Section from the Online Help}
\usage{
example(topic, package = .packages(), lib.loc = NULL,
        echo = TRUE, verbose = getOption("verbose"),
        prompt.echo = paste(abbreviate(topic, 6),"> ", sep=""))
}
\alias{example}
\arguments{
  \item{topic}{name or character:  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{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}.}
}
\description{
  Run all the \R code from the \code{Examples} part of \R's online help
  topic \code{topic}.
}
\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.
}
\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(dbinom)
## force use of the standard package eda:
example("smooth", package="eda", lib.loc=.Library)
}
\keyword{documentation}
\keyword{utilities}
\name{exists}
\title{Is an Object Defined?}
\usage{
exists(x, where = -1, envir = parent.frame(),
       frame = NULL, 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.
}
\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}
\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.
}
\author{B.D. Ripley}

\examples{
expand.grid(height = seq(60, 80, 5), weight = seq(100, 300, 50),
            sex = c("Male","Female"))
}
\keyword{models}
\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 e.g. \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}
\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 ``\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.
}
\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}
%-- 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)  
extractAIC.lm (fit, scale = 0, k = 2, \dots)
extractAIC.glm(fit, scale = 0, k = 2, \dots)  
extractAIC.aov(fit, scale = 0, k = 2, \dots)  
extractAIC.coxph  (fit, scale, k = 2, \dots)  
extractAIC.negbin (fit, scale, k = 2, \dots)  
extractAIC.survreg(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 ``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) \bold{A}kaike \bold{I}nformation
  \bold{C}riterion for a fitted parametric model.
}
\details{
  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 generalized linear models (i.e., for \code{\link{lm}},
  \code{\link{aov}}, and \code{\link{glm}}), \eqn{-2\log L} is
  the \emph{deviance}, as computed by \code{\link{deviance}(fit)}, plus
  a constant.
    
  \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 ``\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. (1997)
  \emph{Modern Applied Statistics with S-PLUS.}
  New York: Springer (2nd ed).
}
\seealso{\code{\link{deviance}}, \code{\link{add1}}, \code{\link{step}}}
\examples{
example(glm)
extractAIC(glm.D93)#>>  5  15.129
}
\keyword{models}

\name{factor}
\title{Factors}
\usage{
factor(x, levels = sort(unique(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)
}
\alias{factor}
\alias{ordered}
\alias{is.factor}
\alias{is.ordered}
\alias{as.factor}
\alias{as.ordered}
\alias{is.na<-.factor}
\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.
}
\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")}.

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

  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.
}
\seealso{
  \code{\link{gl}} for construction of ``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)
ff
codes(ff)
factor(ff)# drops the levels that do not occur
factor(factor(letters[7:10])[2:3]) # exercise indexing and reduction
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] <- T
x  # [1] 1    <NA> NA, <NA> used because NA is a level.
is.na(x)
# [1] FALSE  TRUE FALSE
}
\keyword{category}
\keyword{NA}
% file factor.scope.Rd
% copyright (C) 1998 B. D. Ripley
%
\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.
}
\author{B.D. Ripley}

\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}
\name{faithful}
\alias{faithful}
\title{Old Faithful Geyser Data}
\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.}
\description{
  The `faithful' data frame has 272 rows and 2 columns; the waiting
  time between eruptions and the duration of the eruption for the Old
  Faithful geyser in Yellowstone National Park, Wyoming, USA.
}
\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
  ``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 \code{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}
\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{binomial} family admits the links \code{"logit"},
    \code{"probit"}, \code{"log"}, and \code{"cloglog"} (complementary
    log-log);
    the \code{Gamma} family the links \code{"identity"},
    \code{"inverse"}, and \code{"log"};
    the \code{poisson} family the links \code{"identity"}, \code{"log"},
    and \code{"sqrt"};
    the \code{quasi} family 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.

    The other families have only one permissible link function:
    \code{"identity"} for the \code{gaussian} family, and
    \code{"1/mu^2"} for the \code{inverse.gaussian} 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 ``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-PLUS 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.
}
\seealso{
  \code{\link{glm}}, \code{\link{power}}.
}
\examples{
nf <- gaussian()# Normal family
nf
str(nf)# internal STRucture

gf <- Gamma()
gf
str(gf)
gf$linkinv
all(1:10 == gf$linkfun(gf$linkinv(1:10)))# is TRUE
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}
\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{
  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)
all(fft(fft(x), inverse = TRUE)/(x*length(x)) == 1+0i)
eps <- 1e-11 ## In general, not exactly, but still:
for(N in 1:130) {
    cat("N=",formatC(N,wid=3),": ")
    x <- rnorm(N)
    if(N \%\% 5 == 0) {
        m5 <- matrix(x,ncol=5)
        cat("mvfft:",all(apply(m5,2,fft) == mvfft(m5)),"")
    }
    dd <- Mod(1 - (f2 <- fft(fft(x), inverse=TRUE)/(x*length(x))))
    cat(if(all(dd < eps))paste(" all < ", formatC(eps)) else
            paste("NO: range=",paste(formatC(range(dd)),collapse=",")),"\n")
}

plot(fft(c(9:0,0:13, numeric(301))), type = "l")
periodogram <- function(x, mean.x = mean(x)) { # simple periodogram
  n <- length(x)
  x <- unclass(x) - mean.x
  Mod(fft(x))[2:(n\%/\%2 + 1)]^2 / (2*pi*n) # drop I(0)
}
data(sunspots)
plot(10*log10(periodogram(sunspots)), type = "b", col = "blue")
}
\keyword{math}
\keyword{dplot}
\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.
}

\author{B. D. Ripley}

\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}
\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}
\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(...)
}
\arguments{
  \item{\dots}{character vectors containing file names.}
}
\details{
  What is meant by ``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.
}
\author{B. D. Ripley}

\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}
\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 length one.
}
\keyword{file}
\name{file.show}
\alias{file.show}
\title{Display One or More Files}
\description{Display one or more files.}
\usage{
file.show(\dots, header, 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 ``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}
\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)
dir.create(path)
basename(path)
dirname(path)
path.expand(path)
}
\alias{file.append}
\alias{file.copy}
\alias{file.create}
\alias{file.exists}
\alias{file.remove}
\alias{file.rename}
\alias{dir.create}
\alias{basename}
\alias{dirname}
\alias{path.expand}
\arguments{
  \item{\dots, file1, file2, from, to, path}{character vectors,
    containing file names.}
  \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.

  \code{file.create} creates files with the given names if they
  do not already exist and truncates them if they do.
  It returns a logical vector indicating the success or failure
  of the operation for each file.

  \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.  It returns a logical vector indicating whether or
  not it succeeded in removing each file.

  \code{file.rename} attempts to rename a file.  It returns a logical
  value indicating whether the operation succeeded.
#ifdef windows
  On Windows 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{dir.create} creates the last element of the path. It returns a
  logical, true for success.

  \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.  Tilde expansion is done: see the description for
  \code{path.expand} below.

  In both \code{basename} and \code{dirname} trailing file separators
  are removed before dissecting the path, and for \code{dirname} any
  trailing file separators are removed from the result.

  \code{path.expand} expands path(s) by replacing a leading tilde by the
  user's home directory (if defined on that platform).
#ifdef unix
  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
}
\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}}.
}

\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")
unlink("tmp", recursive=TRUE)
file.remove("A", "B", "C")

basename(file.path("","p1","p2","p3","filename"))
dirname(file.path("","p1","p2","p3","filename"))

path.expand("~/foo")
}
\keyword{file}
\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,
               \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 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, \dots}{additional graphical parameters.}
}
\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.  In future it is likely to
    be replaced by a genuine \code{levelplot} function which will
    work 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 plot.axes argument.  An example is given
     below.
}
\seealso{\code{\link{contour}}, \code{\link{image}}, \code{\link{palette}}.}
\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) })
}
\keyword{hplot}
\keyword{aplot}
\name{fitted.values}
\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}.
}
\seealso{
  \code{\link{coefficients}}, \code{\link{glm}}, \code{\link{lm}},
  \code{\link{residuals}}.
}
\keyword{models}
\keyword{regression}
\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}

\name{fix}
\alias{fix}
\title{Fix an Object}
\description{
  \code{fix} invokes the editor specified in
  \code{\link{options}("editor")} 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}{an \R object.}
  \item{\dots}{arguments to pass to editor.}
}
\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 ...
}
\testonly{
 if(machine() != "Macintosh") {
  oo <- options(editor="touch") # not really changing anything
  fix(pi)
  if(!is.numeric(pi) || length(pi)!=1 ||
     !is.null(attributes(pi)) || abs(pi - 3.1415) > 1e-4)
        stop("OOPS:  fix() is broken ...")
  rm(pi); options(oo)
 }
}
}
\keyword{utilities}
\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) <- list
}
\arguments{
  \item{fun}{a function object or a character string naming the function
    to be manipulated.
    If not specified, the function calling \code{body} is used.}
  \item{list}{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.
}
\seealso{
  \code{\link{args}} for a ``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}
\name{format}
\title{Encode in a Common Format}
\usage{
format(x, \dots)
format.AsIs(x, width = 12, \dots)
format.data.frame(x, \dots, justify = "none") 
format.default(x, trim = FALSE, digits = getOption("digits"),
               nsmall = 0, justify = c("left", "right", "none"), \dots)
format.factor(x, \dots)
format.pval(pv, digits = max(1, getOption("digits") - 2),
            eps = .Machine$double.eps, na.form = "NA")
}
\alias{format}
\alias{format.AsIs}
\alias{format.data.frame}
\alias{format.default}
\alias{format.factor}
\alias{format.pval}
\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}. 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{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., does separate formatting for
  fixed, floating point and very small values (those \code{< eps}).

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

\seealso{
  \code{\link{formatC}}, \code{\link{paste}}, \code{\link{as.character}}.
}
\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)

## handling of quotes
zz <- data.frame(a=I("abc"), b=I("def\"gh"))
format(zz)
\testonly{for(i in c(1:5,10,15:17,20)) cat(i,":\t",format(pi,digits=i),"\n")
}
p <- c(47,13,2,.1,.023,.0045, 1e-100)/1000
format.pval(p)
format.pval(p / 0.9)
format.pval(p / 0.9, dig=3)
}
\keyword{character}
\keyword{print}
\name{format.info}
\title{format(.) Information}
\usage{
format.info(x)
}
\alias{format.info}
\arguments{
 \item{x}{(numeric) vector; potential argument of
   \code{\link{format}(x,\dots)}.}
}
\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))

# Reset old options:
options(dd)
}
\keyword{character}
\keyword{print}
\keyword{programming}
\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.  Will be coerced
    to a character vector.}
  \item{y}{a vector of the same length as \code{x} with the
    corresponding descriptions.  Will be coerced to a character vector.}
  \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{
  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))
## Same information in tagged description list style:
writeLines(formatDL(x$Entry, x$Description, style = "list"))
}
\keyword{print}
\name{formatC}
\title{Formatting Using C-style Formats}
\usage{
formatC(x, digits = NULL, width = NULL,
        format = NULL, flag = "", mode = NULL)
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
    number of \emph{significant} digits.  Note that this can lead to
    quite long result strings, see examples below.}

  \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}.}
}
\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}}.
}
\examples{
xx  <- pi * 10^(-5:4)
dd <- options(digits = 4)   # only for format
cbind(format(xx), formatC(xx))
cbind(formatC(xx, wid = 9, flag = "-"))
cbind(formatC(xx, dig = 5, wid = 8, format = "f", flag = "0"))

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
options(dd) # reset
}
\keyword{character}
\keyword{print}
\name{formula}
\title{Model Formulae}
\usage{
y ~ model
formula(x, \dots)
as.formula(object, env=parent.frame())
I(x)
}
\alias{~}
\alias{I}
\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{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}.
}
\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.
}
\seealso{
  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}
\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://hotspur.psych.yorku.ca/ftp/sas/catdata/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}
\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.
}
\seealso{
  \code{\link{plot.window}}, \code{\link{plot.default}}.
}
\keyword{iplot}
\keyword{aplot}
\name{freeny}
\alias{freeny}
\alias{freeny.x}
\alias{freeny.y}
\title{Freeny's Revenue Data}
\usage{data(freeny)}
\description{
  Freeny's data on quarterly revenue and explanatory variables.
}
\format{
  There are three `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.
}
\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}
\name{ftable}
\alias{ftable}
\alias{ftable.default}
\alias{print.ftable}
\title{Flat Contingency Tables}
\description{Create ``flat'' contingency tables.}
\usage{
\method{ftable}{default}(\dots, exclude = c(NA, NaN), row.vars = NULL, col.vars = NULL)
}
\arguments{
  \item{\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 ``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 ``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 ``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}
\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 ``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}
\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, or a series of expressions separated
        by commas.}
}
\details{
    In \R (unlike S) the names in an argument list cannot be quoted
    non-standard names.

    If \code{value} is a series of expressions, the value returned is a
    list of the evaluated expressions, with names set to the expressions
    where these are the names of \R objects.
}
\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}.
}
\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}
\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}
\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.
}
\usage{
gc.time()
}
\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 and 2000 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}
\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}

\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 quoted 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.
}
\seealso{
  \code{\link{exists}}.
}
\examples{
get("\%o\%")
}
\keyword{data}
\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 ``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:
    \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 ``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 ``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{
getNativeSymbolInfo("dansari")

library(mva)
getNativeSymbolInfo(symbol.For("hcass2"))
\testonly{detach("package:mva")}
}
\keyword{interface}
\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.
}
\note{
  \code{getenv} is an alias for backwards compatibility.
}
\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}
\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}.
}
\examples{
(WD <- getwd())
if (!is.null(WD)) setwd(WD)
}
\keyword{utilities}
\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}
\name{glm}
\alias{glm}
\alias{glm.fit}
\alias{glm.fit.null}
\alias{weights.glm}
\title{Fitting Generalized Linear Models}
\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, 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, nrow(x)),
        start = NULL, etastart  =  NULL, mustart = NULL,
        offset = rep(0, nrow(x)),
        family = gaussian(), control = glm.control(),
        intercept = TRUE)
glm.fit.null(x, y, weights = rep(1, nrow(x)),
        start = NULL, etastart  =  NULL, mustart = NULL,
        offset = rep(0, nrow(x)),
        family = gaussian(), control = glm.control(),
        intercept = FALSE)
\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.
    See \code{\link{family}} for details.}

  \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 ``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 (and presently only) method \code{glm.fit}
    uses iteratively reweighted least squares (IWLS).}

  \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).
}
\value{
  \code{glm} returns an object of class \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-null 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.
}
\references{
  McCullagh P. and Nelder, J. A. (1989)
  \emph{Generalized Linear Models.}
  London: Chapman and Hall.

  Dobson, A. J. (1990)
  \emph{An Introduction to Generalized Linear Models.}
  London: Chapman and Hall.

  Venables, W. N. and Ripley, B. D. (1999)
  \emph{Modern Applied Statistics with S-PLUS.}
  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 (1999, pp.217-8)
\testonly{"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 testonly)
\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))

\testonly{
## these are the same -- example from Jim Lindsey
y <- rnorm(20)
y1 <- y[-1]; y2 <- y[-20]
summary(g1 <- glm(y1 - y2 ~ 1))
summary(g2 <- glm(y1 ~ offset(y2)))
Eq <- function(x,y) all.equal(x,y, tol = 1e-12)
stopifnot(Eq(coef(g1), coef(g2)),
          Eq(deviance(g1), deviance(g2)),
          Eq(resid(g1), resid(g2)))
}
}
\keyword{models}
\keyword{regression}
\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-04, maxit=10, 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.
}
\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-15)
options(oo)
coef(glm.D93X) # the last two are closer to 0 than in ?glm's  glm.D93
}
\keyword{optimize}
\keyword{models}

\name{glm.summaries}
\alias{coefficients.glm}
\alias{family.glm}
\alias{fitted.values.glm}
\alias{residuals.glm}
\alias{print.glm}
\alias{print.glm.null}
\title{Accessing Generalized Linear Model Fits}
\usage{
\method{coefficients}{glm}(x) ; \method{coef}{glm}(x)
\method{family}{glm}(object, \dots)
\method{fitted.values}{glm}(x) ; \method{fitted}{glm}(x)
\method{residuals}{glm}(object, type = c("deviance", "pearson", "working",
                      "response", "partial"), \dots)
}
\arguments{
  \item{object, x}{an object of class \code{glm}, typically the result of
    a call to \code{\link{glm}}.}
  \item{test}{a character string, matching one of \code{"Chisq"},
    \code{"F"} or \code{"Cp"}. See \code{\link{stat.anova}}.}
  \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.
}
\seealso{
  \code{\link{glm}} for computing \code{glm.obj}, \code{\link{anova.glm}};
  the corresponding \emph{generic} functions, \code{\link{summary.glm}},
  \code{\link{coefficients}}, \code{\link{deviance}},
  \code{\link{df.residual}},
  \code{\link{effects}}, \code{\link{fitted.values}},
  \code{\link{residuals}}.
}
\keyword{models}
\keyword{regression}

\name{glm.summary}
\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, \dots)

\method{print}{summary.glm}(x, digits = max(3, getOption("digits") - 3),
              na.print = "", symbolic.cor = p > 4,
              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{na.print}{Unused.}
  \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}, ``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
``significance stars'' if \code{signif.stars} is \code{TRUE}.
}
\seealso{
  \code{\link{glm}}, \code{\link{summary}}.
}
\examples{
## --- Continuing the Example from  ``?glm'':%\code{\link{glm}}:
\testonly{example("glm", echo = FALSE)}
summary(glm.D93)
}
\keyword{models}
\keyword{regression}

\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 ``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}
\name{grep}
\title{Pattern Matching and Replacement}
\usage{
grep(pattern, x, ignore.case=FALSE, extended=TRUE, value=FALSE)
sub(pattern, replacement, x,
        ignore.case=FALSE, extended=TRUE)
gsub(pattern, replacement, x,
        ignore.case=FALSE, extended=TRUE)
regexpr(pattern, text,  extended=TRUE)
}
\alias{grep}
\alias{sub}
\alias{gsub}
\alias{regexpr}
\arguments{
\item{pattern}{character string containing a regular expression
  to be matched in the vector of character string \code{vec}.}
\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{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{replacement}{a replacement for matched pattern in
  \code{sub} and \code{gsub}.}
}
\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.
}
\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.

  The regular expressions used are those specified by POSIX 1003.2,
  either extended or basic, depending on the value of the
  \code{extended} argument.
}
\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 -1
    if there is none, with attribute \code{"match.length"} giving the
    length of the matched text (or -1 for no match).
}
\seealso{
  \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)
}
\keyword{character}
\keyword{utilities}
\name{grid}
\title{Add Grid to a Plot}
\usage{
grid(nx = NULL, ny = NULL, col = "lightgray", lty = "dotted")
}
\arguments{
  \item{nx,ny}{number of cells of the grid in x and y direction.
    Defaults to the number of tick marks on the corresponding axis.}
  \item{col}{character or (integer) numeric; color of the grid lines.}
  \item{lty}{character or (integer) numeric; line type of the grid lines.}
}
\alias{grid}
\description{
  \code{grid} adds an \code{nx} by \code{ny} rectangular grid to an
  existing plot, using lines of type \code{lty} and color \code{col}.

  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{
data(iris)
## maybe change the desired number of tick marks:  par(lab=c(mx,my,7))
plot(iris$Sepal.L, iris$Sepal.W, col = rep(1:3, rep(50, 3)),
     xlim = c(4, 8), ylim = c(2, 4.5), panel.first = grid())
}
\keyword{aplot}
\name{help}
\title{Documentation}
\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 mac
     htmlhelp = getOption("htmlhelp"),
#endif
#ifdef windows
     chmhelp = getOption("chmhelp"),
     htmlhelp = getOption("htmlhelp"), winhelp = getOption("winhelp"),
#endif
     pager = getOption("pager"))
?topic
type?topic
}
\alias{help}
\alias{?}
\arguments{
 \item{topic}{a name or character string on which documentation is
   sought (but \emph{not} a variable containing a character string!).}
 \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{help.start}} for details
   of the browsers that are supported. }
#endif
#ifdef mac
  \item{htmlhelp}{logical (or \code{NULL}).  If \code{TRUE}, the HTML
    version of the help will be shown in a browser.}
#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.}
  \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.}
}
\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}.
}
\details{
  In the case of unary and binary operators and control-flow special
  forms, the name 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 \code{R_LATEXCMD} and \code{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
#ifdef mac
  Offline printing is not currently supported by the Macintosh port.
#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}.
}
\seealso{
  \code{\link{help.search}()} for finding help pages on a ``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}
\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 regular expression in the (file) name, alias, title, or keyword
  entries (or any combination thereof).  Topics and titles of the
  matched help entries are nicely displayed.
}
\usage{
help.search(pattern, fields = c("alias", "title"),
            apropos, keyword, whatis, ignore.case = TRUE,
            package = NULL, lib.loc = NULL,
            help.db = getOption("help.db"),
            verbose = getOption("verbose"),
            rebuild = FALSE)
}
\arguments{
  \item{pattern}{a character string containing a regular expression 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{"alias"}, \code{"title"}, and \code{"keyword"},
    corresponding to the help page's (file) name, the topics it provides
    documentation for, its title, and the keywords it can be classified
    to.}
  \item{apropos}{a character string containing a regular expression to
    be matched in the help page topics and title.}
  \item{keyword}{a character string containing a regular expression to
    be matched in the help page keywords.}
  \item{whatis}{a character string containing a regular expression 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 specified library trees \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.}
}
\details{
  Upon installation of a package, the Perl script \file{Rd2contents.pl}
  creates a \file{CONTENTS} data base which contains the information on
  name, aliases, title and keywords (as well as the URL of the HTML
  version of the help file) in Debian Control Format.  This 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
\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.
}
}
\keyword{documentation}
\name{help.start}
\title{Hypertext Documentation}
\usage{
#ifdef unix  
help.start(gui = "irrelevant", browser = getOption("browser"), remote = NULL)
#endif
#ifdef windows  
help.start(update = TRUE, gui = "irrelevant", browser = "irrelevant")
#endif
}
\alias{help.start}
\arguments{
  \item{gui}{just for compatibility with S-PLUS.}
  \item{browser}{the name of the program to be used as hypertext browser.}
#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
}
\description{
  Start the hypertext (currently HTML) version of \R's online documentation.
}
\details{
#ifdef unix
  All the packages in the known library trees are linked to a directory
  \code{.R} in the user's home directory.

  The \code{browser} needs to work with a \code{"-remote openURL(...)"}
  call. Then, the hypertext \R help interface is opened in any already
  running browser or a new one if necessary.  Browsers that support this
  interface include Netscape 4.x, 6.2 (but not 6.0/1), Opera 5 and
  Mozilla 0.9.5.

  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.
#endif
}

#ifdef unix
\note{
  As a side-effect, the variable \code{"help.start.has.been.run"} in the
  environment \code{"package:base"} is set to true.
}
#endif

\seealso{
  \code{\link{help}()} for on- and off-line help in ASCII/Editor or
  PostScript format.
}
\examples{
\dontrun{help.start()}
}
\keyword{documentation}
\name{hist}
\title{Histograms}
\usage{
hist(x, \dots)
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 an 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
    (``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 `x[i]' equal to the `breaks' value will be included in the first
    (or last, for \code{right = FALSE}) bar.}
  \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 `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 foregound 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.}
  \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{class} "histogram"} is plotted by
  \code{\link{plot.histogram}}, before it is returned.
}
\details{
  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
  ``\emph{include highest}''.

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

\references{
  Venables, W. N. and Ripley. B. D. (1999)
  \emph{Modern Applied Statistics with S-PLUS}.  Springer.
}

\seealso{
  \code{\link{nclass.Sturges}}, \code{\link{stem}},
  \code{\link{density}}.
}

\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}
\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
    ``hue'', ``saturation'' and ``value'' to be combined to form a
    vector of colors.  Values in shorter arguments are recycled.}
  \item{gamma}{a ``gamma correction''}
}
\value{
  This function creates a vector of ``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}.
}
\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}
\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.

 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 ``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.

}
\value{
  A single logical value, \code{TRUE} or
  \code{FALSE}, never \code{NA} and never anything other than a single value.
}
\author{ John Chambers}

\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
\testonly{x <- 1.; y <- .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
}
\keyword{ programming }
\keyword{ logic }
\keyword{  iteration }
\name{identify}
\title{Identify Points in a Scatter Plot}
\usage{
identify(x, \dots)
identify.default(x, y = NULL, labels = seq(along = x), pos = FALSE,
                 n = length(x), plot = TRUE, offset = 0.5, \dots)
}
\alias{identify}
\alias{identify.default}
\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 `Stop' from the menu, or from the `Stop' menu on the
graphics window.
#endif
#ifdef mac
The identification process is terminated by clicking outside the
graphics window.
#endif
 
  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.
}
\seealso{
  \code{\link{locator}}
}
\keyword{iplot}
\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}.}
}
\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}
\name{image}
\alias{image}
\alias{image.default}
\title{Display a Color Image}
\usage{
image(x, \dots)
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} ``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 `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 ``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{contour}},
  \code{\link{heat.colors}}, \code{\link{topo.colors}},
  \code{\link{terrain.colors}}, \code{\link{rainbow}},
  \code{\link{hsv}}, \code{\link{par}}.
}
\examples{
\testonly{
## Degenerate, should still work
image(as.matrix(1))
image(matrix(pi,2,4))
x <- seq(0,1,len=100)
image(x, 1, matrix(x), col=heat.colors(10))
image(x, 1, matrix(x), col=heat.colors(10), oldstyle = TRUE)
image(x, 1, matrix(x), col=heat.colors(10), breaks = seq(0.1,1.1,len=11))
}
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}
\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}
\name{infert}
\title{Infertility after Spontaneous and Induced Abortion}
\usage{data(infert)}
\alias{infert}
\description{
  This is a matched case-control study dating from before the
  availability of conditional logistic regression.
}
\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 equivalent to a Cox model :
if(require(survival)){
  faketime <- rep(42,nrow(infert))
  model3 <- coxph(Surv(faketime,case)~spontaneous+induced+strata(stratum),
                data=infert,method="exact")
  summary(model3)
  detach()# survival (conflicts)
}
}
\keyword{datasets}
\name{influence.measures}
\alias{influence.measures}
\alias{print.infl}
\alias{summary.infl}

\alias{hat}
\alias{rstandard}
\alias{rstudent}
\alias{dfbetas}
\alias{dffits}
\alias{covratio}
\alias{cooks.distance}
\title{Regression Diagnostics}
\usage{
influence.measures(lm.obj)

rstandard(lm.obj,
          infl = lm.influence(lm.obj),
          res = weighted.residuals(lm.obj),
          sd = sqrt(deviance(lm.obj)/df.residual(lm.obj)))
rstudent (lm.obj, infl = \dots, res = \dots)
dffits   (lm.obj, infl = \dots, res = \dots)
dfbetas  (lm.obj, infl = \dots)
covratio (lm.obj, infl = \dots, res = \dots)
cooks.distance(lm.obj, infl = \dots, res = \dots, sd = \dots)

hat(x, intercept = TRUE)
}
\arguments{
  \item{lm.obj}{the resulting object returned by \code{\link{lm}}.}

  \item{infl}{influence structure as returned by \code{\link{lm.influence}}.}
  \item{res}{(possibly weighted) residuals, with proper default.}
  \item{sd}{standard deviation to use, see default.}

  \item{x}{the \eqn{X} or design matrix.}
  \item{intercept}{should an intercept column be pre-prended to \code{x}?}
}
\description{
  This suite of functions can be used to compute some of the regression
  diagnostics discussed in Belsley, Kuh and Welsch (1980), and in Cook
  and Weisberg (1982).
}
\details{
  The primary 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.)

  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}}) 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 it for the
  cases excluded during fitting.

  The function \code{hat()} exists mainly for S (version 2) compatibility.
}
\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.
}
\seealso{\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)
summary(inflm.SR <- influence.measures(lm.SR))
inflm.SR
which(apply(inflm.SR$is.inf, 1, any)) # which observations `are' influential
dim(dfb <- dfbetas(lm.SR))            # the 1st columns of influence.measures
all(dfb == inflm.SR$infmat[, 1:5])
rstandard(lm.SR)
rstudent(lm.SR)
dffits(lm.SR)
covratio(lm.SR)

## 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))
influence.measures(lmH)
}
\keyword{regression}
\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).

  \code{is.integer} returns \code{TRUE} or \code{FALSE} depending on
  whether its argument is of integer type or not. 
}
\keyword{classes}
\name{integrate}
\alias{integrate}
\alias{print.integrate}
\title{Integration of One-Dimensional Functions}
\description{
  Adaptive quadrature of functions of one variable over a finit 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, ...)
}
\arguments{
  \item{f}{An \R function taking a numeric first argument and returning
    a numeric vector the same length. Returning a non-finite 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 passes to \code{f}.}
}
\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}.
}
\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\\
  R. Piessens, E. deDoncker-Kapenga, C. Uberhuber, D. Kahaner
  \emph{Quadpack: a Subroutine Package for Automatic Integration.}
  Springer Verlag, 1983.
}

\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)
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
}
\keyword{math}
\keyword{utilities}

\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.}
  \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.
}
\seealso{\code{\link{factor}}.}%% even more ":" for factors!

\examples{
a <- gl(2, 2, 8)
b <- gl(2, 4, 8)
interaction(a, b)
}
\keyword{category}
\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, ylab, ylim, lty, col = 1,
                 pch = c(1:9, 0, letters), \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}{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}{the x label of the plot.}  
  \item{ylab}{the y label of the plot.}
  \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{\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.
}

\examples{
data(ToothGrowth)
attach(ToothGrowth)
interaction.plot(dose, supp, len, fixed=TRUE)
dose <- ordered(dose)
interaction.plot(dose, supp, len, fixed=TRUE)
detach()

data(OrchardSprays)
attach(OrchardSprays)
interaction.plot(treatment, rowpos, decrease)
interaction.plot(rowpos, treatment, decrease)
## order the rows by their mean effect
rowpos <- factor(rowpos, levels=sort.list(tapply(decrease, rowpos, mean)))
interaction.plot(rowpos, treatment, decrease)
detach()

data(esoph)
attach(esoph)
interaction.plot(agegp, alcgp, ncases/ncontrols)
interaction.plot(agegp, tobgp, ncases/ncontrols, trace.label="tobacco",
                 fixed=TRUE)
detach()
}
\keyword{hplot}
\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}
\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.
}
\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}
\name{iris}
\alias{iris}
\alias{iris3}
\title{Edgar Anderson's Iris Data}
\usage{
data(iris)
data(iris3)
}
\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}.
}
\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.
}
\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}
\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}
\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 or not.

\code{Inf} and \code{-Inf} are positive and negative `infinity' whereas
\code{NaN} means ``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}).

\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}).
}
\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}, see the many
    examples below.
}
\seealso{\code{\link{NA}}, \emph{`Not Available'} which is not a number
    as well, however usually used for missing values.
}
\references{
%%- better ones ?!??
    ANSI/IEEE 754 Floating-Point Standard.

    Currently (6/1999), Bill M.'s \email{billm@melbpc.org.au} tutorial
    and examples at \cr \url{http://www.linuxsupportline.com/~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
)
exp(-Inf) == 0
##              (actually, the last one seems to give NA on not-very-new
##               versions of Linux, which is a Linux bug and seems to be
##               corrected in newer 'libc6' based Linuxen).

stopifnot(
    is.na(0/0),
    !is.na(Inf),
    is.nan(0/0),

    !is.nan(NA)  &&  !is.infinite(NA)  && !is.finite(NA),
     is.nan(NaN) &&  !is.infinite(NaN) && !is.finite(NaN),
    !is.nan(c(1,NA)),
    c(FALSE,TRUE,FALSE) == is.nan(c   (1,NaN,NA)),
    c(FALSE,TRUE,FALSE) == is.nan(list(1,NaN,NA))#-> FALSE in older versions
)

\testonly{
 ( weird.values <- c(-20.9/0, 1/0, 0/0, NA) )

 Mmax <- .Machine$double.xmax
 Mmin <- .Machine$double.xmin
 ( X.val <- c(Mmin*c(2^(-10:3),1e5,1e10),
              Mmax*c(1e-10,1e-5,2^(-3:0),1.001)) )
 ( tst.val <- sort(c(X.val, weird.values), na.last = TRUE) )
 ( x2 <- c(-1:1/0,pi,1,NA) )
 ( z2 <- c(x2, 1+1i, Inf -Inf* 1i) )

 is.inf <-
   function(x) (is.numeric(x) || is.complex(x)) && !is.na(x) && !is.finite(x)

 for(x in list(tst.val, x2, z2))
   print(cbind(format(x), is.infinite=format(is.infinite(x))), quote=FALSE)

 rbind(is.nan(tst.val),
       is.na (tst.val))
 tst.val [ is.nan(tst.val) !=  is.na(tst.val) ]
}
lgamma(Inf) == Inf
Inf + Inf == Inf
Inf - Inf == NaN # NA --- should test with  'is.nan()

(1/0) * (1/0)# Inf
(1/0) / (1/0)# NaN

pm <- c(-1,1) # 'pm' = plus/minus

log(0) == - 1/0
exp(-Inf) == 0

sin(Inf)
cos(Inf)
tan(Inf)
all(atan(Inf*pm) == pm*pi/2) # TRUE


x <- c(100,-1e-13,Inf,-Inf, NaN, pi, NA)
x #  1.000000 -3.000000       Inf      -Inf        NA  3.141593        NA
names(x) <- formatC(x, dig=3)
is.finite(x)
##-   100 -1e-13 Inf -Inf NaN 3.14 NA
##-     T      T   .    .   .    T  .
is.na(x)
##-   100 -1e-13 Inf -Inf NaN 3.14 NA
##-     .      .   .    .   T    .  T
which(is.na(x) & !is.nan(x))# only 'NA': 7

is.na(x) | is.finite(x)
##-   100 -1e-13 Inf -Inf NaN 3.14 NA
##-     T      T   .    .   T    T  T
is.infinite(x)
##-   100 -1e-13 Inf -Inf NaN 3.14 NA
##-     .      .   T    T   .    .  .

##-- either  finite or infinite  or  NA:
all(is.na(x) != is.finite(x) | is.infinite(x)) # TRUE
all(is.nan(x) != is.finite(x) | is.infinite(x)) # FALSE: have 'real' NA

##--- Integer
(ix <- structure(as.integer(x),names= names(x)))
##-   100 -1e-13    Inf   -Inf    NaN   3.14     NA 
##-   100      0     NA     NA     NA      3     NA 
all(is.na(ix) != is.finite(ix) | is.infinite(ix)) # TRUE (still)

ix[3] == (iI <- as.integer(Inf))#> warning: NAs introduced by coercion 
ix[4] == (imI<- as.integer(-Inf))
iI  == .Machine$integer.max # TRUE
imI == -.Machine$integer.max # TRUE

##--- Overflow in simple integer arithmetic:
as.integer(2)*iI #  -2
as.integer(3)*iI #  2147483645
as.integer(3)*iI == iI-2 # TRUE

storage.mode(ii <- -3:5)
storage.mode(zm <- outer(ii,ii, FUN="*"))# integer
storage.mode(zd <- outer(ii,ii, FUN="/"))# double
range(zd, na.rm=TRUE)# -Inf  Inf
zd[,ii==0]

(storage.mode(print(1:1 / 0:0)))# Inf "double"
(storage.mode(print(1:1 / 1:1)))# 1 "double"
(storage.mode(print(1:1 + 1:1)))# 2 "integer"
(storage.mode(print(2:2 * 2:2)))# 4 "integer"
}
\keyword{programming}
\keyword{math}
\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.}
}
\value{\code{TRUE} if \code{x} is a function, and \code{FALSE}
  otherwise.}
}
\keyword{programming}
\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.}
}
\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}
\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.}
}
\seealso{\code{\link{class}}, and \code{\link{methods}}.}

\examples{
is.object(1) # FALSE
is.object(as.factor(1:3)) # TRUE
}
\keyword{methods}
\keyword{classes}
\name{is.recursive}
\title{Is an Object Atomic or Recursive?}
\usage{
is.atomic(x)
is.recursive(x)
}
\alias{is.atomic}
\alias{is.recursive}
\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.}
}
\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)        #   "
is.a.r(y ~ x)     #   "
is.a.r(expression(x+1))# should be F-T (not in 0.62.3!)
}
\keyword{programming}
\keyword{classes}
\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.}
}
\keyword{classes}
\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}
\name{islands}
\alias{islands}
\title{Areas of the World's Major Landmasses}
\usage{data(islands)}
\format{A named vector of length 48.}
\source{The World Almanac and Book of Facts, 1975, page 406.}
\description{
  The areas in thousands of square miles of the landmasses which exceed
  10,000 square miles.
}
\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}
\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.
}
\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}
% file kappa.Rd
% copyright (C) 1998 B. D. Ripley
%
\name{kappa}
\title{Estimate the Condition Number}
\usage{
kappa(z, \dots)
kappa.lm     (z, \dots)
kappa.default(z, exact = FALSE, \dots)
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.
}
\value{
    The condition number, \eqn{kappa}, or an approximation if
    \code{exact=FALSE}.  
}
\author{B.D. Ripley}
\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}
\name{kronecker}

\title{Kronecker products on arrays}

\usage{
kronecker(X, Y, FUN = "*", make.dimnames = FALSE, ...)
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{Matrix Algebra Useful for Statistics, Shayle
R. Searle, John Wiley and Sons, 1982.}

\author{Jonathan Rougier, \email{J.C.Rougier@durham.ac.uk}}

\seealso{\code{\link{outer}}, on which \code{kronecker} is built
and \code{\link{matmult}} for usual matrix multiplication.}

\examples{
# simple scalar multiplication
( M <- matrix(1:6, ncol=2) )
stopifnot(kronecker(4, M)==4 * M)
# Block diagonal matrix:
stopifnot(kronecker(diag(1, 3), M) == diag(1, 3) \%x\% 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)

\testonly{

# dimnames are hard work: let's test them thoroughly

dimnames(bill) <- NULL
kronecker(fred, bill, make=TRUE)
kronecker(bill, fred, make=TRUE)

dim(bill) <- c(2, 2, 1)
dimnames(bill) <- list(c("happy", "sad"), NULL, "")
kronecker(fred, bill, make=TRUE)

bill <- array(1:24, c(3, 4, 2))
dimnames(bill) <- list(NULL, NULL, c("happy", "sad"))
kronecker(bill, fred, make=TRUE)
kronecker(fred, bill, make=TRUE)

fred <- outer(fred, c("frequentist"=4, "bayesian"=4000))
kronecker(fred, bill, make=TRUE)
}
}

\keyword{array}
% file labels.Rd
% copyright (C) 1998 B. D. Ripley
%
\name{labels}
\title{Find Labels from Object}
\usage{
labels(object, \dots)
labels.default(object, \dots)
labels.terms(object, \dots)
labels.lm(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.
}
\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.
}
\author{B.D. Ripley}
\keyword{print}
\keyword{models}
\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)
}
\alias{lapply}
\alias{sapply}
\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.}
}
\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 ``user-friendly'' version of \code{lapply} also
  accepting vectors as \code{X}, and returning a vector or array with
  \code{dimnames} if appropriate.
}
\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)
}
\keyword{iteration}
\keyword{list}
\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}
\name{legend}
\alias{legend}
\title{Add Legends to Plots}
\usage{
legend(x, y, legend, fill, 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 = 0,
       text.width = NULL, merge = do.lines && has.pch, trace = FALSE,
       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 location of the legend.
    \code{x} can be a list with \code{x} and \code{y} components.}
%% if argument \code{y} is missing.
%S: location of the rectangle in which to put the legend.
%S: If x & y are length 1, they determine the top left corner of the rectangle;
%S: if .. length 2 vectors, they give opposite corners of the rectangular area.
%S: A list containing x and y values may be supplied.
  \item{legend}{a vector of text values or an \code{\link{expression}}
    of length \eqn{\ge 1}{>= 1} to appear in the legend.}
  \item{fill}{if specified, this argument will cause boxes filled
    with 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.}
  \item{bty}{the type of box to be drawn around the legend.}
  \item{bg}{the background color for the legend box.}
  \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}, ``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{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{
 ``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.
}
\value{
  A (\code{\link{invisible}}) 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).}
    }
  }
}
\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')

##--- 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:  ------------------------------
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, col=2:3, adj = c(0, .6)))# adj y !

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))

## 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}
\name{length}
\title{Length of a Vector or List}
\usage{
length(x)
length(x) <- n
}
\alias{length}
\alias{length<-}
\arguments{
  \item{x}{a vector or list.}
  \item{n}{an integer.}
}
\description{
  Get or set the length of vectors (including lists).
}
\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{
  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.
}
\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}

\name{levels}
\title{Levels Attributes}
\usage{
levels(x)
levels(x) <- value
}
\alias{levels}
\alias{levels<-}
\alias{levels<-.default}
\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.}
}
\seealso{\code{\link{levels<-.factor}}, \code{\link{nlevels}}.
}
\keyword{category}
\name{levels.factor}
\title{Factor Levels Assignment}
\usage{
levels(x) <- value
}
\alias{levels<-.factor}
\description{
\code{levels<-} provides a way to alter the levels attribute of factor.
\code{value} can be a vector of character strings with length equal to
the number of levels of \code{x}, or a named list specifying how to
rename the levels.
}
\seealso{
\code{\link{factor}}, \code{\link{levels}},
\code{\link{levels<-}}, \code{\link{nlevels}}.
}
\examples{
# assign individual levels
x <- gl(2, 4, 8)
levels(x)[1] <- "low"
levels(x)[2] <- "high"

# or as a group
y <- gl(2, 4, 8)
levels(y) <- c("low", "high")

# combine some levels
z <- gl(3, 2, 12)
levels(z) <- c("A", "B", "A")

# same, using a named list
z <- gl(3, 2, 12)
levels(z) <- list(A=c(1,3), B=2)
}
\keyword{category}
\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{.lib.loc}
\alias{.libPaths}
\alias{print.libraryIQR}
\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, lib.loc = NULL, character.only = FALSE,
        logical.return = FALSE, warn.conflicts = TRUE,
        keep.source = getOption("keep.source.pkgs"),
        verbose = getOption("verbose"))
require(package, quietly = FALSE, warn.conflicts = TRUE,
        keep.source = getOption("keep.source.pkgs"))

.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, use.attached, quiet = FALSE,
              verbose = getOption("verbose"))
.libPaths(new)

.Library
.Autoloaded
}
\arguments{
  \item{package, help}{\link{name} or character string giving the name
    of a package.}
  \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{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 ``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}, a warning will not be
    printed if the package cannot be found.}
  \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{use.attached}{a logical indicating whether attached packages
    should be considered in addition to the ones installed in the given
    libraries.}
  \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 optionally gives a
  warning, rather than giving an error, 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.

  \code{library(help = somename)} prints information on the package
  \code{somename}, typically by listing the most important user level
  objects it contains.

  \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 ``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
  ``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 ``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.
  Argument \code{use.attached} is deprecated.  This function is not
  meant to be called by users, and its interface might change in future
  versions.

  \code{.Autoloaded} contains the ``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 \code{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.  The library search path is initialized at startup from the
  environment variable \code{R_LIBS} (which should be a
#ifdef unix
  colon-separated
#endif
#ifdef windows
  semicolon-separated
#endif
  list of directories at which \R library trees are rooted) by calling
  \code{.libPaths} with the directories specified in \code{R_LIBS}. 
  Currently, the global variable \code{.lib.loc} is used for storing the
  paths to the known library trees; however, this variable should not be
  accessed directly.
}
\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.
}
\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}},
  \code{\link{INSTALL}}, \code{\link{REMOVE}}.
}
\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()))

.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)
}}
}
\keyword{data}
\name{library.dynam}
\alias{library.dynam}
\alias{.Dyn.libs}
\title{Loading Shared Libraries}
\usage{
library.dynam(chname, package = .packages(), lib.loc = NULL,
              verbose = getOption("verbose"), file.ext, \dots)
}
\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{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.}
}
\description{
  Load the specified file of compiled code if it has not been loaded already.
}
\details{
  This 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}()}.  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.
}
\value{
  The \code{.Dyn.libs} vector with the names of packages
  which have used \code{library.dynam} in the current \R session.

  It is returned as \code{\link{invisible}}, unless the \code{chname}
  argument is missing.

  Users should never set \code{.Dyn.libs} directly.
}
\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
}
\examples{
library.dynam()# which packages have been ``dynamically loaded''
}
\keyword{data}
\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}
\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)
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.}
  \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.
}
\seealso{
  \code{\link{points}},
  \code{\link{plot}},
  and the underlying ``primitive'' \code{\link{plot.xy}}.
}
\examples{
data(cars)
# draw a smooth line through a scatter plot
plot(cars, main="Stopping Distance versus Speed")
lines(lowess(cars))
}
\keyword{aplot}
\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.

  An empty pairlist, \code{pairlist()} is the same as \code{NULL}.  This
  is different from \code{list()}.
}
\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}
\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)
       dir(path = ".", pattern=NULL, all.files=FALSE, full.names=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.}
}
\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}
\note{
  File naming conventions are very platform dependent.
}
\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}
\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 ``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, defaulting to
    \code{TRUE}. \emph{\code{FALSE} is not yet implemented}.}

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

  \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{class}} \code{"lm"} or for
  multiple responses of class \code{c("mlm", "lm")}.
%% actually also c("lm.null","lm") and c("mlm.null", "lm.null", "mlm", "lm")
%% but I'm still not sure that this should be `it' for the future. {MM}.

  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.
}
\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}
\name{lm.influence}
\title{Regression Diagnostics}
\usage{
lm.influence(lm.obj)
}
\alias{lm.influence}
\arguments{
\item{lm.obj}{an object as returned by \code{\link{lm}}.}
}
\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.
}
\value{
  A list containing the following components:
  \item{hat}{a vector containing the diagonal of the ``hat'' matrix.}
  \item{coefficients}{the change in the estimated coefficients which results
    when the i-th case is dropped from the regression is contained in
    the i-th row of this 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.}
}
\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.

  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{
  Belsley, D. A., Kuh, E. and Welsch, R. E. (1980)
  \emph{Regression Diagnostics.}
  New York: Wiley.
}
\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}
\name{lm.summaries}
\alias{coefficients.lm}
\alias{family.lm}
\alias{formula.lm}
\alias{fitted.values.lm}
\alias{residuals.lm}
\alias{weights}
\alias{weights.lm}
\alias{weights.default}
\title{Accessing Linear Model Fits}
\usage{
\method{coefficients}{lm}(object, \dots) ; \method}{lm}{coef(object, \dots)
\method{family}{lm}(object, \dots)
\method{formula}{lm}(x, \dots)
\method{fitted.values}{lm}(object, \dots)
\method{residuals}{lm}(object,
          type=c("working","response", "deviance","pearson", "partial"), \dots)
weights(object, \dots)
}
\arguments{
  \item{object, x}{an object of class \code{lm}, usually, a result of a
    call to \code{\link{lm}}.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\description{
All these functions are \code{\link{methods}} for class \code{"lm"}  objects.
}
\details{
The generic accessor functions \code{coefficients}, \code{effects},
\code{fitted.values} and \code{residuals} can be used to extract
various useful features of the value returned by \code{lm}.
}
\seealso{
  The model fitting function \code{\link{lm}}, \code{\link{anova.lm}}.

  \code{\link{coefficients}}, \code{\link{deviance}},
  \code{\link{df.residual}},
  \code{\link{effects}}, \code{\link{fitted.values}},
  \code{\link{glm}} for \bold{generalized} linear models,
  \code{\link{lm.influence}} for regression diagnostics,
  \code{\link{weighted.residuals}},
  \code{\link{residuals}}, \code{\link{residuals.glm}},
  \code{\link{summary.lm}}.
}
\examples{
\testonly{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}
\name{lm.summary}
\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, \dots)

\method{print}{summary.lm}(x, digits = max(3, getOption("digits") - 3),
      symbolic.cor = p > 4,
      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}, ``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
``significance stars'' if \code{signif.stars} is \code{TRUE}.
}
\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.}
  \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*)}.}
  \item{fstatistic}{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 ``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
    \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.}
}
\seealso{
  The model fitting function \code{\link{lm}}, \code{\link{summary}}.
}
\examples{
\testonly{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}
\name{lm.fit}
\title{Fitter Functions for Linear Models}
\usage{
lm.fit (x, y,    offset = NULL, method = "qr", tol = 1e-7, \dots)
lm.wfit(x, y, w, offset = NULL, method = "qr", tol = 1e-7, \dots)
lm.fit.null (x, y,    method = "qr", tol = 1e-7, \dots)
lm.wfit.null(x, y, w, method = "qr", tol = 1e-7, \dots)
}
\alias{lm.fit}
\alias{lm.wfit}
\alias{lm.fit.null}
\alias{lm.wfit.null}
\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{\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}{\code{n} vector; \dots\dots}%% FIXME
  \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}
%% these two *not* for the  lm*fit.null() functions:
  \item{qr}{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))

str(lm0 <-  lm.fit.null (x=X, y=y))
str(lmw0 <- lm.wfit.null(x=X, y=y,w=w))

%% do an example which sets `tol' and gives a difference!
}
\keyword{regression}
\keyword{array}
\name{load}
\title{Reload Saved Datasets}
\alias{load}
\description{
  This function will reload the datasets written to a file with the
  function \code{save}.
}
\usage{
load(file, envir = parent.frame())
}
\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.}
}
\seealso{
  \code{\link{save}}.
}
\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 workspace
load("all.Rdata", .GlobalEnv)
}
\keyword{file}
\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{locales}} 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}
\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_COLLATE"} and  \code{"LC_CTYPE"}, 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 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{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}
\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 `Stop' from the menu, or from the `Stop' menu on the
graphics window.
#endif
#ifdef mac
The identification process can be terminated by clicking outside 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.

  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.
}
\seealso{
  \code{\link{identify}}
}
\keyword{iplot}
% from nls,  logLik.Rd,v 1.1 1999/11/12 13:34:35 bates
\name{logLik}
\title{Extract Log-Likelihood}
\usage{
logLik(object, ...)

\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{lm}, \code{nls} in package \bold{nls},
  and \code{gls}, \code{lme} and others in package \bold{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[nls]{logLik.nls}},
  \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}
\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.
}
\seealso{\code{\link{glm}}, \code{\link{logLik.lm}}}
\examples{
\testonly{example("glm", echo = FALSE)}
##-- Continuing the  glm(.) example:
Eq <- function(x,y) all.equal(x,y, tol = 1e-12)
stopifnot(Eq(AIC(anorex.1), anorex.1$aic),
          Eq(AIC(g1), g1$aic),
          Eq(AIC(g2), g2$aic))
}
\keyword{models}
% from nlme, was logLik.lm.Rd,v 1.4 2000/07/03 18:22:47 bates 
\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{
  the (restricted) log-likelihood of the linear model represented by
  \code{object} evaluated at the estimated coefficients.
}
\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)

Nnlme <- is.na(match("package:nlme", search()))
if(require(nlme)) {
  data(Orthodont)
  fm1 <- lm(distance ~ Sex * age, Orthodont)
  print(logLik(fm1))
  print(logLik(fm1, REML = TRUE))
  if(Nnlme) detach( "package:nlme")
}
}
\keyword{models}
\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 ``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.
}
\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}}.

  \code{is.logical} returns \code{TRUE} or \code{FALSE} depending on
  whether its argument is of logical type or not.
}
\keyword{classes}
\keyword{logic}
\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 ``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 `[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 ``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 `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{
  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}
\name{longley}
\alias{longley}
\title{Longley's 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:}{`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.
}
\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}
\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 <- ma <- matrix(1:20, 4, 5)
m2[lower.tri(m2)] <- NA
m2
stopifnot(lower.tri(ma) == !upper.tri(ma, diag=TRUE))
}
\keyword{array}
\name{lowess}
\title{Scatter Plot Smoothing}
\usage{
lowess(x, y, f=2/3, iter=3, delta=.01*diff(range(x)))
}
\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 replaced by a single value in the output from \code{lowess}.}
}
\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{
  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 \code{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}
\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
    ``.'' 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}.
}
\seealso{
  \code{\link{apropos}} (or \code{\link{find}}) for finding objects in the
  whole search path; \code{\link{grep}} for more details on ``regular
  expressions''; \code{\link{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}
\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{
\testonly{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}
\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}
\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 matrix valued 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}{an unused parameter for compatibility.}
}
\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 (stated below).}
\item{residuals}{residuals from the fit.}
\item{intercept}{indicates whether an intercept was fitted.}
\item{qr}{the QR decomposition of the design matrix.}
}
\seealso{
\code{\link{lm}} which usually is preferable;
\code{\link{ls.print}}, \code{\link{ls.diag}}.
}
\examples{
\testonly{example("lm", echo = FALSE)}
##-- Using the same data as the lm(.) example:
lsD9 <- lsfit(x = codes(gl(2,10)), y = weight)
ls.print(lsD9)
}
\keyword{regression}
\name{machine}
\title{Determine the Machine R is Running On}
\usage{
machine()
}
\alias{machine}
\description{
  This function returns a character string which specifies what kind of
  environment \R is being run in.
}
\seealso{
  \code{\link{.Platform}} which provides more than \code{machine()};
  \code{\link{Machine}} for the computer's characteristics in arithmetics;
}
\examples{
machine()# to see yours
tolower(machine()) == .Platform $ OS ## --> often TRUE
if (machine() == "Macintosh")
  cat("You are using a Macintosh computer\n")
}
\keyword{environment}
\keyword{programming}
\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 ``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 ``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 ``low'' or ``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}

\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))) == apply(x*x, 1, sum))
	##- Here, D^2 = usual Euclidean distances
Sx <- cov(x)
D2 <- mahalanobis(x, apply(x, 2, mean), 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}
\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}

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

  All invalid characters are translated to \code{"."}.
}
\seealso{
  \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.b1"

all(make.names(letters) == letters)# TRUE

data(state)
state.name[make.names(state.name) != state.name]# those 10 with a space
}
\keyword{character}
\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}
\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}
\name{manova}
\alias{manova}
\title{Multivariate Analysis of Variance}
\description{
  A class of 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.
}
\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.
}
\author{B.D. Ripley}

\seealso{
  \code{\link{aov}}, \code{\link{summary.manova}}, the latter containing
  examples.
}
\keyword{models}
\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}
\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}
\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.}
  \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}: A numeric 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.
}
\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}
\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}
\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}.
}
\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}
\name{match.fun}
\alias{match.fun}
\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.
}
\title{Function Verification for ``Function Variables''}
\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}
\name{matmult}
\title{Matrix Multiplication}
\usage{
a \%*\% b
}
\alias{\%*\%}
\alias{matmult}
\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.
}
\value{
  The matrix product.  Use \code{\link{drop}} to get rid of dimensions
  which have only one level.
}
\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}
\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.
}
\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}
\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.
}
\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.
}
\seealso{\code{\link{data.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}
% Originally file MASS/max.col.d
% copyright (C) 1999 W. N. Venables and B. D. Ripley
% copyright (C) 2000 The R Core Development Team
\name{max.col}
\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 ``tie'' assumes that
  the entries are probabilities.
}
\author{W. N. Venables and B. D. Ripley}
\references{
  Venables, W. N. and Ripley, B. D. (1999)
  \emph{Modern Applied Statistics with S-PLUS.}
  New York: Springer (3nd 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}
\name{mean}
\title{Arithmetic Mean}
\usage{
mean(x, \dots)
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.
}
\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))

all.equal(mean(x, trim = 0.5), median(x))

data(USArrests)
mean(USArrests, trim = 0.2)
}
\keyword{univar}

\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.
}
\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}
\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}
\name{menu}
\title{Menu Interaction Function}
\usage{
menu(choices, graphics = FALSE, title = "")
}
\alias{menu}
\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}
}
\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 `0'.
}
\value{
  The number corresponding to the selected item, or 0 if no choice was
  made.
}
\examples{
\dontrun{
switch(menu(c("List letters", "List LETTERS")) + 1,
       cat("Nothing done\n"), letters, LETTERS)
}
}
\keyword{utilities}
\keyword{programming}
\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 ``join'' operations.
}
\usage{
merge(x, y, by, by.x, by.y, all = FALSE, all.x = all, all.y = all,
      sort = TRUE, suffixes = c(".x",".y"))
}
\synopsis{
merge(x, y, \dots)
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.}
}
\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
  ``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{x}.  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)

\testonly{
 b2 <- books; names(b2)[1] <- names(authors)[1]

 merge(authors, b2, all.x = TRUE)
 merge(authors, b2, all.y = TRUE)

 ## empty d.f. :
 merge(authors, b2[7,])
 			 
 merge(authors, b2[7,], all.y = TRUE)
 merge(authors, b2[7,], all.x = TRUE)
}
}
\keyword{array}
\keyword{manip}
\name{methods}
\title{Class Methods}
\usage{
UseMethod(generic, object)
NextMethod(generic = NULL, object = NULL, \dots)
methods(generic.function, class)
}
\alias{UseMethod}
\alias{NextMethod}
\alias{methods}
\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}.
}
\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.}
  \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.}
}
\details{
  An \R ``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 ``inherits'' from.  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.

  \code{methods} can be used to find out about the methods for a
  particular generic function or class.  See the examples below for
  details.

  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 ``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 (!?).  Any
  statements after the call to \code{UseMethod} will not be evaluated as
  \code{UseMethod} does not return.

  \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.
}
\note{
  The \code{methods} function was written by Martin Maechler.
}
\seealso{
  \code{\link{class}}
}
\examples{
methods(summary)

methods(print)

methods(class = data.frame)

methods("[")  ##- does not list the C-internal ones...
}
\keyword{methods}
\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.
}

\seealso{
  \code{\link{substitute}} for argument expression;
  \code{\link{NA}} for ``missing values'' in data.
}
\examples{
myplot <- function(x,y) {
                if(missing(y)) {
                        y <- x
                        x <- 1:length(y)
                }
                plot(x,y)
        }
}
\keyword{programming}
\name{mode}
\title{The (Storage) Mode of an Object}
\usage{
mode(x)
mode(x) <- "<mode>"
storage.mode(x)
storage.mode(x) <- "<mode>"
}
\alias{mode}
\alias{mode<-}
\alias{storage.mode}
\alias{storage.mode<-}
\description{
  Get or set the type or storage mode of an object.
}
\arguments{
  \item{x}{any \R 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.
}
\seealso{
  \code{\link{typeof}} for the R-internal ``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}
\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}{The name of a components 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.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}
\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)
model.frame.default(formula, data = NULL,
                    subset = NULL, na.action = na.fail,
                    drop.unused.levels = FALSE, xlev = NULL, \dots)

Methods for
        lm      glm     aovlist
}
\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.}

  \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 ``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 ``design matrix'',
  \code{\link{formula}} for formulas  and
  \code{\link{expand.model.frame}} for model.frame manipulation.
}
\examples{
data(cars)
data.class(model.frame(dist ~ speed, data = cars))
}
\keyword{models}
\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}} 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.
}
\value{
  The design matrix for a regression model with the specified formula
  and data.
}
\references{
  Chambers, J. M. and Hastie, T. J. eds (1992)
  \emph{Statistical Models in S.}
  Chapman & Hall, London.
}
\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}
% file model.tables.Rd
% copyright (C) 1998 B. D. Ripley
%
\name{model.tables}
\title{Compute Tables of Results from an Aov Model Fit.}
\usage{
model.tables(x, \dots)
model.tables.aov(x, type = "effects", se = FALSE, cterms, \dots)
model.tables.aovlist(x, type = "effects", se = FALSE, \dots)
}
\alias{model.tables}
\alias{model.tables.aov}
\alias{model.tables.aovlist}

\alias{print.tables.aov}
\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.}
}
\description{
 Computes summary tables for model fits, especially complex \code{aov} fits.
}
\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.}

\author{B.D. Ripley}

\seealso{\code{\link{aov}}}, \code{\link{proj}}}, \code{\link{replications}}}}

\examples{
## From Venables and Ripley (1997) p.210.
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}
\name{morley}
\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 `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
  `experiment' and `run' as the factors.  `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}
\name{mosaicplot}
\alias{mosaicplot}
\alias{mosaicplot.default}
\alias{mosaicplot.formula}
\title{Mosaic Plots}
\description{Plots a mosaic on the current graphics device.}
\usage{
\method{mosaicplot}{default}(x, main = NULL, xlab = NULL, ylab = NULL,
                   sort = NULL, off = NULL, dir = NULL,
                   color = FALSE, shade = FALSE, margin = NULL,
                   type = c("pearson", "deviance", "FT"), \dots)
\method{mosaicplot}{formula}(formula, data = NULL, \dots, 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{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}{(\code{TRUE} or vector of integer colors) for color
    shading or (\code{FALSE}, the default) for empty boxes with no
    shading.  Ignored if \code{shade} is not \code{FALSE}.}
  \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{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
    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}.
  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://hotspur.psych.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 blond females than expected
## in the case of independence (and too few brown eyed blond 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)
}
\keyword{hplot}
\name{mtcars}
\alias{mtcars}
\title{Motor Trend Road Tests}
\usage{data(mtcars)}
\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).
}
\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}
\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 ``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.}
\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}


\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.  It allows to specify a main title and uses \emph{smart}
  defaults for several \code{\link{par}} calls.
}
\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}
\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 ``NA action'' which should be applied to \code{object} whenever
  \code{\link{NA}}s are not desired.
}
\seealso{
  \code{\link{options}("na.action")}, \code{\link{na.omit}},
  \code{\link{na.fail}}
}
\examples{
na.action(c(1, NA))
}
\keyword{NA}
\keyword{methods}
\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}
\title{Handle Missing Values in Objects}
\usage{
na.fail(object, \dots)
na.omit(object, \dots)
na.exclude(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.
}
\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}.
}
\seealso{
  \code{\link{na.action}};
  \code{\link{options}} with argument \code{na.action} for setting ``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}
\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 \code{MASS}, \code{rpart} and \code{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}
\name{name}
\alias{name}
\alias{is.symbol}
\alias{as.symbol}
\alias{as.name}
\alias{is.name}
\title{Variable Names or Symbols, respectively}
\usage{
as.symbol(x)
is.symbol(y)

as.name(x)
is.name(y)
}
\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.
}
\arguments{
  \item{x, y}{objects to be coerced or tested.} 
}
\note{
  The term ``symbol'' is from the lisp background of \R, whereas ``name''
  has been the standard S term for this.
}
\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}
\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 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.

  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"))}.
}
\examples{
\testonly{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
}
\keyword{attribute}
\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}
\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. 
}
\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}
\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}.
It only accepts character vectors as arguments if you want to operate
on other objects passing them through \code{deparse} first will be required.
}
\arguments{
  \item{x}{character vector.} 
}
\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}
\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.
}
\note{
  For consistency with earlier versions of \R, \code{nclass.Sturges}
  rounds down.  This is incompatible with S-PLUS, and probably wrong:
  however the other algorithms are to be preferred.
}
\references{
  Venables, W. N. and Ripley, B. D. (1999)
  \emph{Modern Applied Statistics with S-PLUS.}
  Springer, pages 118--9.

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

\name{nhtemp}
\alias{nhtemp}
\title{Average Yearly Temperatures in New Haven}
\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.
}
\description{
  The mean annual temperature in degrees Fahrenheit in New Haven,
  Connecticut, from 1912 to 1971.
}
\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}
\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}
\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 ``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
  \code{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}
\name{noquote}
\title{Class for ``no quote'' Printing of Strings}
\usage{
noquote(obj)
print.noquote(x, \dots)
obj[j]
}
\alias{noquote}
%> ./Extract.Rd for "[" and "[<-"
\alias{print.noquote}
\alias{as.matrix.noquote}
\arguments{
 \item{obj, x}{any \R object; typically a vector of \code{\link{character}}
   strings.}
 \item{\dots}{further options for \code{\link{print}}.}
}
\description{
  These functions exist both as utilities and as an example of using
  \code{\link{class}} and object orientation.
}
\value{
  \code{noquote} returns its argument as an object of class
  \code{"noquote"}.  The function \code{"[.noquote"} ensures that the
  class is not lost by subsetting.

  For (default) printing, \code{print.noquote} will be used which prints
  characters \emph{without} quotes (\code{"\dots"}).
}
\author{Martin Maechler \email{maechler@stat.math.ethz.ch}}
\seealso{\code{\link{methods}},\code{\link{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}
\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}
\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.
}
\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}
\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.
}
\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.
}
\examples{
as.numeric(c("-.1"," 2.7 ","B")) # (-0.1, 2.7, NA)  +  warning
as.numeric(factor(5:10))
}
\keyword{classes}
\keyword{attribute}
\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)))
as.matrix(rev(sort(z))[1:10])
}
\keyword{utilities}
\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
  atttribute, 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}
\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}}, \code{\link{glm}}}

\keyword{models}
\name{on.exit}
\title{Function Exit Code}
\usage{
on.exit(expr, add = FALSE)
}
\alias{on.exit}
\arguments{
  \item{expr}{an expression to be executed.}
  \item{add}{if TRUE, add \code{expr} to be executed after any previously
    set expressions.}
}
\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.
}
\seealso{
  \code{\link{sys.on.exit}} to see the current expression.
}
\examples{
opar <- par(mai = c(1,1,1,1))
on.exit(par(opar))
\testonly{par(opar)}
}
\keyword{programming}
\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.
}
\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. Not needed for the
   \code{"Nelder-Mead"} and \code{"SANN"} method. If it is \code{NULL}
   and it is needed, a
   finite-difference approximation will be used. It is guaranteed that
   \code{gr} will be called immediately after a call to \code{fn} at
   the same parameter values.}
 \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 comprehansive reference for the
  previous three methods.
  
  Method \code{"SANN"} is 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. The next candidate point is generated from a
  Gaussian Markov kernel with scale proportional to the actual temperature.
  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}}{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{
  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 \code{opt/lbfgs_bcm.shar}: another version is in \code{toms/778}).

  The code for method \code{"SANN"} was contributed by A. Trapletti.
}

\seealso{\code{\link{nlm}}, \code{\link{optimize}}}

\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)
}
\keyword{nonlinear}
\keyword{optimize}
\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.

  It uses Fortran code (from Netlib) based on algorithms given in the
  reference.

  \code{optimise} is an alias for \code{optimize}.
}
\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
}
\keyword{optimize}
\name{options}
\alias{options}
\alias{.Options}
\alias{getOption}
\title{Options Settings}
\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 ``base \R''.

    Further, \code{options('name') == options()['name']}, see the example.
  }

  \item{prompt}{a string, used for \R's prompt; should usually end in a
    blank (\code{" "}).}

  \item{continue}{a string setting the prompt used for lines which continue
    over one line.}

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

  \item{editor}{sets the default text editor, e.g., for
    \code{\link{edit}}.  Set from the environment variable \code{VISUAL}
    on UNIX.}

  \item{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{browser}{default HTML browser used by \code{\link{help.start}()}
    on UNIX.}

  \item{mailer}{default mailer used by \code{\link{bug.report}()}. can
    be \code{"none"}.}

  \item{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{expressions}{sets a limit on the number of nested expressions that
    will be evaluated.  This is especially important on the Macintosh
    since stack overflow is likely if this is set too high.
    Valid values are 25\dots100000 with default 500.}

  \item{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{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
    \code{R_KEEP_PKG_SOURCE} is set to \code{yes}.}

  \item{na.action}{the name of a function for treating missing values
    (\code{\link{NA}}'s) for certain situations.}

  \item{papersize}{the default paper format used by \code{\link{postscript}};
    set by environment variable \code{R_PAPERSIZE} when \R is started
    and defaulting to \code{"a4"} if that is unset or invalid.}

  \item{printcmd}{the command used by \code{\link{postscript}} for
    printing; set by environment variable \code{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{latexcmd, dvipscmd}{character strings giving commands to be used
    in off-line printing of help pages.}
#endif

  \item{show.signif.stars, show.coef.Pvalues}{logical, affecting P value
    printing, see \code{\link{print.coefmat}}.}

  \item{ts.eps}{the relative tolerance for certain time series
    (\code{\link{ts}}) computations.}

  \item{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{show.error.messages}{a logical. Should error messages be
    printed?  Intended for use with \code{\link{try}} or a
    user-installed error handler.}

  \item{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{check.bounds}{logical, defaulting to \code{FALSE}.  If true, a
    \link{warning} is produced whenever a ``generalized vector''
    (atomic or \code{\link{list}}) is extended, by something like
    \code{x <- 1:3; x[5] <- 6}.}

  \item{echo}{logical.  Only used in non-interactive mode, when it
    controls whether input is echoed. Command-line option
    \code{--slave} sets this initially to \code{FALSE}.}

  \item{verbose}{logical.  Should \R report extra information on
    progress? Set to \code{TRUE} by the command-line option
    \code{--verbose}.}

  \item{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{X11colortype}{The default colour type for \code{\link{X11}} devices.}
#endif

  \item{CRAN}{The URL of the preferred CRAN node for use by
    \code{\link{update.packages}}. Defaults to
    \url{http://cran.r-project.org}.}

  \item{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{unzip}{the command used unzipping help files.
#ifdef windows
    Defaults to "internal" when the internal unzip DLL is used.
#endif
  }
  \item{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{encoding}{An integer vector of length 256 holding an input
    encoding.  Defaults to \code{native.enc} (= \code{0:255}).
    See \code{\link{connections}}.}

  \item{timeout}{Integer.  The timeout for Internet operations,
    in seconds.  Default 60 seconds.}

  \item{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{x}{a character string holding one of the above option names.}
}
\description{
  \code{options} allows the user to set and examine a variety of global
  ``options'' which affect the way in which \R computes and displays
  its results.
}
\details{
  Invoking \code{options()} with no arguments returns a list with the
  current values of the options.  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 ``read only'' however.

  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{warn} \tab \code{0}\cr
    \code{echo} \tab \code{TRUE} \tab
    \code{verbose} \tab \code{FALSE}
  }
  Others are set from environment variables or are platform-dependent.
}
\value{
  A list (in any case) with the previous values of the options changed,
  or all options when no arguments were given.
}
\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(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=quote(dump.frames()))
## A possible setting for non-interactive sessions
options(error=quote({dump.frames(to.file=TRUE); q()}))
}}
\keyword{environment}
\keyword{error}
\keyword{print}
\name{order}
\title{Ordering Permutation}
\alias{order}
\alias{sort.list}
\description{
  \code{order} returns a permutation which rearranges its first
  argument into ascending order, breaking ties by further arguments.
  \code{sort.list} is the same, using only one argument but allowing
  partial sorting.
}
\usage{
order(\dots, na.last = TRUE)
sort.list(x, partial = NULL, na.last = TRUE)
}
\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{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.
    }
}
\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).

  \code{\link{NA}} values are treated as greater than any other values
  so that permutations returned by \code{order} move \code{NA} values to
  the top end of the array.  Other options are not (yet) implemented in
  \R.

  \code{partial} is supplied for compatibility with other
  implementations of S, but no other values are accepted and ordering is
  always complete.
}
\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)

## 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, ]
}
\keyword{univar}
\keyword{manip}
\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}
\seealso{
  \code{\link{matmult}} 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}
\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 # c("holm", "hochberg", "bonferroni","none")
}
\arguments{
 \item{p}{vector of p values}
 \item{method}{correction method}
 \item{n}{number of comparisons}
}
\details{
  The adjustment methods include the Bonferroni correction in
  which the p values are multiplied by the number of comparisons. Two
  less conservative corrections by Holm, respectively Hochberg,
  are also included. 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}.
}
\value{
  A vector of corrected p values.
}
\references{ S Paul Wright: Adjusted P-values for simultaneous
  inference,  Biometrics \bold{48}, 1005--1013
 }
\note{The Hochberg method is only proved to work if the p values are
  independent, although simulations have indicated that it works in
  correlated cases as well. Hence the Holm method is the default.}
\seealso{\code{pairwise.*} functions in the \code{ctest} package, such
  as \code{\link[ctest]{pairwise.t.test}}.
}
\examples{
  p <- runif(50)
  p.adjust(p)
}
\keyword{ htest }
\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}
\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}
\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 \code{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 "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}%-- one or more ...
\keyword{utilities}%-- one or more ...
\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, ...)
\method{update}{packageStatus}(object, lib.loc=levels(object$inst$LibPath),
       repositories=levels(object$avail$Repository), ...)
\method{upgrade}{packageStatus}(object, ask=TRUE, ...)
}
\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{...}{currently not used.}
}
\examples{
\dontrun{
x <- packageStatus()
print(x)
summary(x)
upgrade(x)
x <- update(x)
print(x)
}}
\keyword{utilities}
\name{page}
\alias{page}
\title{Invoke a Pager on an R Object}
\usage{
page(x, method = c("dput", "print"), ...)
}
\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.
}
\author{B. D. Ripley}
\seealso{
    \code{\link{file.show}}, \code{\link{edit}}, \code{\link{fix}}.
}
\keyword{utilities}
\name{pairs}
\alias{pairs}
\alias{pairs.default}
\title{Scatterplot Matrices}
\description{
  A matrix of scatterplots is produced.
}
\synopsis{
pairs(x, \dots)
pairs.default(x, labels = colnames(x), 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)
pairs.default(x, labels = colnames(x), 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{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 ``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.
}
\author{
  Enhancements for \R 1.0.0 contributed by Dr. Jens
  Oehlschlaegel-Akiyoshi and R-core members.
}
\examples{
data(iris)
pairs(iris[1:4], main = "Anderson's Iris Data -- 3 species", 
      pch = 21, bg = c("red", "green3", "blue")[codes(iris$Species)])

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}
\name{pairs.formula}
\alias{pairs.formula}
\title{Formula Notation for Scatterplot Matrices}
\description{
  Produce a matrix of scatterplots using formula notation.
}
\usage{
\method{pairs}{formula}(formula, data = NULL, \dots, subset)
}
\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{\dots}{arguments to the default pairs method and graphical
    parameters may also be passed as arguments, see \code{\link{par}}.}
  \item{subset}{an optional vector specifying a subset of observations
    to be used for plotting.}
}
\details{
  This is a method of the generic function \code{\link{pairs}}.  It
  operates by setting up the data from the formula specification, and
  then calling \code{\link{pairs.default}}.
}
\seealso{
  \code{\link{pairs.default}}
}
\examples{
data(swiss)
pairs(~ Fertility + Education + Catholic, data = swiss,
      subset = Education < 20, main = "Swiss data, Education < 20")
}
\keyword{hplot}
\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 ``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}
\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} ``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 ``saturation'' and ``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 ``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
piechart(rep(1,12), col=rainbow(12))

##------ Some palettes ------------
ch.col <- c("rainbow(n, start=.7, end=.1)", "heat.colors(n)",
            "terrain.colors(n)", "topo.colors(n)", "cm.colors(n)")

n <- if(.Device == "postscript") 64 else 16
     # Since for screen, larger n may give color allocation problem
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=paste("color palettes;  n=",n))
for (k in 1:nt) {
  rect(i-.5,(k-1)*j+ dy, i+.4,  k*j, col=eval(parse(text=ch.col[k])))
  text(2*j,  k * j +dy/4, ch.col[k])
}
}
\keyword{color}
\keyword{dplot}
\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, bg=NA, 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}
\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/par.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 ``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
      `invisible lines' (i.e., doesn't draw them).

      Alternatively, a string of up to 8 characters (from \code{c(0:9,
	"A":"F")}) may be given, giving the length of line segments
      which are alternatively drawn and skipped.  See section `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 ``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 arc should be.}
    \item{\code{srt}}{The string rotation in degrees.
      %% 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=1}, grid lines are drawn.  The default setting 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}.}
    \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.}
    \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}}{\emph{\bold{R.O.}}; 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.}
    \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}}{\emph{\bold{R.O.}}; 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 there 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. This provides compatibility with S.

  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, 3 = dotted) or
  directly as the lengths of on/off stretches of line.  This is done
  with a string of up to eight characters 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 `units' here are (on most
  devices) proportional to \code{lwd}, and with \code{lwd = 1} are in
  pixels or points.
}

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

\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

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}
\name{parse}
\title{Parse Expressions}
\usage{
parse(file = "", n = NULL, text = NULL, prompt = "?", white = FALSE)
}
\alias{parse}
\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. The text to parse, quoted.}
  \item{prompt}{the prompt to print when parsing from the keyboard.
    \code{NULL} means to use \R's prompt, \code{options("prompt")[[1]]}.}
  \item{white}{if \code{TRUE} then any white space separates expressions
    otherwise only newlines or semicolons do.}
}
\description{
  \code{parse} returns the parsed but unevaluated expressions in a
  list.  Each element of the list is of mode \code{expression}.
}
\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 Mac).  The final line can be incomplete, that
  is missing the final EOL marker. 
}
\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}
\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.
}
\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.
}
\examples{
paste(1:12) # same as as.character(1:12)
paste("A", 1:6, sep = "")
paste("Today is", date())
}
\keyword{character}
\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, \dots)
}
\usage{
pdf(file = ifelse(onefile, "Rplots.pdf", "Rplot\%03d.pdf"),
    width = 6, height = 6, onefile = TRUE, family = "Helvetica",
    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{encoding}{the name of an encoding file.  Defaults to
#ifdef unix
\code{"ISOLatin1.enc"}
#endif
#ifdef windows
\code{"WinAnsi.enc"}
#endif
#ifdef mac
\code{"MacRoman.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.

  There is an internal limit of 500 pages per PDF file, which should
  be ample.
}
\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}}
}
\keyword{device}
\name{persp}
\title{Perspective Plots}
\usage{
persp(x, ...)
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 = NULL, border = NULL, ltheta = -135, lphi = 0, shade = NA,
      box = TRUE, axes = TRUE, nticks = 5, ticktype = "simple",
      ...) 
}
\alias{persp}
\alias{persp.default}
\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 the
    character strings; expressions are not accepted.}
  \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 of the surface 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: "simple" draws just an arrow parallel to 
    the axis to indicate direction of increase; "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 "simple".}
  \item{\dots}{additional graphical parameters (see \code{\link{par}}).}
}
\description{
  This function draws perspective plots of surfaces over the
  x--y plane. \code{persp} is a generic function.
}
\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.
}
\seealso{
  \code{\link{contour}} and \code{\link{image}}.
}
\examples{
# (1) The Obligatory Mathematical surface.
#     Rotated sinc function.

x <- seq(-10, 10, length=50)
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
par(bg = "white")
persp(x, y, z, theta = 30, phi = 30, expand = 0.5, col = "lightblue",
      xlab = "X", ylab = "Y", zlab = "Z") 
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 = "Z") 


# (2) 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)
persp(x, y, z, theta = 120, phi = 15, scale = FALSE, axes = FALSE)


# (3) Now something more complex
#     We border the surface, to make it more "slice like"
#     and color the top and sides of the surface differently.

zmin <- min(z) - 20
z <- rbind(zmin, cbind(zmin, z, zmin), zmin)
x <- c(min(x) - 1e-10, x, max(x) + 1e-10)
y <- c(min(y) - 1e-10, y, max(y) + 1e-10)

fill <- matrix("green3", nr = nrow(z)-1, nc = ncol(z)-1)
fill[,1] <- "gray"
fill[,ncol(fill)] <- "gray"
fill[1,] <- "gray"
fill[nrow(fill),] <- "gray"

par(bg = "lightblue")
persp(x, y, z, theta = 120, phi = 15, col = fill, scale = FALSE, axes = FALSE)
title(main = "Maunga Whau\nOne of 50 Volcanoes in the Auckland Region.",
      font.main = 4)

par(bg = "slategray")
persp(x, y, z, theta = 135, phi = 30, col = fill, scale = FALSE,
      ltheta = -120, lphi = 15, shade = 0.65, axes = FALSE)
persp(x, y, z, theta = 135, phi = 30, col = "green3", scale = FALSE,
      ltheta = -120, shade = 0.75, border = NA, box = FALSE)
}
\keyword{hplot}
\keyword{aplot}
\name{phones}
\title{The World's Telephones}
\usage{data(phones)}
\alias{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}.
}
\description{
  The number of telephones in various regions of the world (in
  thousands).
}
\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:7, lty = 1:7, pch = rep(21, 7))
title(main = "phones data: log scale for response")
}
\keyword{datasets}
\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
\name{piechart}
\title{Pie Charts}
\alias{piechart}
\description{
  Draw a pie chart.
}
\usage{
piechart(x, labels = names(x), edges = 200, radius = 0.8,
         density = NULL, angle = 45, col = 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.}
  \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 `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 the slices. If
    missing \code{par("bg")} is used, unless \code{density} is specified
    when \code{par("fg")} is used.}
  \item{main}{an overall title for the plot.}
  \item{\dots}{graphical parameters can be given as arguments to
    \code{piechart}.}
}
\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.
}
\seealso{
  \code{\link{dotchart}}.
}
\examples{
piechart(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")
piechart(pie.sales,
    col=c("purple", "violetred1", "green3",
    "cornsilk", "cyan", "white"))
piechart(pie.sales,
    col=gray(seq(0.4,1.0,length=6)))
piechart(pie.sales,
    density=10, angle=15+10*1:6)
}
\keyword{hplot}
\name{plot}
\title{Generic X-Y Plotting}
\alias{plot}
\synopsis{
plot(x, \dots)
}
\usage{
plot(x, y, xlim=range(x), ylim=range(y), type="p",
     main, xlab, ylab, \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{xlim, ylim}{the ranges to be encompassed by the x and y axes.}
  \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 ``\bold{o}verplotted'',
      \item \code{"h"} for ``\bold{h}istogram'' like (or
      ``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.}
  \item{xlab}{a title for the x axis.}
  \item{ylab}{a title for the y axis.}
  \item{\dots}{graphical parameters can be given as arguments to
    \code{plot}.}
}
\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}
\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 ``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}
\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.25)
}
\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 ``Scale-Location'' plot, also called ``Spread-Location'' or
  ``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 `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{lm.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")
\testonly{% which=4 failed in R 1.0.1
 par(mfrow=c(1,1), oma= rep(0,4))
 data(longley)
 summary(lm.fm2 <- lm(Employed ~ . - Population - GNP.deflator, data = longley))
 for(wh in 1:4) plot(lm.fm2, which = wh)
}
}
\keyword{hplot}
\keyword{regression}
\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 ``bar like''.
}
\usage{
%% Improvement ideas: see code definition, currently in ../R/plot.R
plot.table(x, type = "h", ylim = c(0, max(x)), lwd = 2,
           xlab = NULL, ylab = deparse(substitute(x)), frame.plot = is.num, ...)
}
\arguments{
  \item{x}{a \code{\link{table}} (like) object.}
  \item{type}{plotting type.}
  \item{ylim}{range of y-axis.}
  \item{lwd}{line width of bars when \code{type = "h"} is used.}
  \item{xlab, ylab}{x- and y-axis labels.}
  \item{frame.plot}{logical indicating if a frame (\code{\link{box}})
    should be drawn.  Default are ~~Describe \code{frame.plot} here~~ }
  \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}
\name{plot.ts}
\alias{plot.ts}
\alias{plot.mts}
\alias{lines.ts}
\title{Plotting Time-Series Objects}
\description{
  Plotting methods for objects of class \code{"ts"} or \code{"mts"}
  (multivariate time-series).
}
\synopsis{
plot.ts(x, y = NULL, type = "l", xlim = NULL, ylim = NULL,
	  xlab = "Time", ylab, log = "",
	  col = par("col"), bg = NA,
	  pch = par("pch"), cex = par("cex"),
	  lty = par("lty"), lwd = par("lwd"),
	  axes = TRUE, frame.plot = axes, ann = par("ann"),
	  main = NULL, plot.type = c("multiple", "single"),
	  xy.labels = n <= 150, xy.lines = do.lab, panel=lines, ...)
}
\usage{
\method{plot}{ts}(x, y = NULL, type = "l", frame.plot = axes,
     plot.type = c("multiple", "single"),
     xy.labels = n <= 150, xy.lines = do.lab, panel=lines, ...)

lines(x, \dots)
}
\arguments{
  \item{x,y}{time series objects, usually of class \code{"ts"}.}

  \item{type}{the type of plot, see \code{\link{plot}}.  When \code{y}
    is present, the default will depend on \code{xy.labels}, see below.}

  \item{frame.plot}{a function to give the `frame' for each panel.}

  \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.}
  \item{xy.lines}{logical, indicating if \code{\link{lines}}
    should be drawn for an x-y plot.  Default is true, when labels are
    drawn as well.}
  \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{\dots}{additional graphical arguments, see \code{\link{plot}},
    \code{\link{plot.default}} and \code{\link{par}}.}
}
\details{
  With one principal argument, these functions create time series
  plots, for multivariate series of two kinds depending on \code{plot.type},

  If \code{y} is present, both \code{x} and \code{y} must be univariate,
  and a ``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)                # multiple
plot(z, panel=points)  # same with points instead of lines
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")
}

library(ts)

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)

detach("package:ts") 
}
\keyword{hplot}
\keyword{ts}
\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)
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.5)
\testonly{detach("package:mva")}
}
\keyword{aplot}
\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 (``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}
\name{plot.default}
\alias{plot.default}
\title{The Default Scatterplot Function}
\description{
  Draw a scatter plot with ``decorations'' such as axes and titles
  in the active graphics window.
}
\usage{
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("fg"), bg = NA, pch = par("pch"),
             cex = par("cex"), 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.}
  \item{bg}{background color for open plot symbols, see
    \code{\link{points}}.}
  \item{pch}{a vector of plotting characters or symbols.}
  \item{cex}{a numerical value 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{
  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}
\name{plot.factor}
\title{Plotting Factor Variables}
\usage{
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 ``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

plot(PlantGrowth$group, axes=FALSE, main="no axes")# extremly silly
}
\keyword{hplot}
\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}}.}
  \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{class}} attribute)
  then \code{plot.formula} looks for a plot method for that class first.
}
\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}
\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),
               xlim = range(x$breaks), ylim = range(y, 0),
               xlab = x$xname, ylab, 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{intensities}, \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
    (``probabilities''), i.e., \code{x$intensities}, 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{xlim, ylim}{the range of x and y values with sensible defaults.}
  \item{main, xlab, ylab}{these arguments to \code{title} have useful
    defaults here.}
  \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
    intensities; 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}
\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{example(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{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{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{\link{axis}},
  \code{\link{mtext}},
  \code{\link{text}},
  \code{\link{title}}
}
\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")
tt <- 1.23 ; mtext(substitute(hat(theta) == that, list(that= tt)))
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)

######
# create tables of mathematical annotation functionality
######
make.table <- function(nr, nc) {
    savepar <- par(mar=rep(0, 4), pty="s")
    plot(c(0, nc*2 + 1), c(0, -(nr + 1)),
         type="n", xlab="", ylab="", axes=FALSE)
    savepar
}

get.r <- function(i, nr) {
    i \%\% nr + 1
}

get.c <- function(i, nr) {
    i \%/\% nr + 1
}

draw.title.cell <- function(title, i, nr) {
    r <- get.r(i, nr)
    c <- get.c(i, nr)
    text(2*c - .5, -r, title)
    rect((2*(c - 1) + .5), -(r - .5), (2*c + .5), -(r + .5))
}

draw.plotmath.cell <- function(expr, i, nr, string = NULL) {
    r <- get.r(i, nr)
    c <- get.c(i, nr)
    if (is.null(string)) {
        string <- deparse(expr)
        string <- substr(string, 12, nchar(string) - 1)
    }
    text((2*(c - 1) + 1), -r, string, col="grey")
    text((2*c), -r, expr, adj=c(.5,.5))
    rect((2*(c - 1) + .5), -(r - .5), (2*c + .5), -(r + .5), border="grey")
}

nr <- 20
nc <- 2
oldpar <- make.table(nr, nc)
i <- 0
draw.title.cell("Arithmetic Operators", i, nr); i <- i + 1
draw.plotmath.cell(expression(x + y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x - y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x * y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x / y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x \%+-\% y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x \%/\% y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x \%*\% y), i, nr); i <- i + 1
draw.plotmath.cell(expression(-x), i, nr); i <- i + 1
draw.plotmath.cell(expression(+x), i, nr); i <- i + 1
draw.title.cell("Sub/Superscripts", i, nr); i <- i + 1
draw.plotmath.cell(expression(x[i]), i, nr); i <- i + 1
draw.plotmath.cell(expression(x^2), i, nr); i <- i + 1
draw.title.cell("Juxtaposition", i, nr); i <- i + 1
draw.plotmath.cell(expression(x * y), i, nr); i <- i + 1
draw.plotmath.cell(expression(paste(x, y, z)), i, nr); i <- i + 1
draw.title.cell("Lists", i, nr); i <- i + 1
draw.plotmath.cell(expression(list(x, y, z)), i, nr); i <- i + 1
# even columns up
i <- 20
draw.title.cell("Radicals", i, nr); i <- i + 1
draw.plotmath.cell(expression(sqrt(x)), i, nr); i <- i + 1
draw.plotmath.cell(expression(sqrt(x, y)), i, nr); i <- i + 1
draw.title.cell("Relations", i, nr); i <- i + 1
draw.plotmath.cell(expression(x == y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x != y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x < y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x <= y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x > y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x >= y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x \%~~\% y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x \%=~\% y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x \%==\% y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x \%prop\% y), i, nr); i <- i + 1
draw.title.cell("Typeface", i, nr); i <- i + 1
draw.plotmath.cell(expression(plain(x)), i, nr); i <- i + 1
draw.plotmath.cell(expression(italic(x)), i, nr); i <- i + 1
draw.plotmath.cell(expression(bold(x)), i, nr); i <- i + 1
draw.plotmath.cell(expression(bolditalic(x)), i, nr); i <- i + 1

# Need fewer, wider columns for ellipsis ...
nr <- 20
nc <- 2
make.table(nr, nc)
i <- 0
draw.title.cell("Ellipsis", i, nr); i <- i + 1
draw.plotmath.cell(expression(list(x[1], ..., x[n])), i, nr); i <- i + 1
draw.plotmath.cell(expression(x[1] + ... + x[n]), i, nr); i <- i + 1
draw.plotmath.cell(expression(list(x[1], cdots, x[n])), i, nr); i <- i + 1
draw.plotmath.cell(expression(x[1] + ldots + x[n]), i, nr); i <- i + 1
draw.title.cell("Set Relations", i, nr); i <- i + 1
draw.plotmath.cell(expression(x \%subset\% y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x \%subseteq\% y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x \%supset\% y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x \%supseteq\% y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x \%notsubset\% y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x \%in\% y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x \%notin\% y), i, nr); i <- i + 1
draw.title.cell("Accents", i, nr); i <- i + 1
draw.plotmath.cell(expression(hat(x)), i, nr); i <- i + 1
draw.plotmath.cell(expression(tilde(x)), i, nr); i <- i + 1
draw.plotmath.cell(expression(ring(x)), i, nr); i <- i + 1
draw.plotmath.cell(expression(bar(xy)), i, nr); i <- i + 1
draw.plotmath.cell(expression(widehat(xy)), i, nr); i <- i + 1
draw.plotmath.cell(expression(widetilde(xy)), i, nr); i <- i + 1
draw.title.cell("Arrows", i, nr); i <- i + 1
draw.plotmath.cell(expression(x \%<->\% y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x \%->\% y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x \%<-\% y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x \%up\% y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x \%down\% y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x \%<=>\% y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x \%=>\% y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x \%<=\% y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x \%dblup\% y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x \%dbldown\% y), i, nr); i <- i + 1
draw.title.cell("Symbolic Names", i, nr); i <- i + 1
draw.plotmath.cell(expression(Alpha - Omega), i, nr); i <- i + 1
draw.plotmath.cell(expression(alpha - omega), i, nr); i <- i + 1
draw.plotmath.cell(expression(infinity), i, nr); i <- i + 1
draw.plotmath.cell(expression(32 * degree), i, nr); i <- i + 1
draw.plotmath.cell(expression(60 * minute), i, nr); i <- i + 1
draw.plotmath.cell(expression(30 * second), i, nr); i <- i + 1

# Need even fewer, wider columns for typeface and style ...
nr <- 20
nc <- 1
make.table(nr, nc)
i <- 0
draw.title.cell("Style", i, nr); i <- i + 1
draw.plotmath.cell(expression(displaystyle(x)), i, nr); i <- i + 1
draw.plotmath.cell(expression(textstyle(x)), i, nr); i <- i + 1
draw.plotmath.cell(expression(scriptstyle(x)), i, nr); i <- i + 1
draw.plotmath.cell(expression(scriptscriptstyle(x)), i, nr); i <- i + 1
draw.title.cell("Spacing", i, nr); i <- i + 1
draw.plotmath.cell(expression(x ~~ y), i, nr); i <- i + 1

# Need fewer, taller rows for fractions ...
# cheat a bit to save pages
par(new = TRUE)
nr <- 10
nc <- 1
make.table(nr, nc)
i <- 4
draw.plotmath.cell(expression(x + phantom(0) + y), i, nr); i <- i + 1
draw.plotmath.cell(expression(x + over(1, phantom(0))), i, nr); i <- i + 1
draw.title.cell("Fractions", i, nr); i <- i + 1
draw.plotmath.cell(expression(frac(x, y)), i, nr); i <- i + 1
draw.plotmath.cell(expression(over(x, y)), i, nr); i <- i + 1
draw.plotmath.cell(expression(atop(x, y)), i, nr); i <- i + 1

# Need fewer, taller rows and fewer, wider columns for big operators ...
nr <- 10
nc <- 1
make.table(nr, nc)
i <- 0
draw.title.cell("Big Operators", i, nr); i <- i + 1
draw.plotmath.cell(expression(sum(x[i], i=1, n)), i, nr); i <- i + 1
draw.plotmath.cell(expression(prod(plain(P)(X == x), x)), i, nr); i <- i + 1
draw.plotmath.cell(expression(integral(f(x) * dx, a, b)), i, nr); i <- i + 1
draw.plotmath.cell(expression(union(A[i], i==1, n)), i, nr); i <- i + 1
draw.plotmath.cell(expression(intersect(A[i], i==1, n)), i, nr); i <- i + 1
draw.plotmath.cell(expression(lim(f(x), x \%->\% 0)), i, nr); i <- i + 1
draw.plotmath.cell(expression(min(g(x), x >= 0)), i, nr); i <- i + 1
draw.plotmath.cell(expression(inf(S)), i, nr); i <- i + 1
draw.plotmath.cell(expression(sup(S)), i, nr); i <- i + 1

make.table(nr, nc)
i <- 0
draw.title.cell("Grouping", i, nr); i <- i + 1
draw.plotmath.cell(expression((x + y)*z), i, nr); i <- i + 1
draw.plotmath.cell(expression(x^y + z), i, nr); i <- i + 1
draw.plotmath.cell(expression(x^(y + z)), i, nr); i <- i + 1
# have to do this one by hand
draw.plotmath.cell(expression(x^{y + z}), i, nr, string="x^{y + z}"); i <- i + 1
draw.plotmath.cell(expression(group("(", list(a, b), "]")), i, nr); i <- i + 1
draw.plotmath.cell(expression(bgroup("(", atop(x, y), ")")), i, nr); i <- i + 1
draw.plotmath.cell(expression(group(lceil, x, rceil)), i, nr); i <- i + 1
draw.plotmath.cell(expression(group(lfloor, x, rfloor)), i, nr); i <- i + 1
draw.plotmath.cell(expression(group("|", x, "|")), i, nr); i <- i + 1

par(oldpar)
}
\keyword{aplot}
\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}.
}
\note{
  Versions of \R prior to 1.0.0 had a different behaviour that was
  seriously incompatible with S (and the current version) when
  \code{duplicates.ok = TRUE}.
}
\author{
  Of this version, B. D. Ripley.
}
\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}
\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)
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 ``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.
    }
  }
  \item{col}{color code or name, see \code{\link{colors}},
    \code{\link{palette}}.}
  \item{bg}{background (``fill'') color for open plot symbols}
  \item{cex}{character expansion}
  \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}}.

  Graphical parameters are permitted as arguments to this function.
}
\seealso{
  \code{\link{plot}}, \code{\link{lines}}, and the underlying
  ``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}
\name{poly}
\title{Compute Orthogonal Polynomials}
\usage{
poly(x, degree=1)
}
\alias{poly}
\arguments{
 \item{x}{a numeric vector at which to evaluate the polynomial}
 \item{degree}{the degree of the polynomial}
}
\description{
Returns 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.
}
\value{
  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.}
\author{B.D. Ripley}

\note{This routine is intended for statistical purposes such as
    \code{contr.poly}: it does not attempt to orthogonalize to
    machine accuracy.
}

\seealso{\code{\link{contr.poly}}}

\examples{
poly(1:10, 3)
}
\keyword{math}
\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.
    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}{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=0} to omit borders.}
  \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}.}
}
\seealso{
  \code{\link{segments}} for even more flexibility, \code{\link{lines}},
  \code{\link{rect}}, \code{\link{box}}, \code{\link{abline}}.
}
\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}
\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.
}
\value{
  A complex vector of length \eqn{n - 1}, where \eqn{n} is
  \code{length(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)
}
\keyword{math}
\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}
\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, \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)

% 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\%d.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 `Families'.}
  \item{encoding}{the name of an encoding file. Defaults to
#ifdef unix
"ISOLatin1.enc"
#endif
#ifdef windows
"WinAnsi.enc"
#endif
#ifdef mac
"MacRoman.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 "white" (or a
    specification equivalent to white), 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 give 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 ``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.}
}
\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 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}.
  }
#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
  \code{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.)

  As ISOLatin1 encoding is used, \code{-} is set as a minus and not
  as a hyphen.  Supply a hyphen (character 173) if that is what you
  need.

  \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 \code{afm} files.  The software
  including the PostScript plot file should either embed the font
  outlines (usually from \code{.pfb} or \code{.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.
}
\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("R.ps"), 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.
}
\testonly{
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}
\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.
}
\seealso{
    \code{\link{make.link}},
    \code{\link{family}}
}
\examples{
power()
quasi(link=power(1/3))[c("linkfun", "linkinv")]
}
\keyword{models}
\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 ``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.
}
\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}
\name{precip}
\title{Annual Precipitation in US Cities}
\usage{data(precip)}
\alias{precip}
\description{
  The average amount of precipitation (rainfall) in inches for each of
  70 United States (and Puerto Rico) cities.
}
\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}
\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{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}}.
}
\examples{
## All the "predict" methods available in your current search() path:
for(fn in methods("predict"))
   cat(fn,":\n\t",deparse(args(get(fn))),"\n")
}
\keyword{methods}
\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, \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{\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.}
}
\author{B.D. Ripley}
%  \note{This method is also currently used for objects of
%    class \code{"survreg"} (parametric survival fits from package
%    \code{survival4}) and possibly others. The assumptions made by
%    \code{predict.glm} may not always be right for such objects.}

\seealso{\code{\link{glm}}}

\examples{
## example from Venables and Ripley (1997, pp. 231-3.)
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}
\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, \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{\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}.
}
\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}}.
}
\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}

\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, ...)
}
\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}
\name{presidents}
\alias{presidents}
\title{Approval Rating of US Presidents}
\usage{data(presidents)}
\format{
  A time series of 120 values.
}
\source{
  The Gallup Organisation.
}
\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.
}
\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}
\name{pressure}
\alias{pressure}
\title{Vapor Pressure of Mercury as a Function of Temperature}
\usage{data(pressure)}
\description{
    Data on the relation between temperature in degrees Celsius and
    vapor pressure of mercury in millimeters (of mercury).
}
\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}
\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 ``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 ``optimal'':
    \code{u5.bias = .5 + 1.5*high.u.bias}.}
\item{eps.correct}{integer code, one of \{0,1,2\}. If non-0, an
    \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
    \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

}
\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}
\name{print}
\title{Print Values}
\usage{
print(x, \dots)

print.factor(x, quote = FALSE, \dots)
print.ordered(x, quote = FALSE, \dots)
}
\alias{print}
\alias{print.factor}
\alias{print.ordered}
\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{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.}
}
\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.

    See \code{\link{noquote}} as an example of a class whose main
    purpose is a specific \code{print} method.
}
\seealso{The default method \code{\link{print.default}}, and help for the
  methods above; further \code{\link{options}}, \code{\link{noquote}}.
}
\examples{
ts(1:20)#-- print  is the ``Default function'' --> print.ts(.) is called
rr <- for(i in 1:3) print(1:i)
rr
}
\keyword{print}
\name{print.coefmat}
\alias{print.coefmat}
\title{Print Coefficient Matrices}
\description{
  Utility function to be used in ``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{
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(",
              na.print = "", \dots)
}
\arguments{
  \item{x}{a numeric matrix like object, to be printed.}
  \item{digits}{number of digits to be used for most numbers.}
  \item{signif.stars}{logical; if \code{TRUE}, P-values are additionally
    encoded visually as ``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}{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 ``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{na.print}{a character string to code \code{\link{NA}} values in
    printed output.}
 \item{\dots}{further arguments for \code{\link{print}}.}
}
\details{
  Despite its name, this is \emph{not} (yet) a method for the generic
  \code{\link{print}} function, because there is no class
  \code{"coefmat"}.
}
\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)")
print.coefmat(cmat[,1:3])
print.coefmat(cmat)
options(show.coef.Pvalues = FALSE)
print.coefmat(cmat, digits=2)
print.coefmat(cmat, digits=2, P.values = TRUE)
options(show.coef.Pvalues = TRUE)# revert
}
\keyword{print}
\name{print.data.frame}
\title{Printing Data Frames}
\alias{print.data.frame}
\description{
  These functions create or manipulate 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{
\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 number of significant digits to be printed.}
  \item{quote}{logical, indicating whether or not strings
    (\code{\link{character}}s) should be printed with surrounding quotes.}
  \item{right}{logical, indicating whether or not strings should be
    right-aligned. The default is left-alignment.}
}
\value{
  For the \code{\link{print}} method (\code{print.data.frame}), see
  \code{\link{print.matrix}}.
}
}
\seealso{
  \code{\link{data.frame}}.
}
\keyword{print}
\name{print.default}
\title{Default Printing}
\usage{
print.default(x, digits = NULL, quote = TRUE, na.print = NULL,
              print.gap = NULL, right = FALSE, \dots)
print.atomic(x, quote = TRUE, \dots)
}
\alias{print.default}
\alias{print.atomic}
\arguments{
  \item{x}{the object to be printed.}
  \item{digits}{a non-null value for \code{digits} specifies the 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} meaning
    \code{"NA"}.}
  \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, currently disregarded)}
}
\description{
  \code{print.default} is the \emph{default} method of the generic
  \code{\link{print}} function which prints its argument.

  \code{print.atomic} is almost the same and exists purely for
  compatibility reasons.
}
\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}
\name{print.matrix}
\title{Print Matrices}
\usage{
print.matrix(x, rowlab=character(0), collab=character(0),
             quote=TRUE, right=FALSE, na.print = NULL,
             print.gap = NULL, \dots)
}
\alias{print.matrix}
\alias{prmatrix}
\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{print.gap}{not yet used.}
  \item{\dots}{arguments for other methods.}
}
\description{
  Pseudo-method for the \code{\link{print}} generic.  Especially useful
  with the \code{right} argument which does not (yet) exist for
  \code{\link{print.default}}.
}
\details{
  \code{print.matrix} and \code{\link{print.default}} both print
  matrices, and each has at least an optional argument that the other
  lacks.  Also, both directly dispatch into \code{.Internal} code
  directly instead of relying on each other.
  This mainly stems from historic compatibility and similar reasons should
  be changed in the future.
  %%-- ``signed:  Martin Maechler''

  \code{prmatrix} is currently just an alias for
  \code{print.matrix}.
}
\value{Invisibly returns its argument, \code{x}.}}
\seealso{\code{\link{print.default}}, and other \code{\link{print}} methods.}
\examples{
print.matrix(m6 <- diag(6), row = rep("",6), coll=rep("",6))

chm <- matrix(scan(system.file("help", "AnIndex", package = "eda"),
                   what = ""), , 2, byrow = TRUE)
chm  #-> print.default(.)  = `same' as  print.matrix(chm)
print.matrix(chm, collab = paste("Column",1:3), right=TRUE, quote=FALSE)
}
\keyword{print}
\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}
\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 ``timing'' the evaluation of \R expressions,
  which can be done conveniently with \code{\link{system.time}}.
}
#ifndef mac
\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 and 2000 systems. Times of child processes are
  not available and will always be given as \code{NA}.
#endif
}
#endif
\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{
ptm <- proc.time()
for (i in 1:50) mad(runif(500))
proc.time() - ptm
}
\keyword{utilities}
\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.
}
\seealso{
\code{\link{sum}},
\code{\link{cumprod}},
\code{\link{cumsum}}.
}
\examples{
print(prod(1:7)) == print(gamma(8))
}
\keyword{arith}
\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 \bold{nls},
  \code{\link[MASS:confint]{profile.glm}} in package \bold{MASS},
  \ldots
}
\keyword{models}
\name{proj}
\title{Projections of Models}
\usage{
proj     (object, \dots)  
proj.aov    (object, onedf = FALSE, unweighted.scale = FALSE, \dots)  
proj.aovlist(object, onedf = FALSE, unweighted.scale = FALSE, \dots)  
proj.default(object, onedf = TRUE, \dots)  
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.
}
\author{B.D. Ripley}

\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}
\name{prompt}
\title{Produce Prototype of an R Documentation File}
\synopsis{
prompt.default(object,
    filename = paste0(name, ".Rd"), force.function = FALSE, \dots)

prompt.data.frame(object,
    filename = paste0(name, ".Rd"), \dots)
}
\usage{
prompt(object, \dots)

prompt.default(object,
    filename = paste(name, ".Rd", sep = ""),
    force.function = FALSE, \dots)

prompt.data.frame(object,
    filename = paste(name, ".Rd", sep = ""), \dots)
}
\alias{prompt}
\alias{prompt.default}
\alias{prompt.data.frame}
\arguments{
  \item{object}{an \R object, typically a function}
  \item{filename}{name of the output file}
  \item{force.function}{treat \code{object} as function in any case}
  \item{\dots}{further arguments passed to or from other methods.}
}
\description{
  Facilitate the constructing of files documenting \R functions.
}
\details{
  An ASCII file \code{filename} is produced containing the proper
  function and argument names of \code{object}.  You have to edit it
  before adding the documentation to the source tree, i.e., (currently)
  to \file{\$R\_HOME/src/library/base/man/}.
}
\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 \code{base} library.  We are trying to settle on a preferred
  format for the documentation.
}
\seealso{
  \code{\link{help}} and the chapter on ``Writing \R documentation'' in
  ``Writing \R Extensions'' (see the \file{doc/manual}
  subdirectory of the \R source tree).
}
\author{Douglas Bates for \code{prompt.data.frame}}
\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}
\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 }
\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}
\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}
\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, \dots)
qqline(y, \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{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 corresponding y coordinates}
  }
\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}
\name{qr}
\title{The QR Decomposition of a Matrix}
\usage{
qr(x, tol=1e-07)
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)

is.qr(x)
as.qr(x)
}
\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}
\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}.}
  \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 matrix or QR decomposition.}
  \item{k}{effective rank.}
}
\description{
  \code{qr} computes the QR decomposition of a matrix.  It provides an
  interface to the techniques used in the LINPACK routine DQRDC
  or (for complex matrices) the LAPACK routine 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{qr.solve} solves systems of equations via the QR decomposition.

  \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/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).}
  \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 complex case.}
  \item{pivot}{information on the pivoting strategy used during
    the decomposition.}
}
\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}}.

  The complex case uses column pivoting and does not attempt to detect
  rank-deficient matrices.
}
\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.\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

\testonly{## tests of complex case
set.seed(1)
A <- matrix(rnorm(25), 5, 5, dimnames=list(1:5, letters[1:5]))
qr.solve(A, 1:5)
A[] <- as.complex(A)
qr.coef(qr(A), 1:5)
qr.solve(A, 1:5)}
\testonly{## check for rank-deficient cases
X <- cbind(1:3, 1:3, 1)
stopifnot(all.equal(qr.X(qr(X)), X))}
}
\keyword{algebra}
\keyword{array}
\keyword{regression}
\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 = 1)
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 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.}
}
\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.  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 :
all((1 - X /( Q \%*\% R))< 100*.Machine$double.eps)#TRUE

dim(Qc <- qr.Q(qrstr, complete=TRUE)) # Square: dim(Qc) == rep(nrow(x),2)
all((crossprod(Qc) - diag(nrow(x))) < 10*.Machine $double.eps)

QD <- qr.Q(qrstr, D=1:p)      # QD == Q \%*\% diag(1:p)
all(QD - Q \%*\% diag(1:p)  < 8* .Machine$double.eps)

dim(Rc <- qr.R(qrstr, complete=TRUE)) # == dim(x)
dim(Xc <- qr.X(qrstr, complete=TRUE)) # square: nrow(x) ^ 2
all(Xc[,1:p] == X)
}
\keyword{algebra}
\name{quakes}
\title{Locations of Earthquakes off Fiji}
\usage{data(quakes)}
\alias{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.
}
\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.
}
\details{
  There are two clear planes of seismic activity.  One is a major
  plate junction; the other is a 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}
\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{
\method{quantile}{default}(x, probs = seq(0, 1, 0.25), na.rm = FALSE,
         names = TRUE, ...)
}
\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 <- order(x)} (the ``order statistics'') 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.
}
\seealso{\code{\link[stepfun]{ecdf}} for empirical distributions of
  which \code{quantile} is the "inverse".
  \code{\link{boxplot.stats}} and \code{\link{fivenum}} for computing
  ``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)

n <- length(x) ## the following is exact, because 1/(1001-1) is exact:
stopifnot(sort(x) == quantile(x, probs = ((1:n)-1)/(n-1), names=FALSE))

n <- 777
ox <- sort(x <- round(rnorm(n),1))# round() produces ties
ox <- c(ox, ox[n]) #- such that ox[n+1] := ox[n]
p <- c(0,1,runif(100))
i <- floor(r <- 1 + (n-1)*p)
f <- r - i
all(abs(quantile(x,p) - ((1-f)*ox[i] + f*ox[i+1])) < 20*.Machine$double.eps)
}
\keyword{univar}
\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
    `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.
}
\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}
\name{randu}
\alias{randu}
\title{Random Numbers from Congruential Generator}
\usage{data(randu)}
\description{
    400 triples of successive random numbers were taken from the VAX
    FORTRAN function RANDU running under VMS 1.5.
}
\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}
\name{range}
\alias{range}
\alias{range.default}
\title{Range of Values}
\usage{
range(\dots, na.rm = FALSE)
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{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
}
\seealso{
  \code{\link{min}},
  \code{\link{max}},
  \code{\link{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}
\name{rank}
\alias{rank}
\title{Sample Ranks}
\description{
  Returns the sample ranks of the values in a numeric vector.
  Ties result in ranks being averaged.
}
\usage{
rank(x, na.last = TRUE)
}
\arguments{
  \item{x}{a numeric vector.}
  \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.}
}
\seealso{\code{\link{order}} and \code{\link{sort}}.}
\examples{
(r1 <- rank(x1 <- c(3,1,4,59,26)))
(r2 <- rank(x2 <- c(3,1,4,5,9,2,6,5,3,5))) # ties

## rank() is "idempotent": rank(rank(x)) == rank(x) :
stopifnot(rank(r1) == r1, rank(r2) == r2)
}
\keyword{univar}
\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}
\name{read.ftable}
\alias{read.ftable}
\alias{write.ftable}
\alias{as.table.ftable}
\title{Manipulate Flat Contingency Tables}
\description{Read, write and coerce ``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 ``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 ``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}
\name{read.fwf}
\alias{read.fwf}
\title{Read Fixed Width Format Files}
\description{
  Read a ``table'' of \bold{f}ixed \bold{w}idth \bold{f}ormatted data
  into a \code{\link{data.frame}}.
}
\usage{
read.fwf(file, widths, 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{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}
\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}
\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.

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

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

  \item{fill}{logical. If \code{TRUE} then in case the rows have unequal
    length, blank fields are implicitly added.}

  \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 ``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{read.table.url}} for ``reading'' data from the internet;
  \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.
}
\keyword{file}
\keyword{connection}
\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.  \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 shorted 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.
}

\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}
\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{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}
\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}
\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}
\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}
\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)
}
\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.
    Non-positive values of \code{density} also inhibit the drawing
    of shading lines.}
  \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.}
  \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 (``e\bold{xp}an\bold{d}''); defaults to
    \code{par("xpd")}.  See \code{\link{par}(xpd= )}.}
}
\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 ``standard'' box around the plot;
  \code{\link{polygon}} and \code{\link{segments}} for flexible line
  drawing.
}
\examples{
## set up the plot region:
op <- par(bg = "thistle")
plot(c(100, 250), c(300, 450), type = "n", xlab="",
     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\"))")
par(op)
}
\keyword{aplot}
\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{
    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() 
 gc() # trigger cleanup
}
\keyword{programming}\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}.
}
\author{B. D. Ripley}

\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}
\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)
}
\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.}
}
\seealso{
#ifdef unix
  \code{\link{REMOVE}} for a command line version;
#endif
  \code{\link{install.packages}} for installing packages.
}
\keyword{utilities}
\name{rep}
\alias{rep}
\title{Replicate Elements of Vectors and Lists}
\usage{
rep(x, times, length.out)
}
\arguments{
  \item{x}{a vector (of any mode including a list) or a pairlist.}
  \item{times}{integer.  A vector giving the number of times to repeat
    each element. Either of length 1 or \code{length(x)}.}
  \item{length.out}{integer.  (Optional.)  The desired length of the
    output vector.}
}
\description{
  \code{rep} replicates the values in \code{x}
  according to the values given in \code{times}
  and \code{length.out}.
}

\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.
}
\note{
  If the original vector has names, these are also replicated and so
  will almost always contain duplicates.
}
\seealso{
  \code{\link{seq}}, \code{\link{sequence}}.
}
\examples{
rep(1:4, 2)
rep(1:4, c(2,2,2,2))     # same as above, length 8.
rep(1:4, c(2,1,2,1))
rep(1:4, c(2,2,2,2), 4)  # first 4 only.
rep(1:4, c(2,2,2,2), 10) # 8 intgers 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)
}
\keyword{manip}
\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.
}
\note{
  \code{x} is unchanged: remember to assign the result.
}
\keyword{manip}
% file replications.Rd
% copyright (C) 1998 B. D. Ripley
%
\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))}.
}
\author{B. D. Ripley}

\seealso{\code{\link{model.tables}}}

\examples{
## From Venables and Ripley (1997) p.210.
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}
\name{reshape}
\alias{reshape}
%- Also NEED an `\alias' for EACH other topic documented here.
\title{Reshape grouped data}
\description{
  This function reshapes a dataframe between `wide' format with repeated
measurements in separate columns of the same record and `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, fix.row.names = TRUE,
    split=list(regexp="\\.",include=FALSE)
}
%- maybe also `usage' for other objects documented here.
\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 (`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/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}{\code{"wide" to reshape to wide format, "long" to
  reshape to long format}}
  \item{fix.row.names}{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 `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
  `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 `long' format dataset also needs a `time'
  variable identifying which time point each record comes from and an
  `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}

\name{reshapeLong-deprecated}
\alias{reshapeLong-deprecated}
\title{Reshape data frame to long format}
\description{
  (EXPERIMENTAL). Convert data frame with repeated measurements in
  wide format with repeated
  observations in multiple variables across rows to long
  format, 1 row per observation.
}
\usage{
reshapeLong(x, jvars, ilev=row.names(x), jlev=names(x)[jvars],
            iname="reshape.i", jname="reshape.j", vname="reshape.v")
}
%- maybe also `usage' for other objects documented here.
\arguments{
  \item{x}{The data frame to convert}
  \item{jvars}{The variables to reshape by}
  \item{ilev}{Levels of 1st indexing factor}
  \item{jlev}{Levels of 2nd indexing factor}
  \item{iname}{Name of 1st indexing factor}
  \item{jname}{Name of 2nd indexing factor }
  \item{vname}{Name of variable holding the combined values of the
    "across" variables}
}
\details{
  This causes the values in \code{jvars} to be combined into a single
  variable, all other variables being replicated the relevant number of
  times. Two factors are added to the data frame indicating rows and
  columns of the original data format.
}
\value{
   The reshaped data frame.
}
\note{The same substitution tricks are used for \code{jvars} as for the
  \code{select} argument to \code{subset}. I.e.\ the argument is treated
  as an expression and variables are replaced with their number in the
  data frame, allowing ranges of variables to be specified.
}
\section{Bugs}{There ought to be a way to have multiple sets of
  \code{jvars} variables.} 

\seealso{\code{\link{reshapeWide}}, \code{\link{stack}} }

\examples{
(dd<-as.data.frame(matrix(1:24,4)))
reshapeLong(dd,V3:V5)
}
\keyword{ manip }%-- one or more ...
\name{reshapeWide-deprecated}
\alias{reshapeWide-deprecated}
\title{Reshape data frame to wide format}
\description{
  (EXPERIMENTAL). Convert data frame with repeated measurements in long
  format, 1 row per observation to wide format with repeated
  observations in multiple variables across rows.
}
\usage{
reshapeWide(x, i=reshape.i, j=reshape.j,
            val=reshape.v, jnames=levels(j))
}
\arguments{
  \item{x}{The data frame to convert}
  \item{i}{Factor or numeric. Indicates observations in same row of the
    wide format}
  \item{j}{Factor or numeric. Indicates observations in same column of
    wide format}
  \item{val}{Value to reshape for.}
  \item{jnames}{Names of new variables in reshaped frame}
}
\details{
  \code{val}, \code{i}, and \code{j} are interpreted relative to
  \code{x}.
  This essentially places the values of \code{val} in a table defined by
  \code{i} and \code{j}, which are assumed to span the data set (exactly
  one observation in each cell of their cross-tabulation). Any
  other variables in the data frame will be
  assumed to have the same value for all values of \code{j} (given
  \code{i}) and are
  collapsed into a single value.
}
\value{
   The reshaped data frame.
}
\note{The defaults are set to use the names that result
  from a call to \code{reshapeLong}.}

\section{WARNING}{There is no check that the names given to the new
  columns are
  valid identifiers or unique within the data frame. Variables in
  \code{x} are not checked to have constant values given \code{i}.}
\section{Bugs}{There ought to be a way to have multiple \code{val} variables.}

\seealso{\code{\link{reshapeLong}}, \code{\link{unstack}}}

\examples{
dd<-as.data.frame(matrix(1:24,4))
(dd1<-reshapeLong(dd,V3:V5))
reshapeWide(dd1)
reshapeWide(dd1,jnames=c("A","B","C"))
}
\keyword{ manip }%-- one or more ...
\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
  `residuals' and not `resid'.)

  Methods can make use of \code{\link{naresid}} methods to compensate
  for the omission of missing values.  The default method does.
}
\seealso{
  \code{\link{coefficients}}, \code{\link{fitted.values}},
  \code{\link{glm}}, \code{\link{lm}}.
}
\keyword{models}
\keyword{regression}
\name{restart}
\alias{restart}
\title{Restart an Expression}
\usage{
restart(on = TRUE)
}
\arguments{
  \item{on}{if true a jump point is set; if false the jump point is removed.}
}
\description{
  \code{restart} performs a type of non-local return.
}
\details{
  When \code{restart} is called with \code{on = TRUE} the evaluator
  marks that function as a return point.  Any errors or signals
  (such as control-C on Unix) cause control to return to the start of
  the function containing the call to \code{restart}. The most recently
  established function is always entered first.
}
\note{
  The direct use of \code{restart} is likely to result in an infinite loop.
  Use \code{\link{try}} unless you are \bold{sure} you know what
  you are doing.
}
\seealso{
  \code{\link{options}} for setting error handlers and suppressing the
  printing of error messages.
}
\keyword{programming}
\name{rev}
\alias{rev}
\title{Reverse a Vector's Elements}
\usage{
rev(x)
}
\arguments{
  \item{x}{a vector.}
}
\description{
  \code{rev}
  provides a reversed version of its argument.
  It can be used in combination with
  \code{sort} to obtain vectors sorted into descending order.
}
\seealso{\code{\link{seq}}, \code{\link{sort}}.}
\examples{
x <- c(1:5,5:3)
# sort into descending order
rev(sort(x))
stopifnot(rev(1:7) == 7:1)#- don't need `rev' here
}
\keyword{manip}
\name{rgb}
\title{RGB Color Specification}
\usage{
rgb(red, green, blue, names=NULL)
}
\alias{rgb}
\description{
This function creates ``colors'' corresponding to
the given intensities (between 0 and 1) 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{par}.
}
\arguments{
  \item{red, blue, green}{vector in \eqn{[0, 1]}.}
  \item{names}{character. The names for the resulting vector.}
}
\seealso{
  \code{\link{col2rgb}} the ``inverse'' for translating \R colors to RGB
  vectors.\cr
  \code{\link{rainbow}}, \code{\link{hsv}}, \code{\link{gray}}.
}
\examples{
rgb(0,1,0)
u01 <- seq(0,1, length=11); all(rgb(u01,u01,u01) == gray(u01))
reds <- rgb((0:15)/15, g=0,b=0, names=paste("red",0:15,sep="."))
reds
}
\keyword{color}
\name{rivers}
\alias{rivers}
\title{Lengths of Major North American Rivers}
\description{
  This data set gives the lengths (in miles) of 141 ``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}
\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)
\method{print}{rle}(x, digits = getOption("digits"), \dots)
inverse.rle(x, \dots)
}
\arguments{
  \item{x}{a simple vector [as argument of rle()],\cr
    a class "rle" object [as argument of \code{print()} or
    \code{inverse.rle()}].}
  \item{digits, \dots}{potentially further arguments to the
    corresponding method.}
}
\value{
  \code{rle()} returns an object of class "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}
\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.
   }
\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}
\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"))
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.
}
\note{
  \code{trunc} is not generic, so \code{trunc.POSIXt} has to be called
  explicitly.
}
\value{
  An object of class \code{"POSIXlt"}.
}
\seealso{\code{\link{DateTimeClasses}}}

\examples{
round(.leap.seconds + 1000, "hour")
trunc.POSIXt(Sys.time(), "day")
}
\keyword{chron}
\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}.
}
\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}
\name{rowsum}
\alias{rowsum}
\title{
Give Row Sums of a Matrix, Based on a Grouping Variable
}
\description{
  Compute sums across rows of a matrix for each level of a grouping
  variable.
}
\usage{
rowsum(x, group, reorder = TRUE)
}
\arguments{
  \item{x}{a matrix 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 are not allowed.}
  \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 (and may run faster for large matrices).
    The default is to reorder the data, so as to agree with
    \code{tapply} (see example below).}
}
\value{
  a matrix containing the sums.  There will be one row per unique value
  of \code{group}.
}
\author{Terry Therneau}
\seealso{
  \code{\link{tapply}}
}
\examples{
x <- matrix(runif(100), ncol=5)
group <- sample(1:8, 20, TRUE)
xsum <- rowsum(x, group)

## same result another way, slower, and temp may be much larger than x
temp <- model.matrix(~ a - 1, data.frame(a=as.factor(group)))
xsum2<- t(temp) \%*\% x

## same as last one, but really slow
xsum3 <- tapply(x, list(group[row(x)], col(x)), sum)
}
\keyword{manip}
% Converted by Sd2Rd version 0.2-a3.
\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)
}
\arguments{
 \item{x}{A numeric vector}
 \item{ticksize}{The length of the ticks making up the `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.}
}
\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.
}
\author{B. D. Ripley}
\seealso{\code{\link{jitter}} which you may want for ties in \code{x}.}
\examples{
data(faithful)
attach(faithful)
plot(density(eruptions, bw=0.15))
rug(eruptions)
rug(jitter(eruptions, amount = .01), side = 3, col = "light blue")
detach("faithful")
}
\keyword{hplot}
\name{sample}
\title{Random Samples and Permutations}
\usage{
sample(x, size, replace = FALSE, prob = NULL)
}
\alias{sample}
\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}{A positive 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.}
}
\description{
  \code{sample} takes a sample of the specified size from
  the elements of \code{x} using either with or without replacement.
}
\details{
  If \code{x} has length 1, sampling takes place from
  \code{1:x}.

  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.
}
\examples{
x <- 1:12
# a random permutation
sample(x)
# bootstrap sampling
sample(x,replace=TRUE)

# 100 Bernoulli trials
sample(c(0,1), 100, replace = TRUE)
}
\keyword{distribution}
\name{save}
\title{Save R Objects}
\usage{
save(\dots, list = character(0), file = "", 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)
}
\alias{save}
\alias{save.image}
\alias{sys.save.image}
\alias{sys.load.image}
\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.  NULL specifies
    the current default format.  The version used from \R 0.99.0 to
    \R 1.3.1 is 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, or if \code{\link{gzfile}} is not
    supported on this platform.}
  \item{safe}{logical.  If 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.}
  }
}
\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}.

  \code{save.image()} is just a short-cut for ``save my current
  environment'',
  i.e., \code{save(list = ls(all=TRUE), file = ".RData")}. It is what also
  happens with \code{\link{q}("yes")}.
}
\details{
  Almost all current \R platforms (including Windows and Macintosh)
  use the XDR representation of binary objects in binary save-d files,
  and these are portable across all XDR-compliant implementations.

  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.
}
\seealso{
  \code{\link{dput}}, \code{\link{dump}}, \code{\link{load}}.
}
\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 dafaults using option:
options(save.image.defaults=list(ascii=TRUE, safe=FALSE))
save.image()
unlink(".RData")
}
\keyword{file}
\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 Rterm but not in embedded/DCOM versions.
#endif
#ifdef unix
  This works under the \code{readline} and GNOME interfaces, but not if
  \code{readline} is not available.
#endif
}
\note{
  If you want to save the history (almost) every session, you can put a
  call to \code{savehistory()} in \code{\link{.Last}}.
}
\keyword{utilities}
\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)
}
\synopsis{
scale.default(x, center = TRUE, scale = TRUE)
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.
}
\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.
}
\seealso{
  \code{\link{sweep}} which allows centering (and scaling) with
  arbitrary statistics.
}
\examples{
x <- matrix(1:10, nc=2)
(centered.x <- scale(x, scale=FALSE))
cov(centered.scaled.x <- scale(x))# all 1
\testonly{## test out NA handling
tm <- matrix(c(2,1,0,1,0,NA,NA,NA,0), nrow=3)
scale(tm, , FALSE)
scale(tm)
}}
\keyword{array}
\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).

    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
    (``fields'').}

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

  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.

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

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

\seealso{
  \code{\link{par}}, \code{\link{layout}}, \code{\link{Devices}},
  \code{dev.*}
}

\examples{
if (interactive()) {
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}
\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 dataframe, 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}
\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}}.
}
\author{B. D. Ripley}
\seealso{\code{\link{model.tables}}}

\keyword{internal}
% file se.contrast.Rd
% copyright (C) 1998 B. D. Ripley
%
\name{se.contrast}
\title{Standard Errors for Contrasts in Model Terms}
\usage{
se.contrast(object, \dots)
se.contrast.aov(object, contrast.obj,
  coef = contr.helmert(ncol(contrast))[, 1], data = NULL, \dots) 
se.contrast.aovlist(object, contrast.obj,
  coef = contr.helmert(ncol(contrast))[, 1], data = NULL, \dots)
}
\alias{se.contrast}
\alias{se.contrast.aov}
\alias{se.contrast.aovlist}
\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 as returned by \code{contrasts}.}
 \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 directly with 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.
}
\value{
  A vector giving the standard errors for each contrast.
}
\author{B.D. Ripley}
\seealso{
  \code{\link{contrasts}},
  \code{\link{model.tables}}
}
\examples{
## From Venables and Ripley (1997) p.210.
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)
}
\keyword{models}
\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 \emph{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.
}
\seealso{\code{\link{attach}} and \code{\link{detach}} to change the
  search ``path'', \code{\link{objects}} to find \R objects in there.
}
\examples{
search()
searchpaths()
}
\keyword{data}

\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{
\method{seek}{connection}(con, where = NA, origin = "start", rw = "", \dots)
\method{truncate}{connection}(con, \dots)

isSeekable(con)
}
\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 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.
#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}
\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).
}
\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}
\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, ...)
}
\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{"week"},
    \code{"month"} or \code{"year"}.  This can optionally be
    preceded by an integer and a space.
  }
}
\value{
  A vector of class \code{"POSIXct"}.
}
\seealso{\code{\link{DateTimeClasses}}}

\examples{
## first days of years in the (commonly used) 20th century
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")
}
\keyword{manip}
\keyword{chron}
\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 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)}.

  If \code{from} and \code{to} are factors of the same length, then
  \code{from : to} returns the ``cross'' of the two.
}
\value{
  The result is of \code{mode} \code{"integer"} if \code{from} is
  (numerically equal to an) integer and \code{by} is not specified.
}
\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)
stopifnot(
 3 == seq(3,3,  by=pi),
 3 == seq(3,3.1,by=pi),
 seq(1,6,by=3) == c(1,4),
 seq(10,4.05,by=-3) == c(10,7)
)

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}
\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}
\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\%}}}
\author{B. D. Ripley}

\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}
\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))}
\testonly{r <- as.numeric(row.names(showConnections()))
close(getConnection(r))}
showConnections()
}
\keyword{connection}
\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}

\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.
  These too 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.
}
\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}
\name{sleep}
\alias{sleep}
\title{Students' Sleep Data}
\usage{data(sleep)}
\description{
  Data which show the effect of two soporific drugs (increase in hours
  of sleep) on groups consisting of 10 patients each.
}
\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}
\name{slotOp}
\title{Extract or Replace Slots}
\alias{@}
\alias{@<-}
\description{
  Operators to extract or replace tbe contents of a slot in a object
  with a formal class structure.
}
\usage{
object@name
object@name <- value
}
\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 \code{methods}.
  See \code{\link[methods]{slot}} for further details.
}
\seealso{
  \code{\link{Extract}}, \code{\link[methods]{slot}}
}
\keyword{manip}
\name{solve}
\title{Solve a System of Equations}
\usage{
\method{solve}{default}(a, b, tol = 1e-7, ...)
}
\alias{solve}
\alias{solve.default}
\alias{solve.qr}
\arguments{
  \item{a}{a numeric matrix containing the coefficients of the linear
    system.}
  \item{b}{a numeric vector or matrix giving the right-hand side(s) of
    the linear system.  If omitted, \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}.}
  \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 version 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 beavailable on all
  platforms.
}
\seealso{
  \code{\link{backsolve}}, \code{\link{qr.solve}}.
}
\examples{
hilbert <- function(n) { i <- 1:n; 1 / outer(i - 1, i, "+") }
h8 <- hilbert(8); h8
\dontrun{solve(h8) # gives error: `singular'}
sh8 <- solve(h8, tol = 1e-10)
round(sh8 \%*\% h8, 3)

A <- hilbert(4)
A[] <- as.complex(A)
## might not be supported on all platforms
try(solve(A))
}
\keyword{algebra}
\name{sort}
\alias{sort}
\alias{is.unsorted}
\title{Sorting a Vector}
\description{
  Sort a numeric or complex vector (partially) into ascending order.
}
\usage{
sort(x, partial = NULL, na.last = NA)
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{na.rm}{logical. Should missing values be removed?}
}
\details{
  If \code{partial} is non \code{NULL}, it is taken to contain indexes
  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.

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

stopifnot(!is.unsorted(sort(x)),
          !is.unsorted(LETTERS),
           is.unsorted(c(NA,1:3,2), na.rm = TRUE))
}
\keyword{univar}
\keyword{manip}
\keyword{arith}
\name{source}
\title{Redirect Input}
\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 ``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. 
}
\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}
\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{
  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 \code{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 \code{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}
\name{split}
\title{Divide into Groups}
\alias{split}
\alias{split.default}
\alias{split.data.frame}
\description{
  \code{split} divides the data in the vector \code{x} into the groups
  defined by \code{f}.
}
\usage{
split(x, f)
split.default(x, f)
split.data.frame(x, f)
}
\arguments{
  \item{x}{vector containing the values to be divided into groups.}
  \item{f}{a ``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.}
}
\details{ 
  \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.
}
\value{
  The value returned 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.
}
\seealso{\code{\link{cut}}}
\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)

## 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}
\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)
stack.default(x, \dots)
stack.data.frame(x, select, \dots)
unstack(x, \dots)
unstack.default(x, form, \dots)
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}
\name{stackloss}
\alias{stackloss}
\alias{stack.loss}
\alias{stack.x}
\title{Brownlee's Stack Loss Plant Data}
\usage{data(stackloss)}
\description{Operational data of a plant for the oxidation of ammonia to
  nitric acid.}
\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{
  ``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{
  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}

\name{standardGeneric}
\alias{standardGeneric}
\alias{objWithClass}
\alias{dataClass}
\alias{topicName}
\title{Formal Method System Placeholders}
\description{
  These routines are primitives used with the \code{methods} package.
  They should not be used without it and do not need to be called
  directly in any case.

  \describe{
    \item{\code{standardGeneric}:}{
      dispatch the method defined for generic function named \code{f},
      using the actual arguments in the frame from which
      \code{standardGeneric} is called.
    }
    \item{\code{objWithClass}:}{
      return the result of setting the class of \code{object} to
      \code{value}.  Defined as a separate primitive function because R
      types cannot generally be changed in place.
    }
    \item{\code{dataClass}:}{ returns a single string for the class of
      \code{object} even in the case that the object has an old-style
      class attribute with multiple strings.
    }
    \item{\code{topicName}:}{
      the string used internally to find documenation of the given type
      and topic.  Called by the \code{?} operator and the special prompt
      functions in the methods package.
    }
  }
}
\usage{
standardGeneric(f)
objWithClass(object, value)
dataClass(object)
topicName(type, topic)
}
\author{ John Chambers }
\keyword{programming}
\keyword{internal}
\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 ``spider'' (or ``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)),
      \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 ``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.}
  }
}
\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}
\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}
\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}
\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.
}
\seealso{\code{\link{anova.lm}}, \code{\link{anova.glm}}.}
\examples{
##-- Continued from  ``?glm'':
\testonly{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}
\name{state}
\alias{state}
\alias{state.abb}
\alias{state.area}
\alias{state.center}
\alias{state.division}
\alias{state.name}
\alias{state.region}
\alias{state.x77}
\title{States of the U.S.A.}
\usage{data(state)}
\description{Data sets related to the 50 states of the United States of
  America.}
\details{\R currently contains the following ``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}.
}
\keyword{datasets}
\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.}
}
\examples{
data(islands)
stem(islands)
stem(log10(islands))
}
\keyword{univar}
\keyword{distribution}
% file step.Rd
% copyright (C) 1998 B. D. Ripley
%
\name{step}
\title{
Choose a model by AIC in a Stepwise Algorithm
}
\usage{
step(object, scope, scale = 0,
     direction = c("both", "backward", "forward"), 
     trace = 1, keep = NULL, steps = 1000, k = 2, \dots)
}
\alias{step}
\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 (or the initial model is the
    upper model) 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).
}
\description{
  Select a formula-based model by AIC.
}
\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}}
}
\author{B. D. Ripley}
\examples{
example(lm)
step(lm.D9)  

data(swiss)
summary(lm1 <- lm(Fertility ~ ., data = swiss))
slm1 <- step(lm1)
summary(slm1)
slm1$anova
}
\keyword{models}
\name{stop}
\title{Stop Function Execution}
\usage{
stop(message = NULL, call. = TRUE)
geterrmessage()
}
\alias{stop}
\alias{geterrmessage}
\arguments{
  \item{message}{a character vector (of length 1) 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, prints the
  message given as its argument, then executes an error action.

  \code{geterrmessage} gives the last error message.
}
\details{
  The error action is controlled by the current error handler set by
  \code{options(error=)}. The default behaviour  (the \code{NULL}
  error-handler) in interactive use is
  to return to the top level prompt, and in non-interactive use to
  (effectively) call \code{\link{q}("no", status=1, runLast=FALSE}).
}
\value{
  \code{geterrmessage} gives the last error message, as character string
  ending in \code{"\n"}.
}
\seealso{
  \code{\link{warning}}, \code{\link{restart}} to catch errors and retry,
  and \code{\link{options}} for setting error handlers.
  \code{\link{stopifnot}} for validity testing.
}
\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}
\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}
\name{str}
\title{Compactly Display the Structure of an Arbitrary R Object}
\usage{
str(object, \dots)
str.data.frame(object, \dots)
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, mode = "any",
        max.level = 1, give.attr = FALSE)
lsf.str(pos = 1, pattern, \dots)
}
\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
  ``diagnostic'' function and an alternative to \code{\link{summary}}
  (and to some extent, \code{\link{dput}}).  Ideally, only one line for
  each ``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 ``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 ``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{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()

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")
\testonly{
 ##-- Some "crazy" objects
 str(array(1:5, dim=20))
 str(factor(character(0)))
 str(as.data.frame(NULL))
}
}
\keyword{print}
\keyword{documentation}
\keyword{utilities}
\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 are 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,
           xlim=NULL, ylim=NULL, main="", ylab="", xlab="",
           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{xlim, ylim, main, ylab, xlab, 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 <- round(rnorm(50), 1)
stripchart(x)
}
\keyword{hplot}
\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.
}
\synopsis{
format.POSIXct(x, format = "", tz = "", usetz = FALSE, \dots)
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")
}
\usage{
format.POSIXct(x, format = "", tz = "", usetz = FALSE, \dots)
format.POSIXlt(x, format = "", usetz = FALSE, \dots)

\method{as.character}{POSIXt}(x, \dots)

strftime(x, format="\%Y-\%m-\%d \%X", 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 vector. 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.
#ifdef mac
  Under MacOS only the current timezone \code{""} and UTC (or GMT)
  are supported.
#endif

  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}
\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 ``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("asfef", "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"
}
\keyword{character}
\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.
}
\examples{
structure(1:6, dim = 2:3)
}
\keyword{attribute}
\keyword{manip}
\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.}
  \item{units}{character indicating in which units \code{s} is measured;
    must be one of \code{"user"}, \code{"inches"}, \code{"figure"} .}
  \item{cex}{character expansion to which is applies. Per 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{
  integer vector with the same length as \code{s}, giving the
  width for each \code{s[i]}.
}
\seealso{
  \code{\link{text}}, \code{\link{nchar}}
}
\examples{
str.ex <- c("W","w","I",".","WwI.")
op <- par(pty='s'); plot(1:100,1:100); par('usr')
sw <- strwidth(str.ex); sw
sum(sw[1:4] == sw[5])#- since the last string contains the others
sw / strwidth(str.ex, cex = .5)
# between 1.5 and 4.2 (!),  font dependent

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")
table(shL)# all have same heights ...
mean(shL) / par("cin")[2] # should be 1 (exactly?)

swL <- strwidth(all.lett)
swL <- 3 * swL / min(swL)
all(swL == round(swL))#- TRUE !
swL <- as.integer(swL)
n.classes <- length(tL <- table(swL)); tL
iL <- order(swL)
structure(swL[iL], names = all.lett[iL])
lett.classes <- structure(vector("list", n.classes), names= names(tL))
for(i in 1:n.classes)
  lett.classes[[i]] <- all.lett[swL == as.numeric(names(tL)[i])]
lett.classes

sumex <- expression(sum(x[i], i=1,n), e^{i * pi} == -1)
strwidth(sumex)
strheight(sumex)

rm(sumex); par(op)#- reset to previous setting
}
\keyword{dplot}
\keyword{character}
\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}
\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)
subset.default(x, subset, \dots)
subset.data.frame(x, subset, select, \dots)
}
\arguments{
  \item{x}{object to be subsetted}
  \item{\dots}{how to subset, depends on object}
  \item{subset}{logical expression}
  \item{select}{expression, indicating variables to select from a
    data frame}
}
\details{
  For ordinary vectors, the result is simply
  \code{x[subset & !is.na(subset)]}.

  For dataframes, the \code{subset} argument works similarly on the
  rows.  Note that \code{subset} will be evaluated in the dataframe.

  The \code{select} argument exists only for dataframes.  It works by
  first replacing variable names in the selection expression with the
  corresponding column numbers in the dataframe and then using the
  resulting integer vector to index the columns.  This allows the use
  of the standard indexing conventions so that for examples ranges of
  variables can be specified easily.
}
\value{
  Selected rows and columns of the object \code{x}.
}
\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)

attach(airquality)
subset(Ozone, Temp > 80)
}
\keyword{manip}
\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.
}
\seealso{
  \code{\link{missing}} for argument ``missingness''.
}
\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}
\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.
}
\seealso{
 \code{\link{strsplit}}, \code{\link{paste}}, \code{\link{nchar}}.
}
\examples{
substr("abcdef",2,4)
print(ss <- substring("abcdef",1:6,1:6))
stopifnot(ss == strsplit ("abcdef",NULL)[[1]])
## strsplit is more efficient ...

substr(rep("abcdef",4),1:4,4:5)
x <- c("asfef", "qwerty", "yuiop[", "b", "stuff.blah.yech")
stopifnot(substr(x, 2, 5) == substring(x, 2, 5))
substr(x, 2, 5)
substring(x, 2, 4:6)

substring(x, 2) <- c("..", "+++")
x
}
\keyword{character}
\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 vectors.}
  \item{na.rm}{logical. Should missing values be removed?}
}
\keyword{arith}
\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{class}} of the first argument.
}
\usage{
summary(object, \dots)

summary.default   (object, \dots, digits = max(3, getOption("digits")-3))
summary.data.frame(object, maxsum = 7,
                   digits = max(3, getOption("digits")-3), \dots)
summary.factor    (object, maxsum = 100, \dots)
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}}.
}
\examples{
data(attenu)
summary(attenu, digits = 4) #-> summary.data.frame(...), default precision
summary(attenu $ station, maxsum = 20) #-> summary.factor(...)
}
\keyword{methods}
\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 names 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.
}
\author{B.D. Ripley}


\seealso{\code{\link{aov}}}

\examples{
## Example on producing plastic filem 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}
\name{sunflowerplot}
\alias{sunflowerplot}
\title{Produce a Sunflower Scatter Plot}
\description{
  Multiple points are plotted as ``sunflowers'' with multiple leaves
  (``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 ``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 ``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}
\name{sunspots}
\alias{sunspots}
\title{Monthly Sunspot Numbers, 1749--1983}
\usage{data(sunspots)}
\description{
  Monthly mean relative sunspot numbers from 1749 to 1983.  Collected at Swiss
  Federal Observatory, Zurich until 1960, then Tokyo Astronomical
  Observatory.
}
\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 \code{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}
\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))
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{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} provides an interface to the LINPACK routine DSVDC.
  \code{La.svd} provides an interface to 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.

  \code{La.svd} is preferred to \code{svd} for new projects, but it is
  not an exact replacement as it returns the transpose of the right
  singular vector matrix, and the signs of the singular vectors may differ
  from those given by \code{svd}.  (They may also differ between methods
  and between platforms.)

  Both functions handle complex matrices via LAPACK routine ZGESVD.

  Computing the singular vectors is the slow part for large matrices.

  Using \code{method="dgesdd"} requires IEEE 754 arithmetic.  Should
  this not be supported on your platform, \code{method="dgesvd"} is
  used, with a warning.
}
\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 components in the returned value correspond directly
  to the values returned by DSVDC.
  \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}.}
  \item{v}{a matrix whose columns contain the right singular vectors of
    \code{x}.}

  For \code{La.svd} the return value replaces \code{v} by \code{vt}, the
  (conjugated if complex) transpose of \code{v}.
}
\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.\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))
Eps <- 100 * .Machine$double.eps

D <- diag(s$d)
stopifnot(abs(X - s$u \%*\% D \%*\% t(s$v)) < Eps)#  X = U D V'
stopifnot(abs(D - t(s$u) \%*\% X \%*\% s$v) < Eps)#  D = U' X V

X <- cbind(1, 1:7)
str(s <- svd(X)); D <- diag(s$d)
stopifnot(abs(X - s$u \%*\% D \%*\% t(s$v)) < Eps)#  X = U D V'
stopifnot(abs(D - t(s$u) \%*\% X \%*\% s$v) < Eps)#  D = U' X V

}
\keyword{algebra}
\keyword{array}

\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.
}
\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}
\name{swiss}
\title{Swiss Fertility and Socioeconomic Indicators (1888) Data}
\usage{data(swiss)}
\alias{swiss}
\description{
  Standardized fertility measure and socio-economic indicators for each
  of 47 French-speaking provinces of Switzerland at about 1888.
}
\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}, ``common standardized
    fertility measure''\cr
    [,2] \tab Agriculture\tab \% of males involved in agriculture
    as occupation\cr
    [,3] \tab Examination\tab \% ``draftees'' receiving highest mark
    on army examination\cr
    [,4] \tab Education \tab \% education beyond primary school for
    ``draftees''.\cr
    [,5] \tab Catholic \tab \% catholic (as opposed to ``protestant'').\cr
    [,6] \tab Infant.Mortality\tab live births who live less than 1
    year.
  }

  All variables but `Fertility' give proportions of the population.
}
\details{
  (paraphrasing Mosteller and Tukey):

  Switzerland, in 1888, was entering a period known as the ``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 ``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 ``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
  ``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.''
}
\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}
\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}.
}
\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(ch, a=1,    b=2:3),            "\n")
for(ch in ccc) cat(ch,":",switch(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}
\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, 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}{a vector giving the x coordinates of the symbols.}
  \item{y}{a vector giving the y coordinates of the symbols.}
  \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.
}
\references{
  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}
\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,
       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 ``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{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] `s[1]' c[2] `s[2]' \dots `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(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}
\name{sys.parent}
\title{Functions to Access the Function Call 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)
}
\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}
\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.}
}
\description{
  These functions provide access to \code{\link{environment}}s (``frames''
  in S terminology) associated with functions further up the calling stack.
}
\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).
}
\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}
\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 ``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.
}
\seealso{\code{\link{source}}, and \code{\link{library}} which uses
  \code{sys.source}.
}
\keyword{file}
\keyword{utilities}
\name{system.file}
\title{Find Names of R System Files}
\usage{
system.file(\dots, package = "base", lib.loc = NULL, pkg, lib)
}
\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.}
  \item{pkg}{previous name for argument \code{package}.  Deprecated.}
  \item{lib}{previous name for argument \code{lib.loc}.  Deprecated.}
}
\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
  \code{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}
\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 ``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).

  \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 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 and 2000.
#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:50) mad(runif(500)))
exT <- function(n = 100) {
  # 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):
exT()                 #- `1.4' on -O-optimized Ultra1
system.time(exT())    #~ +/- same
}
\keyword{utilities}
\name{t}
\alias{t}
\alias{t.default}
\alias{t.data.frame}
\title{Matrix Transpose}
\description{
Given a matrix or \code{\link{data.frame}} \code{x},
\code{t} returns the transpose (matrix or data.frame) of \code{x}.
}
\usage{
t(x)
}
\arguments{
  \item{x}{a matrix or data frame.}
}
\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(! a[, j] == ta[j, ]) stop("wrong transpose")
}
\keyword{array}
\name{table}
\title{Cross Tabulation}
\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, deparse.level = 1)
as.table(x, \dots)
is.table(x)
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}
  \item{dnn}{the names to be given to the dimensions in the result (`the
    dimname names').}
  \item{deparse.level}{controls how the default \code{dnn} is
    constructed.  See details.}
  \item{x}{an arbitrary \R object.}
  \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.}
}
\details{
  If the argument \code{dnn} is not supplied, the internal function
  \code{list.names} is called to compute the `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.

  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 \bold{ctest}
  currently only handles 2-d tables).

  \code{as.table} and \code{is.table} coerce to and test for contingency
  table, respectively.

  \code{as.data.frame.table} is a method for the generic function
  \code{as.data.frame} 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}}.
}
\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)

data(airquality)
attach(airquality)
# simple two-way contingency table
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))
}
\keyword{category}
\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{
\testonly{tabulate(numeric(0))}
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}
\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.
}
\seealso{
  the convenience function \code{\link{aggregate}} (using \code{tapply});
  \code{\link{apply}},
  \code{\link{lapply}} with its version
  \code{\link{sapply}}.
}
\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)

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}
\name{taskCallback}
\alias{addTaskCallback}
\alias{removeTaskCallback}
\title{Add or remove a top-level task callback}
\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.
}
\note{
  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}
\name{taskCallbackManager}
\alias{taskCallbackManager}
\title{Create an R-level task callback manager}
\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 `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}
\name{taskCallbackNames}
\alias{getTaskCallbackNames}
\title{Query the names of the current internal top-level task callbacks}
\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{
  This is an experimental feature and the interface may be changed
  in the future.
}
\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}
\name{tempfile}
\alias{tempfile}
\title{Create Names for Temporary Files}
\description{
  Returns a vector of character strings which can be used as
  names for temporary files.
}
\usage{
tempfile(pattern = "file")
}
\arguments{
  \item{pattern}{a non-empty character vector giving the initial part
    of the name.}
}
\value{
  A character vector giving the names of possible (temporary) files.

  Note that no files are generated by \code{tempfile}.
}
\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. The filenames will be in the directory given by
  the first found of the environment variables \code{TMP}, \code{TEMP},
  or \code{"/tmp"}.
#endif
#ifdef windows
  The filenames will be in the directory given by the first found of
  the environment variables \code{TMP}, \code{TEMP} and \code{R\_USER}
  (see \code{\link{Rconsole}}). 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
}
\seealso{\code{\link{unlink}} for deleting files.}
#ifdef unix
\examples{
tempfile(c("ab", "a b c"))   # give file name with spaces in!
}
#endif
\keyword{file}
\name{termplot}
\alias{termplot}
\alias{plot.gam}
\title{Plot regression terms}
\description{
  Plots regression terms against their predictors, optionally with
  standard errors and partial residuals added.
}
\usage{
termplot(model, data=model.frame(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",
         \dots)
}
\arguments{
  \item{model}{fitted model object}
  \item{data}{data frame in which the 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 ``term curve'',
    see \code{\link{lines}}.}
  \item{col.se, lty.se, lwd.se}{color, line type and line width for the
    ``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{\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 base package,
  \code{\link[survival]{coxph}} and \code{\link[survival]{survreg}} in the
  \code{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.

  It is often necessary to specify the \code{data} argument, because it is
  not possible to reconstruct eg \code{x} from a model frame containing
  \code{sin(x)}.  The \code{data} argument must have exactly the same
  rows as the model frame of the model object so, for example, missing
  data must  have been removed in the same way.
}
\seealso{For (generalized) linear models, \code{\link{plot.lm}} and
  \code{\link{predict.glm}}.}
\examples{
rs <- require(splines)
x <- 1:100
z <- factor(rep(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(rs) detach("package:splines")
}
\keyword{hplot}
\keyword{regression}
\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.
}
\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}
\name{terms.formula}
\alias{terms.formula}
\title{A function to 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{
terms.formula(x, specials=NULL, abb=NULL, data=NULL, neg.out=TRUE,
              keep.order=FALSE, ...)
}
\arguments{
  \item{x}{A formula.}
  \item{specials}{What functions in the formula should be marked as
    special in the terms object.}
  \item{abb}{Unused 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}{\code{TRUE} if terms with a minus, \code{-} should be
    removed. If FALSE these are kept in and indicate a negative order
    (for fractionate?).}
  \item{keep.order}{A logical value indicating whether the terms should
    keep their positions. If FALSE the terms are reordered so that main
    effects come first.}
  \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 is returned.
}
\seealso{ \code{\link{terms.object}},  \code{\link{terms.default}} }
\keyword{ models }
\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.

  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.
}
\value{
  An object with the following attributes:
  \item{factors}{A matrix of variables by terms showing which variables
    appear in which terms.}
  \item{term.labels}{A character vector containing the labels for each
    of the terms in the model.}
  \item{variables}{A 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. 

  An example of the \code{specials} argument can be seen in the
  \code{\link{aov}} function.
}
\seealso{
  \code{\link{terms}},
  \code{\link{terms.default}},
  \code{\link{formula}}.
}
%%--- MM: I would really like instructive examples here...
\keyword{models}
\name{text}
\title{Add Text to a Plot}
\usage{
text (x, \dots)
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.}
  \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}}.  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).
}
\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}
\name{textConnection}
\alias{textConnection}
\title{Text Connections}
\description{
  Input and output text connections.
}
\usage{
textConnection(object, open = "r")
}
\arguments{
  \item{object}{character.  A description of the connection. 
    For an input 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.}
}
\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.  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.

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

\seealso{
  \code{\link{connections}}, \code{\link{showConnections}},
  \code{\link{pushBack}}
}

\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}
\name{time}
\title{Sampling Times of Time Series}
\usage{
time(x, offset=0, \dots)
cycle(x, \dots)
frequency(x, \dots)
deltat(x, \dots)
}
\synopsis{
time(x, \dots)
time.default(x, offset=0, \dots)
time.ts(x, \dots)
cycle(x, \dots)
cycle.ts(x, \dots)
cycle.default(x, \dots)
frequency(x, \dots)
frequency.default(x, \dots)
deltat(x, \dots)
deltat.default(x, \dots)
}
\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}
\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.}
}
\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}}).
}
\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.
}
\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}
\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}}).}
}
\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=}.
}
\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))

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}
\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)
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}
\name{trace}
\title{Trace All Calls to a Function.}
\usage{
trace(fun)
untrace(fun)
}
\alias{trace}
\alias{untrace}
\arguments{
\item{fun}{any interpreted \R function (not quoted).}
}
\description{
These are both in very primitive form.
If \code{trace} is called the function named is marked and each time it
is entered the call is printed on the console.
To stop tracing a function use \code{untrace}.
}
\seealso{
\code{\link{debug}}.
}
\examples{
trace(names)
data.frame(x=1:2, y=3:4)
untrace(names)
}
\keyword{programming}
\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.
}
\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}
\name{transform}
\alias{transform}
\alias{transform.default}
\alias{transform.data.frame}
\title{Transform an Object, e.g. 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
  dataframes. \code{transform.default} converts its first argument to
  a dataframe 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 dataframe
  \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}
\name{trees}
\title{Girth, Height and Volume for Black Cherry Trees}
\usage{data(trees)}
\alias{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.
}
\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.
}
\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}
\name{try}
\alias{try}
\title{Try an Expression Allowing Error Recovery.}
\usage{
try(expr, first = TRUE)
}
\arguments{
  \item{expr}{an \R expression to try}
  \item{first}{not for user use!}
}
\description{
  \code{try} is a wrapper to run an expression that might fail and allow
  the user's code to handle error-recovery.
}
\details{
  \code{try} is a user-friendly wrapper to \code{\link{restart}}.
  The argument \code{first} is used to record if \code{restart} has
  already been used, and so ensure that \code{restart} is called only
  once.
}
\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 if fails. The normal error handling will print the
  same message unless \code{options("show.error.messages")} is false.
}
\seealso{
  \code{\link{options}} for setting error handlers and suppressing the
  printing of error messages;
  \code{\link{geterrmessage}} for retrieving the last error message.
}
\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)

## 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")
}
options(show.error.messages = FALSE)
## alternative 1
res <- lapply(1:100, function(i) try(doit(x)))
## alternative 2
\dontrun{res <- vector("list", 100)
for(i in 1:100) res[[i]] <- try(doit(x))}
options(show.error.messages = TRUE)
unlist(res[sapply(res, function(x) !inherits(x, "try-error"))])
}
\keyword{programming}
\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.  `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.
}
\author{B. D. Ripley}
\seealso{
  \code{\link{diff}};
  \code{\link{na.omit}}, \code{\link{na.fail}},
  \code{\link[ts]{na.contiguous}}.
}
\keyword{ts}
\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 vector or matrix of the observed time-series values.}
  \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.

  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.
}
\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 \bold{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)

# Ensure working arithmetic for `ts' objects :
stopifnot(z == z)
stopifnot(z-z == 0)

\testonly{
 ts(1:5, start=2, end=4) # truncate
 ts(1:5, start=3, end=17)# repeat
}
## 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}
\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}.
}
\seealso{
    \code{\link{ts}}, \code{\link{time}}, \code{\link{start}}.
}
\keyword{ts}
\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}
\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}
\name{unique}
\alias{unique}
\alias{unique.default}
\alias{unique.data.frame}
\title{Extract Unique Elements}
\description{
  \code{unique} returns a vector or data frame like \code{x} but with duplicate
  elements removed.  If an element is equal to one with a smaller index,
  it is removed.
}
\usage{
unique(x, incomparables = FALSE)
}
\arguments{
  \item{x}{an atomic vector or a data frame.}
  \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.}
}
\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
my.unique <- function(x) x[!duplicated(x)]
for(i in 1:4)
 { x <- rpois(100, pi); stopifnot(unique(x) == my.unique(x)) }

data(iris)
unique(iris)
stopifnot(dim(unique(iris)) == c(149, 5))
}
\keyword{manip}
\keyword{logic}
\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}
\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)
attach(mtcars)
plot(mpg, disp, pch=19, main= "Motor Trend Cars")
text(mpg + xinch(0.12), disp, rownames(mtcars),adj=0, cex = .7, col='blue')
detach(mtcars)
}
\keyword{dplot}
\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.
}
\seealso{
  \code{\link{file.remove}}.
}
%Examples: tempfile has an 'unlink' example
\keyword{file}
\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{
  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.
}
\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}
\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 ``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}
\name{update}
\title{Update and Re-fit a Model Call}
\usage{
update(object, \dots)
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.
}
\author{B.D. Ripley}
\seealso{\code{\link{update.formula}}}

\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}
\name{update.formula}
\alias{update.formula}
\title{Model Updating}
\usage{
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.formula(y ~ x,    ~ . + x2) #> y ~ x + x2
update.formula(y ~ x, log(.) ~ . ) #> log(y) ~ x
}
\keyword{models}
\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)

installed.packages(lib.loc = NULL)
CRAN.packages(CRAN = getOption("CRAN"), method = "auto",
              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 = "auto")
install.packages(pkgs, lib, CRAN = getOption("CRAN"),
                 contriburl = contrib.url(CRAN),
                 method, available = NULL, destdir = NULL)
}
\arguments{ 
  \item{lib.loc}{A character vector describing the location of R
    library trees to search through (and update packages therein).}
  \item{CRAN}{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}{A 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{available}{List of packages available at CRAN as returned by
    \code{CRAN.packages}.}
  \item{lib,instlib}{A character string giving the library directory where to
    install the packages.}
  \item{ask}{If \code{TRUE}, ask before packages are actually downloaded
    and installed.}
}
\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 the 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.
%  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.
}
#ifdef windows
\note{
  \code{wget.exe} is available from
  \url{http://www.stats.ox.ac.uk/pub/Rtools/wget.zip}.
  \code{lynx.exe} is available from
  \url{http://www.fdisk.com/doslynx/lynxport.htm}.
}
#endif
\seealso{
#ifdef unix
  \code{\link{INSTALL}}, \code{\link{REMOVE}},
#endif
  \code{\link{library}}, \code{\link{.packages}},
  \code{\link{read.dcf}}, \code{\link{download.file}}
}
\keyword{utilities}
\name{url.show}
\alias{url.show}
\title{Display a text URL}
\usage{
url.show(url, title = url, file = tempfile(),
         delete.file = TRUE, method, \dots)
}
\arguments{
  \item{url}{The URL to read from.}
  \item{title}{Thitel 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}}.}
}
\description{
  Extension of \code{\link{file.show}} to display text files on a remote 
  server.
}
\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}
\name{uspop}
\alias{uspop}
\title{The Population of the United States}
\usage{data(uspop)}
\description{
  This data set gives the population of the United States (in millions)
  as recorded by the decennial census for the period 1790--1970.
}
\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}
\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{""}.
}
\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}
\name{volcano}
\alias{volcano}
\title{Topographic Information for the Maunga Whau Volcano}
\usage{data(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.
}
\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}
\name{warning}
\alias{warning}
\title{Warning Messages}
\description{
  Generates a warning message that corresponds to its argument(s) and the
  expression or function from which it was called.
}
\usage{
warning(\dots)
}
\arguments{
  \item{\dots}{character vectors (which are pasted together with no
    separator) or \code{NULL}.}
}
\details{
  The result \emph{depends} on the value of
  \code{\link{options}("warn")}.

  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}}.
}
\seealso{
  \code{\link{stop}} for fatal errors,
  \code{\link{warnings}},
  and \code{\link{options}} with argument \code{warn=}.
}
\examples{
\testonly{eigenval <- 10 ^ -rnorm(1,m=6)
if(eigenval < 1.e-7) warning("system near singular")}
}
\keyword{programming}
\keyword{error}
\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}}.}
}
\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}
\name{warpbreaks}
\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}
\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{
\method{weekdays}{POSIXt}(x, abbreviate = FALSE)
\method{months}{POSIXt}(x, abbreviate = FALSE)
\method{quarters}{POSIXt}(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}
\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}
\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{lm.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}

\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.}
\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}
\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.}
\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
\testonly{
  stopifnot(length(which.min(numeric(0))) == 0)
  stopifnot(length(which.max( c(NA,NA) )) == 0)
}
}
\keyword{utilities}
\name{window}
\title{Time Windows}
\usage{
window(x, \dots)
window.default(x, start = NULL, end = NULL,
               frequency = NULL, deltat = NULL, extend = FALSE, \dots)
window.ts(x, start = NULL, end = NULL,
          frequency = NULL, deltat = NULL, extend = FALSE, \dots)
}
\synopsis{
window(x, \dots)
window.default(x, start = NULL, end = NULL,
               frequency = NULL, deltat = NULL, extend = FALSE, \dots)
window.ts(x, \dots)
}
\alias{window}
\alias{window.default}
\alias{window.ts}
\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.
}
\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}
\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{
\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.
}
\seealso{
  \code{\link{evalq}}.
}
\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}
\name{women}
\alias{women}
\title{Average Heights and Weights for American Women}
\usage{data(women)}
\description{
  This data set gives the average heights and weights for American women
  aged 30--39.
}
\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: ``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}
\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.
}
\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}
\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 \code{MASS}
  may be much more efficient if \code{x} is a matrix or can be
  represented in a numeric matrix.
}

\seealso{
  The `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}
\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, LF on Macintosh).  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{readLines}}, \code{\link{cat}}
}

\keyword{file}
\keyword{connection}
\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 = "Rplots.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 (the default) 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 options for \code{xfig()}, such as:}
  \item{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{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.}
  \item{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{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.}
  \item{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}.
}
\keyword{device}
\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 \bold{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 ``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}
\name{xy.coords}
\title{Extracting Plotting Structures}
\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 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{yvar ~ xvar}, \code{xvar} and \code{yvar}
are used as x and y variables;
if the argument is a list containing components \code{x} and
\code{y}, these are used are assumed to define plotting coordinates;
if the argument contains a time series, the x values are
taken to be time and the y values to be the time series;
if the argument is a matrix with two columns, the first
is assumed to contain the x values and the second the
y values; in any other case, the argument is coerced to a vector
and the values plotted against their indices.}
\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.}
}
\description{
\code{xy.coords} is used by many function to obtain
x and y coordinates for plotting.
The use of this common mechanism across all \R functions
produces a measure of consistency.

\code{\link{plot.default}} and \code{\link{lowess}} are examples of functions
which use this mechanism.
}
\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 `label' of \code{x}.}
\item{ylab}{\code{character(1)} or \code{NULL}, the `label' of \code{y}.}
}
\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 ..
}
\keyword{dplot}
\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}
\name{.Alias-deprecated}
\alias{.Alias-deprecated}
\title{Create Alias (Pointer) to R Object}
\description{
  \code{.Alias} creates an \bold{alias} to another (part of) an \R
  object which is more (memory-) efficient than usual assignment.
}
\usage{
.Alias(expr)
}
\arguments{
  \item{expr}{an \R expression; typically a name.}
}
\details{
  Use as \code{new <- .Alias(expr)}, where \code{new} is a new name by
  which \code{expr} can be accessed.
}
\value{
  \emph{an identical copy} of \code{expr}.
}
\section{Warning}{
  This has a \bold{dangerous} semantic, and consequences can be
  unexpected (it can be used to defeat the call-by-value illusion).
  Know what you are doing \emph{before} using \code{.Alias}!
}
\seealso{\code{\link{<-}} for usual assignments.}
\examples{
mop <- options()
mop$browser <- "a browser"   # not set on all platforms
Op <- .Alias(mop)
## A change to mop is reflected in Op and vice versa
## -- ONLY if no new slots are created ...
mop$digits <- "Wow!"
Op$browser <- "another one"
mop$browser; Op$digits
all(names(mop) == names(Op) &
    sapply(seq(mop), function(i) all(Op[[i]] == mop[[i]])))
##> TRUE -- Op and mop ARE the same thing !

mop$newslot <- pi #--->> 'newslot' ==> (shallow) COPY of 'mop'
Op$newslot # R: still the old one, i.e. NULL
all(names(mop) == names(Op))# no longer TRUE

## Feel the power: `call by reference', a function modifying its argument:
tst.Al <- function(x) {
   y <- .Alias(x) ; attributes(y) <- NULL ; invisible()
}
(x0 <- structure(1:5, my.att = "Y"))
tst.Al(x0) # *changes* x0 :
x0
stopifnot(is.null(attributes(x0)))
}
\keyword{programming}
% file C.Rd
% copyright (C) 1998 B. D. Ripley
%
\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.
}
\author{B.D. Ripley}
\seealso{
    \code{\link{contrasts}}, \code{\link{contr.sum}}, etc.
}
\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}
\name{Machine}
\title{Machine Characteristics}
\usage{
Machine()
.Machine
}
\alias{Machine}
\alias{.Machine}
\description{
  \code{Machine()} returns information on numeric characteristics of the
  machine \R is running on, such as the largest double or integer and the
  machine's precision.

  \code{.Machine} is a variable holding this information.
}
\value{
  \code{Machine()} returns a list with components (for simplicity, the
  prefix ``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.}
}
\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{machine}} to determine the computer type which \R is running on.
}
\examples{
str(Machine())
(Meps <- .Machine $ double.eps)

## All the following relations must hold :
stopifnot(
 1 +     Meps != 1,
 1 + .5* Meps == 1,
 log2(.Machine$double.xmax) == .Machine$double.max.exp,
 log2(.Machine$double.xmin) == .Machine$double.min.exp
)
}
% This test fails on HP-UX since pow(2,1024) returns DBL_MAX and sets
% errno = ERANGE.  Most other systems return Inf and set errno
\testonly{
  if (Sys.info()["sysname"] != "HP-UX")
    stopifnot(is.infinite(.Machine$double.base ^ .Machine$double.max.exp))
}
\keyword{sysdata}
\keyword{programming}
\keyword{math}
\name{Methods}
\alias{Methods}
\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}
\title{Internal and Group Methods and Generic Functions}
\usage{
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)

.Method
.Generic
.Group
.Class
}
\description{Many \R-internal functions  are \emph{generic} and  allow
  methods to be written for.  \emph{Group} methods in particular are
  available for the \code{"Math"},  \code{"Ops"}, and
  \code{"Summary"} group.
}
\arguments{
  \item{x, e1, e2}{objects.}
  \item{\dots}{further arguments passed to methods.}
}
 
\section{Group Dispatching}{
    %% --------------- grep -nw DispatchGroup src/*/*[ch]

    There are three \emph{groups} for which methods can be written, namely
    the \code{"Math"}, \code{"Ops"} and \code{"Summary"} groups.

    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{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}
        }
    }
}

\section{Simple Dispatching}{
    % -------------------- 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{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.vector}}, %do_asvector() [coerce.c:948]
    \code{\link{is.na}}, %do_isna()     [coerce.c:1244]
    \code{\link{is.nan}}%do_isnan()    [coerce.c:1332]
}
\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}
\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", "maketitle.pl", file.path(.Library, "base", "TITLE"))
}
\keyword{interface}
\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}
\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.}
}
\description{
    This will extract the file named \code{file} from the zip archive,
    if possible, and write it in a temporary location.
}
\details{
    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 used by \code{tempfile}.
}
\value{
    The name of the original or extracted file.
}
\note{The implementation differs by platform: it might do nothing.}

\section{Warning}{This function is intended for internal use only:
    it may be altered at any time, and may differ between platforms. Do
    NOT use in user code.}

\author{B. D. Ripley}

\keyword{file}
\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}
\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}
\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 \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 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 \code{--configure-args}
  and \code{--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 \code{--configure-vars}), see section
  `Configuration variables' in ``R Installation and Adminstration'' for
  more information.  One can also bypass the configure mechanism using
  the option \code{--no-configure}.
  
  If \code{--no-docs} is given, no help files are built.  Options
  \code{--no-text}, \code{--no-html}, and \code{--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 \code{--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
  \code{--no-save} overrides).  You may need  \code{--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 \code{--save=ARGS}.

  Use \code{R CMD INSTALL --help} for more usage information.
}
\seealso{
  \code{\link{REMOVE}},
  \code{\link{update.packages}} for automatic update of packages using
  the internet;
  the chapter on ``Creating R packages'' in ``Writing \R Extensions''
  (see the \file{doc/manual} subdirectory of the \R source tree).
}
\keyword{utilities}
\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}
\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}
\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}
\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.  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.
}
\note{
  Profiling is not available on all platforms.  By default, it is
  attempted to compile support for profiling.  Configure \R with
  \code{--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.
}
\seealso{
  The chapter on ``Tidying and profiling R code'' in ``Writing \R
  Extensions'' (see the \file{doc/manual} subdirectory of the \R source
  tree).
}
\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
## Post-process the output by
##   R CMD Rprof Rprof.out
## at the shell prompt.
}
}
\keyword{utilities}
\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}
\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}
\name{Gnome}
\alias{GNOME}
\alias{gnome}
\title{GNOME Desktop Graphics Device}
\description{
  \code{gnome} starts a \code{GNOME} compatible device driver.  `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
    \code{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}
\name{gtk}
\alias{gtk}
\alias{GTK}
\title{GTK+ Graphics Device}
\description{
  A variant of the X11 graphics device for use with the GNOME GUI.
}
\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
    \code{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.}
}
\details{
  The GTK device is only available when running under UNIX with
  \code{--gui=gnome}.  Under that circumstance it is the default
  (auto-launched) device, but \code{\link{x11}} can also be used.

  The device has a toolbar in the GNOME style.
}
\author{Lyndon Drake \email{lyndon@stat.auckland.ac.nz}}
\references{
  \url{http://www.gtk.org} for the \code{GTK+} (GIMP Tool Kit) libraries.
}
\seealso{
  \code{\link{x11}},
  \code{\link{Devices}}.
}
\keyword{device}
\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}
\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.jpeg", width = 480, height = 480,
     pointsize = 12, quality = 75, bg = "white", \dots)
png(filename ="Rplot.png", width = 480, height = 480,
    pointsize = 12, bg = "white", \dots)
}
\synopsis{
jpeg(filename = "Rplot.jpeg", width = 480, height = 480, pointsize = 12,
     quality = 75, gamma = 1,
     colortype = getOption("X11colortype"), maxcubesize = 256, bg = "white")
png(filename ="Rplot.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.}
 \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 `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 \code{--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.
}
\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}
\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}.

  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}
\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
    \code{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}
