\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 numeric or complex vectors
  (or objects which can be coerced to them).
}
\arguments{
  \item{x, y}{numeric or complex vectors or objects which can be
    coerced to such, or other objects for which methods have been written.}
}
\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{
  The binary arithmetic operators are generic functions: methods can be
  written for them individually or via the \code{\link{Ops}}) group generic
  function.
  
  If applied to arrays the result will be an array if this is sensible
  (for example it will not if the recycling rule has been invoked).

  Logical vectors will be coerced to numeric vectors, \code{FALSE}
  having value 0 and \code{TRUE} having value one.
  
  \code{1 ^ y} and \code{y ^ 0} are \code{1}, \emph{always}.
  \code{x ^ y} should also give the proper \dQuote{limit} result when
  either argument is infinite (i.e., \code{+- \link{Inf}}).

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

\eof
\name{Comparison}
\alias{<}
\alias{<=}
\alias{==}
\alias{!=}
\alias{>=}
\alias{>}
\alias{Comparison}
\title{Relational Operators}
\description{
  Binary operators which allow the comparison of values in atomic vectors.
}
\usage{
x < y
x > y
x <= y
x >= y
x == y
x != y
}
\arguments{
  \item{x, y}{atomic vectors, or other objects for which methods have
    been written.}
}
\details{
  The binary comparison operators are generic functions: methods can be
  written for them individually or via the \code{\link{Ops}}) group generic
  function.

  Comparison of strings in character vectors is lexicographic within the
  strings using the collating sequence of the locale in use: see
  \code{\link{locales}}.  The collating sequence of locales such as
  \samp{en\_US} is normally different from \samp{C} (which should use
  ASCII) and can be surprising.
}
\value{
  A vector of logicals indicating the result of the element by element
  comparison.  The elements of shorter vectors are recycled as
  necessary.

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

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

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

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

  Note that it is a common mistake to forget putting braces (\code{\{ .. \}})
  around your statements, e.g., after \code{if(..)} or \code{for(....)}.
  In particular, you should not have a newline between \code{\}} and 
  \code{else} to avoid a syntax error in entering a \code{if ... else}
  construct at the keyboard or via \code{source}.
  For that reason, one (somewhat extreme) attitude of defensive programming
  uses braces always, e.g., for \code{if} clauses.

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

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

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

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

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

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

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

  \code{"POSIXct"} objects may also have an attribute \code{"tzone"}, a
  character vector of length one.  If set, it will determine how the
  object is converted to class \code{"POSIXlt"} and in particular how it
  is printed.  This is usually desirable, but if you want to specify an
  object in a particular timezone but to be printed in the current
  timezone you may want to remove the \code{"tzone"} attribute (e.g. by
  \code{c(x)}).

  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{
  \link{Dates} for dates without times.
  
  \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
print(.leap.seconds, tz="PST8PDT")  # and in Seattle's
}
\keyword{utilities}
\keyword{chron}
\eof
\name{Dates}
\alias{Date}
\alias{Dates}
\alias{print.Date}
\alias{summary.Date}
\alias{+.Date}
\alias{-.Date}
\alias{Ops.Date}
\alias{Math.Date}
\alias{Summary.Date}
\alias{[.Date}
\alias{[<-.Date}
\alias{[[.Date}
\alias{as.data.frame.Date}
\alias{c.Date}
\alias{mean.Date}

\title{Date Class}
\description{
  Description of the class \code{"Date"} representing calendar dates. 
}
\details{
  Dates are represented as the number of days since 1970-01-01, with
  negative values for earlier dates.  They are always printed
  following the rules of the current Gregorian calendar, even though
  that calendar was not in use long ago (it was adopted in 1752 in
  Great Britain and its colonies).

  It is intended that the date should be an integer, but this is not
  enforced in the internal representation.  Fractional days will be
  ignored when printing.  It is possible to produce fractional days via
  the \code{mean} method or by adding or subtracting an object of class
  \code{"\link{difftime}"}.
}
\seealso{
  \code{\link{Sys.Date}} for the current date.
  
  \code{\link{format.Date}} for conversion to and from character strings.

  \code{\link[graphics:axis.POSIXct]{plot.Date}} and
  \code{\link[graphics:hist.POSIXt]{hist.Date}} for plotting.

  \code{\link{weekdays}} for convenience extraction functions.

  \code{\link{seq.Date}}, \code{\link{cut.Date}},
  \code{\link{round.Date}} for utility operations.

  \code{\link{DateTimeClasses}} for date-time classes.
}
\examples{
(today <- Sys.Date())
format(today, "\%d \%b \%Y")  # with month as a word
(tenweeks <- seq(today, len=10, by="1 week")) # next ten weeks
weekdays(today)
months(tenweeks)
as.Date(.leap.seconds)
}
\keyword{utilities}
\keyword{chron}
\eof
\name{Defunct}
\title{Defunct Functions}
\alias{Defunct}
\alias{.Defunct}
%------ PLEASE: put \alias{.} here for  EACH !
\alias{Version}
\alias{provide}
\alias{.Provided}
\alias{category}
\alias{dnchisq}
\alias{pnchisq}
\alias{qnchisq}
\alias{rnchisq}
\alias{print.anova.glm}
\alias{print.anova.lm}
\alias{print.tabular}
\alias{print.plot}
\alias{save.plot}
\alias{system.test}
\alias{dotplot}
\alias{stripplot}
\alias{getenv}
\alias{read.table.url}
\alias{scan.url}
\alias{source.url}
\alias{httpclient}
\alias{parse.dcf}
\alias{.Alias}
\alias{reshapeLong}
\alias{reshapeWide}
\alias{piechart}
\alias{print.ordered}
\alias{.Dyn.libs}
\alias{.lib.loc}
\alias{machine}
\alias{Platform}
\alias{Machine}
\alias{restart}
\alias{printNoClass}
\alias{plot.mts}
\alias{print.coefmat}
\alias{codes}
\alias{codes.factor}
\alias{codes.ordered}
\alias{codes<-}
\alias{anovalist.lm}
\alias{lm.fit.null}
\alias{lm.wfit.null}
\alias{glm.fit.null}
\alias{print.atomic}
%
\description{
  The functions or variables listed here are no longer part of \R as
  they are not needed (any more).
}
\usage{
.Defunct()

%--- oldfun(.)
Version()
provide(package)
% Removed in 1.2.0
.Provided
category(\dots)
dnchisq(.)
pnchisq(.)
qnchisq(.)
rnchisq(.)
print.anova.glm(.)
print.anova.lm(.)
print.tabular(.)
print.plot(.)
save.plot(.)
system.test(.)
% </Removed 1.2.0>
% Removed in 1.3.0
dotplot(\dots)
stripplot(\dots)
getenv(\dots)
% </Removed 1.3.0>
% Removed in 1.4.0
read.table.url(url, method,\dots)
scan.url(url, file = tempfile(), method, \dots)
source.url(url, file = tempfile(), method, \dots)
httpclient(url, port=80, error.is.fatal=TRUE, check.MIME.type=TRUE,
           file=tempfile(), drop.ctrl.z=TRUE)
parse.dcf(text = NULL, file = "", fields = NULL, versionfix = FALSE)
% </Removed 1.4.0>
% Removed in 1.5.0
.Alias(expr)
reshapeWide(x, i = reshape.i, j = reshape.j, val = reshape.v,
            jnames = levels(j))
reshapeLong(x,jvars,  ilev = row.names(x),
            jlev = names(x)[jvars], iname = "reshape.i",
            jname = "reshape.j", vname = "reshape.v")
% </Removed 1.5.0>
% Removed in 1.6.0
piechart(x, labels = names(x), edges = 200, radius = 0.8,
         density = NULL, angle = 45, col = NULL, main = NULL, \dots)
print.ordered(.)
.Dyn.libs
.lib.loc
% </Removed 1.6.0>
% Removed in 1.7.0
machine()
Machine()
Platform()
restart()
% </Removed 1.7.0>
% Removed in 1.8.0
printNoClass(x, digits = NULL, quote = TRUE, na.print = NULL,
             print.gap = NULL, right = FALSE, \dots)
% plot.mts can't have such an object, though
plot.mts(x, plot.type = c("multiple", "single"), panel = lines,
         log = "", col = par("col"),  bg = NA, pch = par("pch"),
         cex = par("cex"), lty = par("lty"), lwd = par("lwd"),
         ann = par("ann"),  xlab = "Time", type = "l", main=NULL,
         oma=c(6, 0, 5, 0), \dots)
% </Removed 1.8.0>
% Removed in 1.0.0
print.coefmat(x, digits=max(3, getOption("digits") - 2),
              signif.stars = getOption("show.signif.stars"),
              dig.tst = max(1, min(5, digits - 1)),
              cs.ind = 1:k, tst.ind = k + 1, zap.ind = integer(0),
              P.values = NULL,
              has.Pvalue = nc >= 4 && substr(colnames(x)[nc],1,3) == "Pr(",
              eps.Pvalue = .Machine$double.eps,
              na.print = "", \dots)

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

anovalist.lm(object, \dots, test = NULL)
lm.fit.null(x, y, method = "qr", tol = 1e-07, \dots)
lm.wfit.null(x, y, w, method = "qr", tol = 1e-07, \dots)
glm.fit.null(x, y, weights = rep(1, nobs), start = NULL,
             etastart = NULL, mustart = NULL, offset = rep(0, nobs),
             family = gaussian(), control = glm.control(),
             intercept = FALSE)
print.atomic(x, quote = TRUE, \dots)
% </Removed 1.9.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[graphics]{dotchart}} and \code{\link[graphics]{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[utils]{download.file}}.

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

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

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

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

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

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

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

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

  \code{plot.mts} has been removed, as \code{\link[stats]{plot.ts}} now has the
  same functionality.

  \code{print.coefmat} was an older name for \code{\link[stats]{printCoefmat}}
  with a different default for \code{na.print}.

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

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

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

  \code{print.atomic} differed from \code{print.default} only in its
  argument sequence.  It is not a method for \code{print}.
}
\seealso{\code{\link{Deprecated}}}
\keyword{documentation}
\keyword{utilities}
\keyword{internal}
\eof
\name{Deprecated}
%------ NOTE:  ../R/Deprecated.R   must be synchronized with this!
\title{Deprecated Functions}
\alias{Deprecated}
\alias{.Deprecated}
\alias{La.eigen}
\alias{tetragamma}
\alias{pentagamma}
\alias{package.description}
%------ 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, package=NULL)

% Deprecated in 1.9.0
La.eigen(x, symmetric, only.values = FALSE, method = c("dsyevr", "dsyev"))
tetragamma(x)
pentagamma(x)
package.description(pkg, lib.loc = NULL, fields = NULL)
% </Deprecated 1.9.0>
}
\details{
  \code{.Deprecated("<new name>")} is called from deprecated
  functions. The original help page for these functions is often
  available at \code{help("oldName-deprecated")} (note the quotes).
  Functions in packages other than the base package should be listed in
  \code{help("pkg-deprecated")}.
}
\seealso{
  \code{\link{Defunct}}
}
\keyword{documentation}
\keyword{utilities}
\eof
\name{Extract}
\title{Extract or Replace Parts of an Object}
\alias{Extract}
\alias{Subscript}
\alias{[}
\alias{[[}
\alias{$}
\alias{[<-}
\alias{[[<-}
\alias{$<-}
\alias{.subset}
\alias{.subset2}
\concept{delete}
\description{
  Operators act on vectors, arrays and lists to extract or
  replace subsets.
}
\usage{
x[i]
x[i, j, \dots , drop=TRUE]
x[[i]]
x[[i, j, \dots]]
x$name

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

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

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

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

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

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

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

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

  The functions \code{.subset} and \code{.subset2} are essentially
  equivalent to the \code{[} and \code{[[} operators, except that
  methods dispatch does not take place.  This is to avoid expensive
  unclassing when applying the default method to an object.  They
  should not normally be invoked by end users.

  As from \R 1.9.0 both \code{$} and \code{[[} can be applied to
  environments. Only character arguments are allowed and no partial
  matching is done (this is in contrast to the behavior for lists). The
  semantics of these operations is basically that of \code{get(i, env=x,
    inherits=FALSE)}. If no match is found then \code{NULL} is
  returned. The assignment versions, \code{$<-} and
  \code{[[<-}, can also be used. Again, only character arguments are
  allowed and no partial matching is done. The semantics in this case
  are those of \code{assign(i, value, env=x, inherits=FALSE)}. Such an
  assignment will either create a new binding or change the existing
  binding in \code{x}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{list}}, \code{\link{array}}, \code{\link{matrix}}.

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

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

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

## recursive indexing into lists
z <- list( a=list( b=9, c='hello'), d=1:5)
unlist(z)
z[[c(1, 2)]]
z[[c(1, 2, 1)]]  # both "hello"
z[[c("a", "b")]] <- "new"
unlist(z)

##check $ and [[ for environments
e1 <- new.env()
e1$a <- 10
e1[["a"]]
e1[["b"]] <- 20
e1$b
ls(e1)
}
\keyword{array}
\keyword{list}
\eof
\name{Extract.data.frame}
\alias{[.data.frame}
\alias{[[.data.frame}
\alias{[<-.data.frame}
\alias{[[<-.data.frame}
\alias{$<-.data.frame}
\title{Extract or Replace Parts of a Data Frame}
\description{
  Extract or replace subsets of data frames.
}
\usage{
x[i]
x[i] <- value
x[i, j, drop = TRUE]
x[i, j] <- value

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

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

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

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

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

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

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

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

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

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

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

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

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

  When  \code{[} and \code{[[} are used with two indices, the
  column will be coerced as necessary to accommodate the value.

  Note that when the replacement value is an array (including a matrix)
  it is \emph{not} treated as a series of columns (as
  \code{\link{data.frame}} and \code{\link{as.data.frame}} do) but
  inserted as a single column.
}
\section{Warning}{
  Although the default for \code{drop} is \code{TRUE}, the default
  behaviour  when only one \emph{row} is left is equivalent to
  specifying \code{drop = FALSE}.  To drop from a data frame to a list,
  \code{drop = FALSE} has to specified explicitly.
}
\value{
  For \code{[} a data frame, list or a single column (the latter two
  only when dimensions have been dropped).  If matrix indexing is used for
  extraction a matrix results.

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

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

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

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

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

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

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

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

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

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

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

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

  \code{pmax} and \code{pmin} take several vectors (or matrices) as arguments and
  return a single vector giving the parallel maxima (or minima) of the
  vectors.  The first element of the result is the maximum (minimum) of
  the first elements of all the arguments, the second element of the
  result is the maximum (minimum) of the second elements of all the
  arguments and so on.  Shorter vectors are recycled if necessary.  If
  \code{na.rm} is \code{FALSE}, \code{NA} values in the input vectors
  will produce \code{NA} values in the output.  If \code{na.rm} is
  \code{TRUE}, \code{NA} values are ignored.
  \code{\link{attributes}} (such as \code{\link{names}} or
  \code{\link{dim}}) are transferred from the first argument (if applicable).

  \code{max} and \code{min} are generic functions: methods can be defined
  for them individually or via the \code{\link{Summary}} group generic.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{range}} (\emph{both} min and max) and
  \code{\link{which.min}} (\code{which.max}) for the \emph{arg min},
  i.e., the location where an extreme value occurs.
}
\examples{
require(stats)
min(5:1,pi)
pmin(5:1, pi)
x <- sort(rnorm(100));  cH <- 1.35
pmin(cH, quantile(x)) # no names
pmin(quantile(x), cH) # has names
plot(x, pmin(cH, pmax(-cH, x)), type='b', main= "Huber's function")
}
\keyword{univar}
\keyword{arith}
\eof
\name{Foreign}
\alias{Foreign}
\alias{.C}
\alias{.Fortran}
\alias{.External}
\alias{.Call}
\alias{.External.graphics}
\alias{.Call.graphics}
\title{Foreign Function Interface}
\description{
  Functions to make calls to compiled code that has been loaded into \R.
}
\usage{
                .C(name, \dots, NAOK = FALSE, DUP = TRUE, PACKAGE)
          .Fortran(name, \dots, NAOK = FALSE, DUP = TRUE, PACKAGE)
         .External(name, \dots, PACKAGE)
             .Call(name, \dots, PACKAGE)
.External.graphics(name, \dots, PACKAGE)
    .Call.graphics(name, \dots, PACKAGE)
}
\arguments{
  \item{name}{a character string giving the name of a C function or
    Fortran subroutine.}
  \item{\dots}{arguments to be passed to the foreign function.}
  \item{NAOK}{if \code{TRUE} then any \code{\link{NA}} or
    \code{\link{NaN}} or \code{\link{Inf}} values in the arguments are
    passed on to the foreign function.  If \code{FALSE}, the presence of
    \code{NA} or \code{NaN} or \code{Inf} values is regarded as an error.}
  \item{DUP}{if \code{TRUE} then arguments are \dQuote{duplicated} before
    their address is passed to C or Fortran.}
  \item{PACKAGE}{if supplied, confine the search for the \code{name} to
    the DLL given by this argument (plus the conventional extension,
    \code{.so}, \code{.sl}, \code{.dll}, \dots).  This is intended to
    add safety for packages, which can ensure by using this argument
    that no other package can override their external symbols.  Use
    \code{PACKAGE="base"} for symbols linked in to \R.}
}
\value{
  The functions \code{.C} and \code{.Fortran} return a list similar to
  the \code{\dots} list of arguments passed in, but reflecting any
  changes made by the C or Fortran code.

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

  Chambers, J. M. (1998)
  \emph{Programming with Data. A Guide to the S Language}.
  Springer. (\code{.Call}.)
}
\seealso{\code{\link{dyn.load}}.}
\keyword{programming}
\eof
\name{Formaldehyde}
\docType{data}
\alias{Formaldehyde}
\title{Determination of Formaldehyde}
\description{
  These data are from a chemical experiment to prepare a standard curve
  for the determination of formaldehyde by the addition of chromatropic
  acid and concentrated sulpuric acid and the reading of the resulting
  purple color on a spectophotometer.
}
\usage{data(Formaldehyde)}
\format{
  A data frame with 6 observations on 2 variables.
  \tabular{rlll}{
    [,1] \tab carb\tab numeric \tab Carbohydrate (ml) \cr
    [,2] \tab optden \tab numeric \tab Optical Density
  }
}
\source{
  Bennett, N. A. and N. L. Franklin (1954)
  \emph{Statistical Analysis in Chemistry and the Chemical Industry}.
  New York: Wiley.
}
\references{
  McNeil, D. R. (1977) \emph{Interactive Data Analysis.}
  New York: Wiley.
}
\examples{
require(stats)
data(Formaldehyde)
plot(optden ~ carb, data = Formaldehyde,
     xlab = "Carbohydrate (ml)", ylab = "Optical Density",
     main = "Formaldehyde data", col = 4, las = 1)
abline(fm1 <- lm(optden ~ carb, data = Formaldehyde))
summary(fm1)
opar <- par(mfrow = c(2,2), oma = c(0, 0, 1.1, 0))
plot(fm1)
par(opar)
}
\keyword{datasets}
\eof
\name{HairEyeColor}
\docType{data}
\alias{HairEyeColor}
\title{Hair and Eye Color of Statistics Students}
\description{
  Distribution of hair and eye color and sex in 592 statistics students.
}
\usage{data(HairEyeColor)}
\format{
  A 3-dimensional array resulting from cross-tabulating 592 observations
  on 3 variables.  The variables and their levels are as follows:

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

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

  Friendly, M. (1992),
  Mosaic displays for loglinear models.
  \emph{Proceedings of the Statistical Graphics Section},
  American Statistical Association, pp. 61--68.
  \url{http://www.math.yorku.ca/SCS/Papers/asa92.html}
}
\seealso{
  \code{\link[stats]{chisq.test}},
  \code{\link[stats]{loglin}},
  \code{\link[graphics]{mosaicplot}}
}
\examples{
require(graphics)
data(HairEyeColor)
## Full mosaic
mosaicplot(HairEyeColor)
## Aggregate over sex:
x <- apply(HairEyeColor, c(1, 2), sum)
x
mosaicplot(x, main = "Relation between hair and eye color")
}
\keyword{datasets}
\eof
\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}
}
\details{
  These are generic functions: methods can be defined for them
  individually or via the \code{\link{Math}} group generic.
}
\seealso{
\code{\link{cos}}, \code{\link{sin}}, \code{\link{tan}},
\code{\link{acos}}, \code{\link{asin}}, \code{\link{atan}}.
}
\keyword{math}
\eof
\name{InsectSprays}
\docType{data}
\alias{InsectSprays}
\title{Effectiveness of Insect Sprays}
\description{
  The counts of insects in agricultural experimental units treated with
  different insecticides.
}
\usage{data(InsectSprays)}
\format{
  A data frame with 72 observations on 2 variables.
  \tabular{rlll}{
    [,1]  \tab count  \tab numeric  \tab Insect count\cr
    [,2]  \tab spray  \tab factor   \tab The type of spray
  }
}
\source{
  Beall, G., (1942)
  The Transformation of data from entomological field experiments,
  \emph{Biometrika}, \bold{29}, 243--262.
}
\references{
  McNeil, D. (1977) \emph{Interactive Data Analysis}.
  New York: Wiley.
}
\examples{
require(stats)
data(InsectSprays)
boxplot(count ~ spray, data = InsectSprays,
        xlab = "Type of spray", ylab = "Insect count",
        main = "InsectSprays data", varwidth = TRUE, col = "lightgray")
fm1 <- aov(count ~ spray, data = InsectSprays)
summary(fm1)
opar <- par(mfrow = c(2,2), oma = c(0, 0, 1.1, 0))
plot(fm1)
fm2 <- aov(sqrt(count) ~ spray, data = InsectSprays)
summary(fm2)
plot(fm2)
par(opar)
}
\keyword{datasets}
\eof
\name{Internal}
\title{Call an Internal Function}
\usage{
 .Internal(call)
}
\alias{.Internal}
\description{
\code{.Internal} performs a call to an internal code
which is built in to the \R interpreter.
Only true \R wizards should even consider using this function.
}
\arguments{
  \item{call}{a call expression}
}
\seealso{
\code{\link{.Primitive}}, \code{\link{.C}}, \code{\link{.Fortran}}.
}
\keyword{interface}
\eof
\name{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("splines") # returns invisibly
.Last.value    # shows what library(.) above returned
\dontshow{detach("package:splines")}
}
\keyword{programming}
\eof
\name{LifeCycleSavings}
\docType{data}
\alias{LifeCycleSavings}
\title{Intercountry Life-Cycle Savings Data}
\description{
  Data on the savings ratio 1960--1970.
}
\usage{data(LifeCycleSavings)}
\format{
  A data frame with 50 observations on 5 variables.
  \tabular{rlll}{
    [,1]  \tab sr    \tab numeric  \tab aggregate personal savings \cr
    [,2]  \tab pop15 \tab numeric  \tab \% of population under 15 \cr
    [,3]  \tab pop75 \tab numeric  \tab \% of population over 75 \cr
    [,4]  \tab dpi   \tab numeric  \tab real per-capita disposable
    income \cr
    [,5]  \tab ddpi  \tab numeric  \tab \% growth rate of dpi
  }
}
\source{
  The data were obtained from Belsley, Kuh and Welsch (1980).
  They in turn obtained the data from Sterling (1977).
}
\details{
  Under the life-cycle savings hypothesis as developed by Franco
  Modigliani, the savings ratio (aggregate personal saving divided by
  disposable income) is explained by per-capita disposable income, the
  percentage rate of change in per-capita disposable income, and two
  demographic variables: the percentage of population less than 15
  years old and the percentage of the population over 75 years old.
  The data are averaged over the decade 1960--1970 to remove the
  business cycle or other short-term fluctuations. 
}
\references{
  Sterling, Arnie (1977) Unpublished BS Thesis.
  Massachusetts Institute of Technology.

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

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

  \code{exp} computes the exponential function.

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

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

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

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

  \code{xor} indicates elementwise exclusive OR.

  Numeric and complex vectors will be coerced to logical values, with
  zero being false and all non-zero values being true.
  
  The operators \code{!}, \code{&} and \code{|} are generic functions:
  methods can be written for them individually or via the
  \code{\link{Ops}}) group generic function.

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

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

## construct truth tables :

x <- c(NA, FALSE, TRUE)
names(x) <- as.character(x)
outer(x, x, "&")## AND table
outer(x, x, "|")## OR  table
}
\keyword{logic}
\eof
\name{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 or \code{\link{complex}} vector or array.}
}
\details{
  These are generic functions: methods can be defined for them
  individually or via the \code{\link{Math}} group generic.  For complex
  arguments (and the default method), \code{z},
  \code{abs(z) == \link{Mod}(z)} and \code{sqrt(z) == z^0.5}.
}
\seealso{
  \code{\link{Arithmetic}} for simple, \code{\link{log}} for logarithmic,
  \code{\link{sin}} for trigonometric, and \code{\link{Special}} for
  special mathematical functions.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
require(stats) # for spline
xx <- -9:9
plot(xx, sqrt(abs(xx)),  col = "red")
lines(spline(xx, sqrt(abs(xx)), n=101), col = "pink")
}
\keyword{math}
\eof
\name{Memory}
\alias{Memory}
\alias{mem.limits}
\title{Memory Available for Data Storage}
\description{
  Use command line options to control the memory available for \R.
}
\usage{
#ifdef unix
R --min-vsize=vl --max-vsize=vu --min-nsize=nl --max-nsize=nu
#endif
#ifdef windows
Rgui --min-vsize=vl --max-vsize=vu --min-nsize=nl --max-nsize=nu
Rterm --min-vsize=vl --max-vsize=vu --min-nsize=nl --max-nsize=nu
#endif

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

#ifdef windows
  (On Windows the \option{--max-mem-size} option sets the maximum memory
  allocation: it has a minimum allowed value of 16M.  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 1024Mb.
  See also \code{\link[utils]{memory.limit}}.)
#endif

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

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

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

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

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


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

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

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

\value{
  \code{mem.limits()} returns 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[utils]{object.size}(a)} for the (approximate) size of \R object
  \code{a}.  \code{\link{memory.profile}} for profiling the usage of
  cons cells.
#ifdef windows

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

\note{
  For backwards compatibility, options \option{--nsize} and
  \option{--vsize} are equivalent to \option{--min-nsize} and
  \option{--min-vsize}.
#ifdef windows

  When using the \code{Rgui} console it is simplest to make a shortcut and
  put these command-line flags at the end of the Target field.
#endif
}

\examples{
# Start R with 10MB of heap memory and 500k cons cells, limit to
# 100Mb and 1M cells
\dontrun{
## Unix
R --min-vsize=10M --max-vsize=100M --min-nsize=500k --max-nsize=1M
}
}
\keyword{environment}
\eof
\name{NA}
\alias{NA}
\alias{is.na}
\alias{is.na.data.frame}
\alias{is.na<-}
\alias{is.na<-.default}
\title{Not Available / ``Missing'' Values}
\description{
  \code{NA} is a logical constant of length 1 which contains a missing
  value indicator.  \code{NA} can be freely coerced to any other vector
  type.

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

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

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

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

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

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

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

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

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

\code{is.null} returns \code{TRUE} if its argument
is \code{NULL} and \code{FALSE} otherwise.
}
\details{
  \code{is.null} is generic: you can write methods to handle
  specific classes of objects, see \link{InternalMethods}.
}
\arguments{
  \item{x}{an object to be tested or coerced.}
  \item{\dots}{ignored.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
is.null(list())    # FALSE (on purpose!)
is.null(integer(0))# F
is.null(logical(0))# F
as.null(list(a=1,b='c'))
}
\keyword{attribute}
\keyword{manip}
\keyword{list}
\keyword{sysdata}
\eof
\name{OrchardSprays}
\docType{data}
\alias{OrchardSprays}
\title{Potency of Orchard Sprays}
\description{
  An experiment was conducted to assess the potency of various
  constituents of orchard sprays in repelling honeybees, using a
  Latin square design.
}
\usage{data(OrchardSprays)}
\format{
  A data frame with 64 observations on 4 variables.
  \tabular{rlll}{
    [,1]  \tab rowpos    \tab numeric \tab Row of the design\cr
    [,2]  \tab colpos    \tab numeric \tab Column of the design\cr
    [,3]  \tab treatment \tab factor  \tab Treatment level\cr
    [,4]  \tab decrease  \tab numeric \tab Response
  }
}
\details{
  Individual cells of dry comb were filled with measured amounts of lime
  sulphur emulsion in sucrose solution.  Seven different concentrations
  of lime sulphur ranging from a concentration of 1/100 to 1/1,562,500
  in successive factors of 1/5 were used as well as a solution
  containing no lime sulphur. 
  
  The responses for the different solutions were obtained by releasing
  100 bees into the chamber for two hours, and then measuring the
  decrease in volume of the solutions in the various cells.
  
  An \eqn{8 \times 8}{8 x 8} Latin square design was used and the
  treatments were coded as follows:
  \tabular{rl}{
    A \tab highest level of lime sulphur\cr
    B \tab next highest level of lime sulphur\cr
    . \tab \cr
    . \tab \cr
    . \tab \cr
    G \tab lowest level of lime sulphur\cr
    H \tab no lime sulphur
  }
}
\source{
  Finney, D. J. (1947)
  \emph{Probit Analysis}.
  Cambridge.
}
\references{
  McNeil, D. R. (1977)
  \emph{Interactive Data Analysis}.
  New York: Wiley.
}
\examples{
data(OrchardSprays)
pairs(OrchardSprays, main = "OrchardSprays data")
}
\keyword{datasets}
\eof
\name{Paren}
\alias{Paren}
\alias{(}
\alias{{}
\title{Parentheses and Braces}
\usage{
( \dots )

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

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

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

do <- get("\{")
do(x <- 3, y <- 2*x-3, 6-x-y); x; y
}
\keyword{programming}
\eof
\name{PlantGrowth}
\docType{data}
\alias{PlantGrowth}
\title{Results from an Experiment on Plant Growth}
\description{
  Results from an experiment to compare yields (as measured by dried
  weight of plants) obtained under a control and two different treatment
  conditions.
}
\usage{data(PlantGrowth)}
\format{
  A data frame of 30 cases on 2 variables.

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

  The levels of \code{group} are \sQuote{ctrl}, \sQuote{trt1}, and \sQuote{trt2}.
}
\examples{
## One factor ANOVA example from Dobson's book, cf. Table 7.4:
require(stats)
data(PlantGrowth)
boxplot(weight ~ group, data = PlantGrowth, main = "PlantGrowth data",
        ylab = "Dried weight of plants", col = "lightgray",
        notch = TRUE, varwidth = TRUE)
anova(lm(weight ~ group, data = PlantGrowth))
}
\source{
  Dobson, A. J. (1983)
  \emph{An Introduction to Statistical Modelling}.
  London: Chapman and Hall.
}
\keyword{datasets}
\eof
\name{.Platform}
\title{Platform Specific Variables}
\usage{
.Platform
}
\alias{.Platform}
\description{
  \code{.Platform} is a list with some details of the platform under
  which \R was built.  This provides means to write OS portable \R
  code.
}
\value{
  A list with at least the following components:
  
  \item{OS.type}{
    character, giving the \bold{O}perating \bold{S}ystem
    (family) of the computer.  One of \code{"unix"} or \code{"windows"}.
  }
  \item{file.sep}{
    character, giving the \bold{file} \bold{sep}arator,
    used on your platform, e.g., \code{"/"} on Unix alikes.
  }
  \item{dynlib.ext}{
    character, giving the file name \bold{ext}ension of
    \bold{dyn}amically loadable \bold{lib}raries, e.g., \code{".dll"} on
    Windows.
  }
  \item{GUI}{
    character, giving the type of GUI in use, or
    \code{"unknown"} if no GUI can be assumed.
  }
  \item{endian}{
    character, \code{"big"} or \code{"little"}, giving the
    endianness of the processor in use.
  }
}
\seealso{
  \code{\link{R.version}} and \code{\link{Sys.info}} give more details
  about the OS.  In particular, \code{R.version$platform} is the
  canonical name of the platform under which \R was compiled.
  
  \code{\link{.Machine}} for details of the arithmetic used, and
  \code{\link{system}} for invoking platform-specific system commands.
}
\examples{
## Note: this can be done in a system-independent way by file.info()$isdir
if(.Platform$OS.type == "unix") {
   system.test <- function(...) { system(paste("test", ...)) == 0 }
   dir.exists <- function(dir) sapply(dir, function(d)system.test("-d", d))
   dir.exists(c(R.home(), "/tmp", "~", "/NO"))# > T T T F
}
}
\keyword{file}
\keyword{utilities}
\eof
\name{Primitive}
\alias{.Primitive}
\title{Call a ``Primitive'' Internal Function}
\description{
  \code{.Primitive} returns an entry point to a \dQuote{primitive}
  (internally implemented) function.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  In the underlying C, \code{.Random.seed[-1]} is \code{unsigned};
  therefore in \R \code{.Random.seed[-1]} can be negative, due to
  the representation of an unsigned integer by a signed integer.

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

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

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

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

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

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

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

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

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

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


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

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

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

\seealso{\code{\link[stats]{runif}}, \code{\link[stats]{rnorm}}, \ldots.}
%	this is ./Uniform.Rd
\examples{
## the default random seed is 626 integers, so only print a few
runif(1); .Random.seed[1:6]; runif(1); .Random.seed[1:6]
## If there is no seed, a "random" new one is created:
rm(.Random.seed); runif(1); .Random.seed[1:6]

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

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

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

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

## Reset:
RNGkind(ok[1])
}
\keyword{distribution}
\keyword{sysdata}
\eof
\name{RdUtils}
\alias{Rdconv}
\alias{Rd2txt}
\alias{Rd2dvi}
\alias{Sd2Rd}
\title{Utilities for Processing Rd Files}
\description{
  Utilities for converting files in R documentation (Rd) format to other
  formats or create indices from them, and for converting documentation
  in other formats to Rd format.
}
\usage{

R CMD Rdconv [options] file
#ifdef unix
R CMD Rd2dvi [options] files
#endif
#ifdef windows
R CMD Rd2dvi.sh [options] files
#endif
R CMD Rd2txt [options] file
R CMD Sd2Rd [options] file
}
\arguments{
  \item{file}{the path to a file to be processed.}
  \item{files}{a list of file names specifying the R documentation
    sources to use, by either giving the paths to the files, or the path
    to a directory with the sources of a package.}
  \item{options}{further options to control the processing, or for
    obtaining information about usage and version of the utility.}
}
\details{
  \code{Rdconv} converts Rd format to other formats.  Currently,
  plain text, HTML, LaTeX, S version 3 (Sd), and S version 4 (.sgml)
  formats are supported.  It can also extract the examples for
  run-time testing.

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

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

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

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

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

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

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

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

  \code{zapsmall} determines a \code{digits} argument \code{dr} for
  calling \code{round(x, digits = dr)} such that values \dQuote{close to
    zero} (compared with the maximal absolute one) are \dQuote{zapped},
  i.e., treated as \code{0}.
}
\arguments{
  \item{x}{a numeric vector.}
  \item{digits}{integer indicating the precision to be used.}
}
\details{
  All but \code{zapsmall} are generic functions: methods can be
  defined for them individually or via the \code{\link{Math}} group generic.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole. (except \code{zapsmall}.)

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

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

print   (x2 / 1000, digits=4)
zapsmall(x2 / 1000, digits=4)
zapsmall(exp(1i*0:4*pi/2))
}
\keyword{arith}
\eof
\name{Special}
\alias{Special}
\alias{beta}
\alias{lbeta}
\alias{gamma}
\alias{lgamma}
\alias{psigamma}
\alias{digamma}
\alias{trigamma}
\alias{choose}
\alias{lchoose}
\alias{factorial}
\alias{lfactorial}
\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)
psigamma(x, deriv = 0)
digamma(x)
trigamma(x)
choose(n, k)
lchoose(n, k)
factorial(x)
lfactorial(x)
}
\arguments{
  \item{a, b, x}{numeric vectors.}
  \item{n, k, deriv}{integer vectors.}
}
\details{
  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 formal definition is
  \deqn{B(a, b) = \int_0^1 t^{a-1} (1-t)^{b-1} dt}{integral_0^1 t^(a-1) (1-t)^(b-1) dt}
  (Abramowitz and Stegun (6.2.1), page 258).
  
  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 gamma function is defined by (Abramowitz and Stegun (6.1.1), page 255)
  \deqn{\Gamma(x) = \int_0^\infty t^{a-1} e^{-t} dt}{integral_0^Inf t^(a-1) exp(-t) dt}
  \code{factorial(x)} is \eqn{x!} and identical to
  \code{gamma(x+1)} and \code{lfactorial} is \code{lgamma(x+1)}.

  The functions \code{digamma} and \code{trigamma} return the first and second
  derivatives of the logarithm of the gamma function.
  \code{psigamma(x, deriv)} (\code{deriv >= 0}) is more generally
  computing the \code{deriv}-th derivative of \eqn{\psi(x)}.
  \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.

  All the \code{*gamma*} functions are generic: methods can be
  defined for them individually or via the \code{\link{Math}} group generic.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole. (for \code{gamma} and \code{lgamma}.)

  Abramowitz, M. and Stegun, I. A. (1972)
  \emph{Handbook of Mathematical Functions.} New York: Dover.
  Chapter 6: Gamma and Related Functions.
}
\seealso{
  \code{\link{Arithmetic}} for simple, \code{\link{sqrt}} for
  miscellaneous mathematical functions and \code{\link{Bessel}} for the
  real Bessel functions.

  For the incomplete gamma function see \code{\link[stats]{pgamma}}.
}
\examples{
choose(5, 2)
for (n in 0:10) print(choose(n, k = 0:n))

factorial(100)
lfactorial(10000)

## gamma has 1st order poles at 0, -1, -2, ...
x <- sort(c(seq(-3,4, length=201), outer(0:-3, (-1:1)*1e-6, "+")))
plot(x, gamma(x), ylim=c(-20,20), col="red", type="l", lwd=2,
     main=expression(Gamma(x)))
abline(h=0, v=-3: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
  nm <- paste(ch, "gamma", sep = "")
  if (is.deriv) {
    dy <- diff(y) / dx # finite difference
    der <- which(ch == c("di","tri","tetra","penta")) - 1
    nm2 <- paste("psigamma(*, deriv = ", der,")",sep='')
    nm  <- if(der >= 2) nm2 else paste(nm, nm2, sep = " ==\n")
    y <- psigamma(x, deriv=der)
  } else {
    y <- get(nm)(x)
  }
  plot(x, y, type = "l", main = nm, col = "red")
  abline(h = 0, col = "lightgray")
  if (is.deriv) lines(x[-1], dy, col = "blue", lty = 2)
}

}
\keyword{math}
\eof
\name{Startup}
\alias{Startup}
\alias{Rprofile}
\alias{.Rprofile}
\alias{Rprofile.site}
\alias{Renviron.site}
\alias{.Renviron}
\alias{.First}
\alias{.First.sys}
\title{Initialization at Start of an R Session}
\usage{
.First <- function() { \dots\dots }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

\title{Get Current Date, Time and Timezone}
\description{
  \code{Sys.time} and \code{Sys.Date} returns the system's idea of the
  current date with and without time, and \code{Sys.timezone} returns
  the current time zone.
}
\usage{
Sys.time()
Sys.Date()
Sys.timezone()
}
\details{
  \code{Sys.time} returns an absolute date-time value which can be
  converted in various time zones and may return different days.

  \code{Sys.Date} returns the day in the current timezone.
}
\value{
  \code{Sys.time} returns an object of class \code{"POSIXct"} (see
  \link{DateTimeClasses}).

  \code{Sys.Date} returns an object of class \code{"Date"} (see \link{Date}).

  \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.Date()

Sys.timezone()
}
\keyword{utilities}
\keyword{chron}
\eof
\name{Titanic}
\docType{data}
\alias{Titanic}
\title{Survival of passengers on the Titanic}
\description{
  This data set provides information on the fate of passengers on the
  fatal maiden voyage of the ocean liner \sQuote{Titanic}, summarized according
  to economic status (class), sex, age and survival.
}
\usage{data(Titanic)}
\format{
  A 4-dimensional array resulting from cross-tabulating 2201
  observations on 4 variables.  The variables and their levels are as
  follows:

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

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

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

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

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

  Angles are in radians, not degrees (i.e., a right angle is
  \eqn{\pi/2}).

  All except \code{atan2} are generic functions: methods can be defined
  for them individually or via the \code{\link{Math}} group generic.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\keyword{math}
\eof
\name{UCBAdmissions}
\docType{data}
\alias{UCBAdmissions}
\title{Student Admissions at UC Berkeley}
\description{
  Aggregate data on applicants to graduate school at Berkeley for the
  six largest departments in 1973 classified by admission and sex.
}
\usage{data(UCBAdmissions)}
\format{
  A 3-dimensional array resulting from cross-tabulating 4526
  observations on 3 variables.  The variables and their levels are as
  follows:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  This provides a rather nice 3-way analysis of variance example.
}
\source{
  Moyneau, L.,  Gilliam, S. K., and  Florant, L. C.(1947)
  Differences in Virginia death rates by color, sex, age,
  and rural or urban residence.
  \emph{American Sociological Review}, \bold{12}, 525--535.
}
\references{
  McNeil, D. R. (1977)
  \emph{Interactive Data Analysis}.
  Wiley.
}
\examples{
require(stats)
data(VADeaths)
n <- length(dr <- c(VADeaths))
nam <- names(VADeaths)
d.VAD <- data.frame(
 Drate = dr,
 age = rep(ordered(rownames(VADeaths)),length=n),
 gender= gl(2,5,n, labels= c("M", "F")),
 site =  gl(2,10,  labels= c("rural", "urban")))
coplot(Drate ~ as.numeric(age) | gender * site, data = d.VAD,
       panel = panel.smooth, xlab = "VADeaths data - Given: gender")
summary(aov.VAD <- aov(Drate ~ .^2, data = d.VAD))
opar <- par(mfrow = c(2,2), oma = c(0, 0, 1.1, 0))
plot(aov.VAD)
par(opar)
}
\keyword{datasets}
\eof
\name{R.Version}
\title{Version Information}
\usage{
R.Version()
R.version
R.version.string
}
\alias{R.Version}
\alias{R.version}
\alias{version}
\alias{R.version.string}
\description{
    \code{R.Version()} provides detailed information about the version of
    \R running. \cr
    \code{R.version} is a variable (a \code{\link{list}}) holding this
    information (and \code{version} is a copy of it for
    S compatibility), whereas \code{R.version.string} is a simple
    \code{\link{character}} string, useful for plotting, etc.
}
\value{
 \code{R.Version} returns a list with components
  \item{platform}{the platform for which \R was built.  Under Unix, a
    triplet of the form CPU-VENDOR-OS, as determined by the configure
    script.  E.g, \code{"i586-unknown-linux"}.}
  \item{arch}{the architecture (CPU) \R was built on/for.}
  \item{os}{the underlying operating system}
  \item{system}{CPU and OS.}
  \item{status}{the status of the version (e.g., \code{"Alpha"})}
  \item{status.rev}{the status revision level}
  \item{major}{the major version number}
  \item{minor}{the minor version number}
  \item{year}{the year the version was released}
  \item{month}{the month the version was released}
  \item{day}{the day the version was released}
  \item{language}{always \code{"R"}.}
}
\note{
  Do \emph{not} use \code{R.version$os} to test the platform the
  code is running on: use \code{.Platform$OS.type} instead.  Slightly
  different versions of the OS may report different values of
  \code{R.version$os}, as may different versions of \R.
}
\seealso{
  \code{\link{.Platform}}.
}
\examples{
R.version$os # to check how lucky you are ...
plot(0) # any plot
mtext(R.version.string, side=1,line=4,adj=1)# a useful bottom-right note
}
\keyword{environment}
\keyword{sysdata}
\keyword{programming}
\eof
\name{abbreviate}
\title{Abbreviate Strings}
\usage{
abbreviate(names.arg, minlength = 4, use.classes = TRUE,
           dot = FALSE)
}
\alias{abbreviate}
\arguments{
  \item{names.arg}{a vector of names to be abbreviated.}
  \item{minlength}{the minimum length of the abbreviations.}
  \item{use.classes}{logical (currently ignored by \R).}
  \item{dot}{logical; should a dot (\code{"."}) be appended?}
}
\description{
  Abbreviate strings to at least \code{minlength} characters,
  such that they remain \emph{unique} (if they were).
}
\details{
  The algorithm used is similar to that of S.
  First spaces at the beginning of the word are stripped.
  Then any other spaces are stripped.
  Next lower case vowels are removed followed by lower case consonants.
  Finally if the abbreviation is still longer than \code{minlength}
  upper case letters are stripped.

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

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

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

data(state)
(st.abb <- abbreviate(state.name, 2))
table(nchar(st.abb))# out of 50, 3 need 4 letters
}
\keyword{character}
\eof
\name{agrep}
\alias{agrep}
\alias{fuzzy matching}
\title{Approximate String Matching (Fuzzy Matching)}
\description{
  Searches for approximate matches to \code{pattern} (the first argument)
  within the string \code{x} (the second argument) using the Levenshtein
  edit distance.
}
\usage{
agrep(pattern, x, ignore.case = FALSE, value = FALSE, max.distance = 0.1)
}
\arguments{
  \item{pattern}{a non-empty character string to be matched (\emph{not}
    a regular expression!)}
  \item{x}{character vector where matches are sought.}
  \item{ignore.case}{if \code{FALSE}, the pattern matching is \emph{case
      sensitive} and if \code{TRUE}, case is ignored during matching.}
  \item{value}{if \code{FALSE}, a vector containing the (integer)
    indices of the matches determined is returned and if \code{TRUE}, a
    vector containing the matching elements themselves is returned.}
  \item{max.distance}{Maximum distance allowed for a match.  Expressed
    either as integer, or as a fraction of the pattern length (will be
    replaced by the smallest integer not less than the corresponding
    fraction), or a list with possible components
    \describe{
      \item{\code{all}:}{maximal (overall) distance}
      \item{\code{insertions}:}{maximum number/fraction of insertions}
      \item{\code{deletions}:}{maximum number/fraction of deletions}
      \item{\code{substitutions}:}{maximum number/fraction of
	substitutions}
    }
    If \code{all} is missing, it is set to 10\%, the other components
    default to \code{all}.  The component names can be abbreviated.
  }
}
\details{
  The Levenshtein edit distance is used as measure of approximateness:
  it is the total number of insertions, deletions and substitutions
  required to transform one string into another.

  The function is a simple interface to the \code{apse} library
  developed by Jarkko Hietaniemi (also used in the Perl String::Approx
  module).
}
\value{
  Either a vector giving the indices of the elements that yielded a
  match, of, if \code{value} is \code{TRUE}, the matched elements.
}
\author{David Meyer \email{David.Meyer@ci.tuwien.ac.at} (based on C code
  by Jarkko Hietaniemi); modifications by Kurt Hornik}
}
\seealso{\code{\link{grep}}}
\examples{
agrep("lasy", "1 lazy 2")
agrep("lasy", "1 lazy 2", max = list(sub = 0))
agrep("laysy", c("1 lazy", "1", "1 LAZY"), max = 2)
agrep("laysy", c("1 lazy", "1", "1 LAZY"), max = 2, value = TRUE)
agrep("laysy", c("1 lazy", "1", "1 LAZY"), max = 2, ignore.case = TRUE)
}
\keyword{character}
\eof
\name{airquality}
\docType{data}
\alias{airquality}
\title{New York Air Quality Measurements}
\description{
  Daily air quality measurements in New York, May to September 1973.
}
\usage{data(airquality)}
\format{
  A data frame with 154 observations on 6 variables.

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

  \itemize{
    \item \code{Ozone}: Mean ozone in parts per
    billion from 1300 to 1500 hours at Roosevelt Island
    \item \code{Solar.R}: Solar radiation
    in Langleys in the frequency band 4000--7700 Angstroms from
    0800 to 1200 hours at Central Park
    \item \code{Wind}: Average wind speed in miles
    per hour at 0700 and 1000 hours at LaGuardia Airport
    \item \code{Temp}: Maximum daily
    temperature in degrees Fahrenheit at La Guardia Airport.
  }
}
\source{
  The data were obtained from the New York State Department of
  Conservation (ozone data) and the National Weather Service
  (meteorological data).
}
\references{
  Chambers, J. M., Cleveland, W. S., Kleiner, B. and Tukey, P. A. (1983)
  \emph{Graphical Methods for Data Analysis}.
  Belmont, CA: Wadsworth.
}
\examples{
data(airquality)
pairs(airquality, panel = panel.smooth, main = "airquality data")
}
\keyword{datasets}
\eof
\name{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}.
}
\details{
  This is a generic function: methods can be defined for it
  directly or via the \code{\link{Summary}} group generic.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{any}}, the \dQuote{complement} of \code{all}, and
  \code{\link{stopifnot}(*)} which is an \code{all(*)}
  \dQuote{insurance}.
}
\examples{
range(x <- sort(round(rnorm(10) - 1.2,1)))
if(all(x < 0)) cat("all x values are negative\n")
}
\keyword{logic}
\eof
\name{all.equal}
\title{Test if Two Objects are (Nearly) Equal}
\alias{all.equal}
\alias{all.equal.default}
\alias{all.equal.numeric}
\alias{all.equal.character}
\alias{all.equal.factor}
\alias{all.equal.formula}
\alias{all.equal.list}
\alias{all.equal.language}
\alias{attr.all.equal}
\usage{
all.equal(target, current, \dots)

\method{all.equal}{numeric}(target, current,
          tolerance= .Machine$double.eps ^ 0.5, scale=NULL, \dots)

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

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

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

    For complex arguments, the modulus \code{\link{Mod}} of the difference 
    is used: \code{all.numeric.numeric} is called so arguments
    \code{tolerance} and \code{scale} are available.

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

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

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

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


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

all.vars(expr, functions = FALSE, max.names = 200, unique = TRUE)
}
\arguments{
  \item{expr}{an expression or call from which the names are to be
    extracted.}
  \item{functions}{a logical value indicating whether function names
    should be included in the result.}
  \item{max.names}{the maximum number of names to be returned.}
  \item{unique}{a logical value which indicates whether duplicate names
    should be removed from the value.}
}
\details{
  These functions differ only in the default values for their
  arguments.
}
\value{
  A character vector with the extracted names.
}
\examples{
all.names(expression(sin(x+y)))
all.vars(expression(sin(x+y)))
}
\keyword{programming}
\eof
\name{anscombe}
\docType{data}
\alias{anscombe}
\title{Anscombe's Quartet of ``Identical'' Simple Linear Regressions}
\description{
  Four \eqn{x}-\eqn{y} datasets which have the same traditional
  statistical properties (mean, variance, correlation, regression line,
  etc.), yet are quite different.
}
\usage{data(anscombe)}
\format{
  A data frame with 11 observations on 8 variables.
  \tabular{rl}{
    x1 == x2 == x3 \tab the integers 4:14, specially arranged \cr
    x4             \tab values 8 and 19 \cr
    y1, y2, y3, y4 \tab numbers in (3, 12.5) with mean 7.5 and sdev 2.03}
}
\source{
  Tufte, Edward R. (1989)
  \emph{The Visual Display of Quantitative Information}, 13--14.
  Graphics Press.
}
\references{
  Anscombe, Francis J. (1973)  Graphs in statistical analysis.
  \emph{American Statistician}, \bold{27}, 17--21.
}
\examples{
require(stats)
data(anscombe)
summary(anscombe)

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

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

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

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

  If \code{x} consists of a mix of \code{FALSE} and \code{NA} values,
  the value is \code{NA}.
}
\details{
  This is a generic function: methods can be defined for it
  directly or via the \code{\link{Summary}} group generic.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{all}}, the \dQuote{complement} of \code{any}.
}
\examples{
range(x <- sort(round(rnorm(10) - 1.2,1)))
if(any(x < 0)) cat("x contains negative values\n")
}
\keyword{logic}
\eof
\name{aperm}
\alias{aperm}
\title{Array Transposition}
\description{
  Transpose an array by permuting its dimensions and optionally resizing
  it.
}
\usage{
aperm(a, perm, resize = TRUE)
}
\arguments{
  \item{a}{the array to be transposed.}
  \item{perm}{the subscript permutation vector, which must be a
    permutation of the integers \code{1:n}, where \code{n} is the
    number of dimensions of \code{a}.  The default is to reverse the
    order of the dimensions.}
  \item{resize}{a flag indicating whether the vector should be
    resized as well as having its elements reordered (default \code{TRUE}).}
}
\value{
  A transposed version of array \code{a}, with subscripts permuted as
  indicated by the array \code{perm}.  If \code{resize} is \code{TRUE},
  the array is reshaped as well as having its elements permuted, the
  \code{dimnames} are also permuted;
  if \code{FALSE} then the returned object has the same dimensions as
  \code{a}, and the dimnames are dropped.

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

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

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

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

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

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

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

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

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

approxfun(x, y = NULL,       method="linear",
          yleft, yright, rule = 1, f=0, ties = mean)
}
\arguments{
  \item{x, y}{vectors giving the coordinates of the points to be
    interpolated.  Alternatively a single plotting structure can be
    specified: see \code{\link[graphics]{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 are
    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 are
    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[stats]{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[stats]{spline}} and \code{\link[stats]{splinefun}} for spline
  interpolation.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
x <- 1:10
y <- rnorm(10)
par(mfrow = c(2,1))
plot(x, y, main = "approx(.) and approxfun(.)")
points(approx(x, y), col = 2, pch = "*")
points(approx(x, y, method = "constant"), col = 4, pch = "*")

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

## Show treatment of 'ties' :

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

%%-- MM has nice utility plotting -- do in demo ?
}
\keyword{arith}
\keyword{dplot}
\eof
\name{args}
\alias{args}
\title{Argument List of a Function}
\description{
  Displays the argument names and corresponding default values of a
  function.
}
\usage{
args(name)
}
\arguments{
  \item{name}{an interpreted function.
    If \code{name} is a character string then the function with that
    name is found and used.}
}
\value{
  A function with identical formal argument list but an empty body if
  given an interpreted function; \code{NULL} in case of a variable or
  primitive (non-interpreted) function.
}
\details{
  This function is mainly used interactively.
  For programming, use \code{\link{formals}} instead.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{formals}},
  \code{\link[utils]{help}}.
}
\examples{
args(c)            # -> NULL (c is a 'primitive' function)
args(graphics::plot.default)
}
\keyword{documentation}
\eof
\name{array}
\alias{array}
\alias{as.array}
\alias{is.array}
\title{Multi-way Arrays}
\description{
  Creates or tests for arrays.
}
\usage{
array(data = NA, dim = length(data), dimnames = NULL)
as.array(x)
is.array(x)
}
\arguments{
  \item{data}{a vector (including a list) 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.  If \code{data} has
  length zero, \code{NA} of an appropriate type is used for atomic
  vectors and \code{NULL} for lists.

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

  \code{is.array} returns \code{TRUE} or \code{FALSE} depending on
  whether its argument is an array (i.e., has a \code{dim} attribute)
  or not. It is generic: you can write methods to handle
  specific classes of objects, see \link{InternalMethods}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{aperm}}, \code{\link{matrix}},
  \code{\link{dim}}, \code{\link{dimnames}}.
}
\examples{
dim(as.array(letters))
array(1:3, c(2,4)) # recycle 1:3 "2 2/3 times"
#     [,1] [,2] [,3] [,4]
#[1,]    1    3    2    1
#[2,]    2    1    3    2
}
\keyword{array}
\eof
\name{as.POSIX*}
\alias{as.POSIXct}
\alias{as.POSIXct.default}
\alias{as.POSIXct.POSIXlt}
\alias{as.POSIXct.date}
\alias{as.POSIXct.dates}
\alias{as.POSIXct.Date}
\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"},
  \code{"date"} (from package \pkg{\link[date:as.date]{date}} or
  \pkg{\link[survival:as.date]{survival}}), \code{"chron"} and
  \code{"dates"} (from package \pkg{\link[chron]{chron}}) to these
  classes.  Dates are treated as being at midnight UTC.

  They can also convert character strings of the formats
  \code{"2001-02-03"} and \code{"2001/02/03"} optionally followed by
  white space and a time in the format \code{"14:52"} or
  \code{"14:52:03"}.  (Formats such as \code{"01/02/03"} are ambiguous
  but can be converted via a format specification by
  \code{\link{strptime}}.)

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

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

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

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

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

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

  As from \R 1.9.0 arrays can be converted.  One-dimensional arrays are
  treated like vectors and two-dimensional arrays like matrices.  Arrays
  with more than two dimensions are converted to matrices by
  \sQuote{flattening} all dimensions after the first and creating
  suitable column labels.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

\seealso{
  \code{\link{assign}},
  \code{\link{environment}}.
}
\keyword{data}
\eof
\name{attach}
\title{Attach Set of R Objects to Search Path}
\usage{
attach(what, pos = 2, name = deparse(substitute(what)))
}
\alias{attach}
\arguments{
  \item{what}{\dQuote{database}.  This may currently be a
    \code{data.frame} or \code{list} or a \R data file created with
    \code{\link{save}}.}
  \item{pos}{integer specifying position in \code{\link{search}()} where
    to attach.}
  \item{name}{alternative way to specify the database to be attached.}
}
\description{
  The database is attached to the \R search path.  This means that the
  database is searched by \R when evaluating a variable, so objects in
  the database can be accessed by simply giving their names.}

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

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

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

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

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

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

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

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

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

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

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

x <- sort(rnorm(12))
y <- x^2
is <- interpSpline(x,y)
search() ## now has splines
detach("package:splines")
search()
is2 <- interpSpline(x,y+x)
search() ## and again
detach("package:splines")
}
\keyword{data}
\keyword{programming}

\eof
\name{backsolve}
\alias{backsolve}
\alias{forwardsolve}
\title{Solve an Upper or Lower Triangular System}
\description{
  Solves a system of linear equations where the coefficient matrix is
  upper or lower triangular.
}
\usage{
   backsolve(r, x, k= ncol(r), upper.tri = TRUE, transpose = FALSE)
forwardsolve(l, x, k= ncol(l), upper.tri = FALSE, transpose = FALSE)
}
\arguments{
  % Name 'r' is not really making sense for upper.tri = FALSE
  % Name 'x' is also a  misnomer,  should rather be  'b'. -- is this S ??
  \item{r,l}{an upper (or lower) triangular matrix giving the
    coefficients for the system to be solved.  Values below (above)
    the diagonal are ignored.}
  \item{x}{a matrix whose columns give \dQuote{right-hand sides} for
    the equations.}
  \item{k}{The number of columns of \code{r} and rows of \code{x} to use.}
  \item{upper.tri}{logical; if \code{TRUE} (default), the \emph{upper}
    \emph{tri}angular part of \code{r} is used.  Otherwise, the lower one.}
  \item{transpose}{logical; if \code{TRUE}, solve \eqn{r' * y = x} for
    \eqn{y}, i.e., \code{t(r) \%*\% y == x}.}
}
\value{
  The solution of the triangular system.  The result will be a vector if
  \code{x} is a vector and a matrix if \code{x} is a matrix.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Dongarra, J. J., Bunch,J. R.,  Moler, C. B. and  Stewart, G. W. (1978)
  \emph{LINPACK Users Guide.}  Philadelphia: SIAM Publications.
}
\seealso{
  \code{\link{chol}},
  \code{\link{qr}},
  \code{\link{solve}}.
}
\examples{
## upper triangular matrix 'r':
r <- rbind(c(1,2,3),
           c(0,1,1),
           c(0,0,2))
( y <- backsolve(r, x <- c(8,4,2)) ) # -1 3 1
r \%*\% y # == x = (8,4,2)
backsolve(r, x, transpose = TRUE) # 8 -12 -5
}
\keyword{algebra}
\keyword{array}
\eof
\name{basename}
\alias{basename}
\alias{dirname}
\title{Manipulate File Paths}
\description{
  \code{basename} removes all of the path up to the last path separator
  (if any).

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

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

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

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

# active bindings
f<-local({
    x <- 1
    function(v) {
       if (missing(v))
           cat("get\n")
       else {
           cat("set\n")
           x <<- v
       }
       x
    }
})
makeActiveBinding("fred", f, .GlobalEnv)
bindingIsActive("fred", .GlobalEnv)
fred
fred<-2
fred
}
\keyword{internal}
\author{Luke Tierney}
\eof
\name{body}
\alias{body}
\alias{body<-}
\title{Access to and Manipulation of the Body of a Function}
\description{
  Get or set the body of a function.
}
\usage{
body(fun = sys.function(sys.parent()))
body(fun, envir = parent.frame()) <- value
}
\arguments{
  \item{fun}{a function object, or see Details.}
  \item{envir}{environment in which the function should be defined.}
  \item{value}{an expression or a list of \R expressions.}
}
\value{
  \code{body} returns the body of the function specified.

  The assignment form sets the body of a function to the list on the
  right hand side.
}
\details{
  For the first form, \code{fun} can be a character string
  naming the function to be manipulated, which is searched for from the
  parent environment.
  If it is not specified, the function calling \code{body} is used.
}
\seealso{
  \code{\link{alist}},
  \code{\link{args}},
  \code{\link{function}}.
}
\examples{
body(body)
f <- function(x) x^5
body(f) <- expression(5^x)
## or equivalently  body(f) <- list(quote(5^x))
f(3) # = 125
body(f)
}
\keyword{programming}
\eof
\name{bquote}
\alias{bquote}
\title{Partial substitution in expressions}
\description{
  An analogue of the LISP backquote macro.  \code{bquote} quotes its
  argument except that terms wrapped in \code{.()} are evaluated in the
  specified \code{where} environment.
}
\usage{
bquote(expr, where = parent.frame())
}
\arguments{
  \item{expr}{An expression }
  \item{where}{ An environment }
}

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

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

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

plot(1:10, a*(1:10), main = bquote(a==.(a)))
}
\keyword{programming}
\keyword{data}
\eof
\name{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 sub-interpreter can be
  exited by typing \code{c}.  Execution then resumes at the statement
  following the call to \code{browser}.

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

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

  Chambers, J. M. (1998)
  \emph{Programming with Data. A Guide to the S Language}.
  Springer.
}
\seealso{
  \code{\link{debug}}, and
  \code{\link{traceback}} for the stack on error.
}
\keyword{programming}
\keyword{environment}
\eof
\name{builtins}
\alias{builtins}
\title{Returns the names of all built-in objects}
\description{
  Return the names of all the built-in objects.  These are fetched
  directly from the symbol table of the \R interpreter.
}
\usage{builtins(internal = FALSE)}
\arguments{
  \item{internal}{a logical indicating whether only \dQuote{internal}
    functions (which can be called via \code{\link{.Internal}}) should
    be returned.}
}
\keyword{utilities}
\eof
\name{by}
\alias{by}
\alias{by.default}
\alias{by.data.frame}
\alias{print.by}
\title{Apply a Function to a Data Frame split by Factors}
\description{
  Function \code{by} is an object-oriented wrapper for
  \code{\link{tapply}} applied to data frames.
}
\usage{
by(data, INDICES, FUN, \dots)
}
\arguments{
 \item{data}{an \R object, normally a data frame, possibly a matrix.}
 \item{INDICES}{a factor or a list of factors, each of length \code{nrow(x)}.}
 \item{FUN}{a function to be applied to data frame subsets of \code{x}.}
 \item{\dots}{further arguments to \code{FUN}.}
}
\details{
  A data frame is split by row into data frames
  subsetted by the values of one or more factors, and function
  \code{FUN} is applied to each subset in term.

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

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

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

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

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

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

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

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

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

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

\examples{
capabilities()

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

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

## An example of polynomial regression
plot(cars, xlab = "Speed (mph)", ylab = "Stopping distance (ft)",
    las = 1, xlim = c(0, 25))
d <- seq(0, 25, len = 200)
for(degree in 1:4) {
  fm <- lm(dist ~ poly(speed, degree), data = cars)
  assign(paste("cars", degree, sep="."), fm)
  lines(d, predict(fm, data.frame(speed=d)), col = degree)
}
anova(cars.1, cars.2, cars.3, cars.4)
}
\keyword{datasets}
\eof
\name{cat}
\title{Concatenate and Print}
\usage{
cat(\dots , file = "", sep = " ", fill = FALSE, labels = NULL,
    append = FALSE)
}
\alias{cat}
\description{
  Prints the arguments, coercing them if necessary to character mode first.
}
\arguments{
  \item{\dots}{\R objects which are coerced to character strings,
    concatenated, and printed, with the remaining arguments
    controlling the output.}
  \item{file}{A connection, or a character string naming the file
    to print to.  If
    \code{""} (the default), \code{cat} prints to the standard output
    connection, the console unless redirected by \code{\link{sink}}.
#ifdef unix
    If it is \code{"|cmd"}, the output is piped to the command given
    by \file{cmd}, by opening a pipe connection.
#endif
  }
  \item{sep}{character string to insert between the objects to print.}
  \item{fill}{a logical or numeric controlling how the output is
    broken into successive lines.  If \code{FALSE} (default), only newlines
    created explicitly by \samp{\\n} are printed.  Otherwise, the
    output is broken into lines with print width equal to the option
    \code{width} if \code{fill} is \code{TRUE}, or the value of
    \code{fill} if this is numeric.}
  \item{labels}{character vector of labels for the lines printed.
    Ignored if \code{fill} is \code{FALSE}.}
  \item{append}{logical. Only used if the argument \code{file} is the
    name of file (and not a connection or \code{"|cmd"}).
    If \code{TRUE} output will be appended to
    \code{file}; otherwise, it will overwrite the contents of
    \code{file}.}
}
\details{
  \code{cat} converts its arguments to character strings, concatenates
  them, separating them by the given \code{sep=} string, and then
  prints them.

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

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

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

  In the matrix case, all the vectors/matrices must be atomic or lists
  (e.g. not expressions). 

  Data frames can be \code{cbind}-ed with matrices, in which case
  each matrix forms a single column in the result, unlike calling
  \code{\link{data.frame}}.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  \code{casefold} is a wrapper for \code{tolower} and \code{toupper}
  provided for compatibility with S-PLUS.
}
\seealso{\code{\link{sub}} and \code{\link{gsub}} for other
  substitutions in strings.}
\examples{
x <- "MiXeD cAsE 123"
chartr("iXs", "why", x)
chartr("a-cX", "D-Fw", x)
tolower(x)
toupper(x)
}
\keyword{character}
\eof
\name{chickwts}
\docType{data}
\alias{chickwts}
\title{Chicken Weights by Feed Type}
\description{
  An experiment was conducted to measure and compare the effectiveness
  of various feed supplements on the growth rate of chickens.
}
\usage{data(chickwts)}
\format{
  A data frame with 71 observations on 2 variables.
  \describe{
    \item{weight}{a numeric variable giving the chick weight.}
    \item{feed}{a factor giving the feed type.}
  }
}
\source{
  Anonymous (1948)
  \emph{Biometrika}, \bold{35}, 214.
} 
\details{
  Newly hatched chicks were randomly allocated into six groups, and each
  group was given a different feed supplement.  Their weights in grams
  after six weeks are given along with feed types.
}
\references{
  McNeil, D. R. (1977)
  \emph{Interactive Data Analysis}.
  New York: Wiley.
}
\examples{
require(stats)
data(chickwts)
boxplot(weight ~ feed, data = chickwts, col = "lightgray",
    varwidth = TRUE, notch = TRUE, main = "chickwt data",
    ylab = "Weight at six weeks (gm)")
anova(fm1 <- lm(weight ~ feed, data = chickwts))
opar <- par(mfrow = c(2, 2), oma = c(0, 0, 1.1, 0),
            mar = c(4.1, 4.1, 2.1, 1.1))
plot(fm1)
par(opar)
}
\keyword{datasets}
\eof
\name{chol}
\alias{chol}
\alias{La.chol}
\title{The Choleski Decomposition}
\description{
  Compute the Choleski factorization of a real symmetric
  positive-definite square matrix.
}
\usage{
chol(x, pivot = FALSE,  LINPACK = pivot)
La.chol(x)
}
\arguments{
  \item{x}{a real symmetric, positive-definite matrix}
  \item{pivot}{Should pivoting be used?}
  \item{LINPACK}{logical. Should LINPACK be used (for compatibility with
    \R < 1.7.0)?}
}
\value{
  The upper triangular factor of the Choleski decomposition, i.e., the
  matrix \eqn{R} such that \eqn{R'R = x} (see example).

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  The replacement version of the function sets the class to the value
  provided.  For classes that have a formal definition, directly
  replacing the class this way is strongly deprecated.  The expression
  \code{\link[methods]{as}(object, value)} is the way to coerce an object to a
  particular class.
}
\seealso{
  \code{\link{UseMethod}}, \code{\link{NextMethod}},
  \code{\link{group generic}}.
}
\examples{
x <- 10
inherits(x, "a") #FALSE
class(x) <- c("a", "b")
inherits(x,"a") #TRUE
inherits(x, "a", TRUE) # 1
inherits(x, c("a", "b", "c"), TRUE) # 1 2 0
}
\keyword{methods}
\keyword{classes}
\eof
\name{codes-deprecated}
\alias{codes-deprecated}
\title{Factor Codes}
\description{
  This (generic) function returns a numeric coding of a factor.  It can
  also be used to assign to a factor using the coded form.

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

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

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

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

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

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


\eof
\name{col}
\alias{col}
\title{Column Indexes}
\description{
  Returns a matrix of integers indicating their column number in the
  matrix.
}
\usage{
col(x, as.factor=FALSE)
}
\arguments{
  \item{x}{a matrix.}
  \item{as.factor}{a logical value indicating whether the value should
    be returned as a factor rather than as numeric.}
}
\value{
  An integer matrix with the same dimensions as \code{x} and whose
  \code{ij}-th element is equal to \code{j}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{row}} to get rows.
}
\examples{
# extract an off-diagonal of a matrix
ma <- matrix(1:12, 3, 4)
ma[row(ma) == col(ma) + 1]

# create an identity 5-by-5 matrix
x <- matrix(0, nr = 5, nc = 5)
x[row(x) == col(x)] <- 1
}
\keyword{array}
\eof
\name{colSums}
\alias{colSums}
\alias{rowSums}
\alias{colMeans}
\alias{rowMeans}
\title{Form Row and Column Sums and Means}
\description{
  Form row and column sums and means for numeric arrays.
}
\usage{
colSums (x, na.rm = FALSE, dims = 1)
rowSums (x, na.rm = FALSE, dims = 1)
colMeans(x, na.rm = FALSE, dims = 1)
rowMeans(x, na.rm = FALSE, dims = 1)
}
\arguments{
  \item{x}{an array of two or more dimensions, containing numeric,
    complex, integer or logical values, or a numeric data frame.}
  \item{na.rm}{logical. Should missing values (including \code{NaN})
    be omitted from the calculations?}
  \item{dims}{Which dimensions are regarded as \dQuote{rows} or
    \dQuote{columns} to sum over.  For \code{row*}, the sum or mean is
    over dimensions \code{dims+1, \dots}; for \code{col*} it is over
    dimensions \code{1:dims}.}
}
\details{
  These functions are equivalent to use of \code{\link{apply}} with
  \code{FUN = mean} or \code{FUN = sum} with appropriate margins, but
  are a lot faster.  As they are written for speed, they blur over some
  of the subtleties of \code{NaN} and \code{NA}.  If \code{na.rm =
    FALSE} and either \code{NaN} or \code{NA} appears in a sum, the
  result will be one of \code{NaN} or \code{NA}, but which might be
  platform-dependent.
}
\value{
  A numeric or complex array of suitable size, or a vector if the result is
  one-dimensional.  The \code{dimnames} (or \code{names} for a vector
  result) are taken from the original array.

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

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

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

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

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

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

m2 <- cbind(1,1:4)
colnames(m2, do.NULL = FALSE)
colnames(m2) <- c("x","Y")
rownames(m2) <- rownames(m2, do.NULL = FALSE, prefix = "Obs.")
m2
}
\keyword{array}
\keyword{manip}
\eof
\name{commandArgs}
\alias{commandArgs}
\title{Extract Command Line Arguments}
\description{
  Provides access to a copy of the command line arguments supplied when
  this \R session was invoked.
}
\usage{
commandArgs()
}
\details{
  These arguments are captured before the standard \R command line
  processing takes place.  This means that they are the unmodified
  values.  If it were useful, we could provide support an argument which
  indicated whether we want the unprocessed or processed values.

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

  Contrary to other \code{\link{attributes}}, the \code{comment} is not
  printed (by \code{\link{print}} or \code{\link{print.default}}).
}
\seealso{
  \code{\link{attributes}} and \code{\link{attr}} for \dQuote{normal}
  attributes.
}
\examples{
x <- matrix(1:12, 3,4)
comment(x) <- c("This is my very important data from experiment #0234",
                "Jun 5, 1998")
x
comment(x)
}
\keyword{attribute}
\eof
\name{compareVersion}
\alias{compareVersion}
\title{Compare Two Package Version Numbers}
\description{
  Compare two package version numbers to see which is later.
}
\usage{
compareVersion(a, b)
}
\arguments{
  \item{a, b}{Character strings representing package version numbers.}
}
\value{
  \code{0} if the numbers are equal, \code{-1} if \code{b} is later
  and \code{1} if \code{a} is later (analogous to the C function
  \code{strcmp}).
}
\details{
  \R package version numbers are of the form \code{x.y-z} for integers
  \code{x}, \code{y} and \code{z}, with components after \code{x}
  optionally missing (in which case the version number is older than
  those with the components present). 
}
\seealso{\code{\link{library}}, \code{\link[utils]{packageStatus}}.}
\examples{
compareVersion("1.0", "1.0-1")
compareVersion("7.2-0","7.1-12")
}
\keyword{utilities}
\eof
\name{complex}
\title{Complex Vectors}
\alias{complex}
\alias{as.complex}
\alias{as.complex.default}
\alias{is.complex}
\alias{Re}
\alias{Im}
\alias{Mod}
\alias{Arg}
\alias{Conj}
\description{
  Basic functions which support complex arithmetic in R.
}
\usage{
complex(length.out = 0, real = numeric(), imaginary = numeric(),
        modulus = 1, argument = 0)
as.complex(x, \dots)
is.complex(x)

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

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

  The functions \code{Re}, \code{Im}, \code{Mod}, \code{Arg} and
  \code{Conj} have their usual interpretation as returning the real
  part, imaginary part, modulus, argument and complex conjugate for
  complex values. Modulus and argument are also called the \emph{polar
      coordinates}. If \eqn{z = x + i y} with real \eqn{x} and \eqn{y},
  \code{Mod}\eqn{(z) = \sqrt{x^2 + y^2}}, and for
  \eqn{\phi= Arg(z)}, \eqn{x = \cos(\phi)} and \eqn{y = \sin(\phi)}.
  They are all generic functions: methods can be defined
  for them individually or via the \code{\link{Complex}} group generic.

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

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

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

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

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

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

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

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

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

signalCondition(cond)

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

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

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

withRestarts(expr, \dots)

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

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

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

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

\details{

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

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

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

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

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

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

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

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

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

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

   \code{invokeRestart} transfers control to the point where the
   specified restart was established and calls the restart's handler with the
   arguments, if any, given as additional arguments to
   \code{invokeRestart}.  The restart argument to \code{invokeRestart}
   can be a character string, in which case \code{findRestart} is used
   to find the restart.

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

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

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

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

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

\examples{
tryCatch(1, finally=print("Hello"))
e <- simpleError("test error")
\dontrun{stop(e)}
\dontrun{tryCatch(stop(e), finally=print("Hello"))}
\dontrun{tryCatch(stop("fred"), finally=print("Hello"))}
tryCatch(stop(e), error = function(e) e, finally=print("Hello"))
tryCatch(stop("fred"),  error = function(e) e, finally=print("Hello"))
withCallingHandlers({ warning("A"); 1+2 }, warning = function(w) {})
{ try(invokeRestart("tryRestart")); 1}
\dontrun{{ withRestarts(stop("A"), abort = function() {}); 1}}
withRestarts(invokeRestart("foo", 1, 2), foo = function(x, y) {x + y})
}
\keyword{programming}
\keyword{error}
\eof
\name{conflicts}
\title{Search for Masked Objects on the Search Path}
\usage{
conflicts(where=search(), detail=FALSE)
}
\alias{conflicts}
\arguments{
 \item{where}{A subset of the search path, by default the whole search path.}
 \item{detail}{If \code{TRUE}, give the masked or masking functions for
   all members of the search path.}
}
\description{
    \code{conflicts} reports on objects that exist with the same name in
    two or more places on the \code{\link{search}} path, usually because
    an object in the user's workspace or a package is masking a system
    object of the same name.  This helps discover unintentional masking.
}
\value{
    If \code{detail=FALSE}, a character vector of masked objects.
    If \code{detail=TRUE}, a list of character vectors giving the masked or
    masking objects in that member of the search path.  Empty vectors are
    omitted.
}
\examples{
lm <- 1:3
conflicts(, TRUE)
## gives something like
# $.GlobalEnv
# [1] "lm"
#
# $package:base
# [1] "lm"

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

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

close(con, \dots)
\method{close}{connection}(con, type = "rw", \dots)

flush(con)

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

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

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

  All platforms support \code{file}, \code{gzfile}, \code{bzfile},
  \code{unz} 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[utils]{download.file}}.

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

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

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

  \code{close} closes and destroys a connection.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

\dontrun{## Unix examples of use of pipes

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

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

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

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

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

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

# R process 2
con2 <- socketConnection(Sys.info()["nodename"], port = 6011)
# as non-blocking, may need to loop for input
readLines(con2)
while(isIncomplete(con2)) {Sys.sleep(1); readLines(con2)}
close(con2)}
}
\keyword{file}
\keyword{connection}
\eof
\name{contributors}
\alias{contributors}
\title{R Project Contributors}
\description{
  The \R Who-is-who, describing who made significant contributions to
  the development of \R.
}
\usage{
contributors()
}
\keyword{misc}
\eof
\name{getNumCConverters}
\alias{getNumCConverters}
\alias{getCConverterDescriptions}
\alias{getCConverterStatus}
\alias{setCConverterStatus}
\alias{removeCConverter}

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

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

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

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

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

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

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

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

\examples{
 getNumCConverters()
 getCConverterDescriptions()
 getCConverterStatus()
\dontrun{
  old <- setCConverterStatus(1,FALSE)

  setCConverterStatus(1,old)
}
\dontrun{
  removeCConverter(1)
  removeCConverter(getCConverterDescriptions()[1])
}
}
\keyword{interface}
\keyword{programming}
\eof
\name{convolve}
\alias{convolve}
\title{Fast Convolution}
\description{
  Use the Fast Fourier Transform to compute the several kinds of
  convolutions of two sequences.
}
\usage{
convolve(x, y, conj = TRUE, type = c("circular", "open", "filter"))
}
\arguments{
  \item{x,y}{numeric sequences \emph{of the same length} to be
    convolved.}
  \item{conj}{logical; if \code{TRUE}, take the complex \emph{conjugate}
    before back-transforming (default, and used for usual convolution).}
  \item{type}{character; one of \code{"circular"}, \code{"open"},
    \code{"filter"} (beginning of word is ok).  For \code{circular}, the
    two sequences are treated as \emph{circular}, i.e., periodic.

    For \code{open} and \code{filter}, the sequences are padded with
    \code{0}s (from left and right) first; \code{"filter"} returns the
    middle sub-vector of \code{"open"}, namely, the result of running a
    weighted mean of \code{x} with weights \code{y}.}
}
\details{
  The Fast Fourier Transform, \code{\link{fft}}, is used for efficiency.

  The input sequences \code{x} and  \code{y} must have the same length if
  \code{circular} is true.

  Note that the usual definition of convolution of two sequences
  \code{x} and \code{y} is given by \code{convolve(x, rev(y), type = "o")}.
}
\value{
  If \code{r <- convolve(x,y, type = "open")}
  and \code{n <- length(x)}, \code{m <- length(y)}, then
  \deqn{r_k = \sum_{i} x_{k-m+i} y_{i}}{r[k] = sum(i; x[k-m+i] * y[i])}
  where the sum is over all valid indices \eqn{i}, for \eqn{k = 1,\dots, n+m-1}

  If \code{type == "circular"}, \eqn{n = m} is required, and the above is
  true for \eqn{i , k = 1,\dots,n} when
  \eqn{x_{j} := x_{n+j}}{x[j] := x[n+j]} for \eqn{j < 1}.
}
\references{
  Brillinger, D. R. (1981)
  \emph{Time Series: Data Analysis and Theory}, Second Edition.
  San Francisco: Holden-Day.
}
\seealso{\code{\link{fft}}, \code{\link{nextn}}, and particularly
  \code{\link[stats]{filter}} (from the \pkg{stats} package) which may be
  more appropriate.
}
\examples{
x <- c(0,0,0,100,0,0,0)
y <- c(0,0,1, 2 ,1,0,0)/4
zapsmall(convolve(x,y))         #  *NOT* what you first thought.
zapsmall(convolve(x, y[3:5], type="f")) # rather
x <- rnorm(50)
y <- rnorm(50)
# Circular convolution *has* this symmetry:
all.equal(convolve(x,y, conj = FALSE), rev(convolve(rev(y),x)))

n <- length(x <- -20:24)
y <- (x-10)^2/1000 + rnorm(x)/8

Han <- function(y) # Hanning
       convolve(y, c(1,2,1)/4, type = "filter")

plot(x,y, main="Using  convolve(.) for Hanning filters")
lines(x[-c(1  , n)      ], Han(y), col="red")
lines(x[-c(1:2, (n-1):n)], Han(Han(y)), lwd=2, col="dark blue")
}
\keyword{math}
\keyword{dplot}
\eof
\name{copyright}
\title{Copyrights of Files Used to Build R}
\alias{copyright}
\alias{copyrights}
\description{
  \R is released under the \sQuote{GNU Public License}: see
  \code{\link{license}} for details.  The license describes your right
  to use \R.  Copyright is concerned with ownership of intellectual
  rights, and some of the software used has conditions that the
  copyright must be explicitly stated: see the Details section.  We
  are grateful to these people and other contributors (see
  \code{\link{contributors}}) for the ability to use their work.
}
\details{
  The file \file{\$R\_HOME/COPYRIGHTS} lists the copyrights in full
  detail.
}
\keyword{misc}
\eof
\name{count.fields}
\title{Count the Number of Fields per Line}
\usage{
count.fields(file, sep = "", quote = "\"'", skip = 0,
             blank.lines.skip = TRUE, comment.char = "#")
}
\alias{count.fields}
\arguments{
  \item{file}{a character string naming an ASCII data file, or a
    \code{\link{connection}}, which will be opened if necessary,
    and if so closed at the end of the function call.}

  \item{sep}{the field separator character.  Values on each line of the
    file are separated by this character.  By default, arbitrary amounts
    of whitespace can separate fields.}

  \item{quote}{the set of quoting characters}

  \item{skip}{the number of lines of the data file to skip before
    beginning to read data.}

  \item{blank.lines.skip}{logical: if \code{TRUE} blank lines in the
    input are ignored.}

  \item{comment.char}{character: a character vector of length one
    containing a single character or an empty string.}
}
\description{
  \code{count.fields} counts the number of fields, as separated by
  \code{sep}, in each of the lines of \code{file} read.
}
\details{
  This used to be used by \code{\link{read.table}} and can still be
  useful in discovering problems in reading a file by that function.

  For the handling of comments, see \code{\link{scan}}.
}
\value{
  A vector with the numbers of fields found.
}
\seealso{
  \code{\link{read.table}}
}
\examples{
cat("NAME", "1:John", "2:Paul", file = "foo", sep = "\n")
count.fields("foo", sep = ":")
unlink("foo")
}
\keyword{file}
\eof
\name{crossprod}
\alias{crossprod}
\title{Matrix Crossproduct}
\description{
  Given matrices \code{x} and \code{y} as arguments,
  \code{crossprod} returns their matrix cross-product.
  This is formally equivalent to, but faster than, the
  call \code{t(x) \%*\% y}.
}
\usage{
crossprod(x, y = NULL)
}
\arguments{
  \item{x, y}{matrices: \code{y = NULL} is taken to be the
    same matrix as \code{x}.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
\code{\link{\%*\%}} and outer product \code{\link{\%o\%}}.
}
\examples{
(z <- crossprod(1:4))    # = sum(1 + 2^2 + 3^2 + 4^2)
drop(z)                  # scalar
}
\keyword{algebra}
\keyword{array}
\eof
\name{cumsum}
\alias{cumsum}
\alias{cumprod}
\alias{cummin}
\alias{cummax}
\title{Cumulative Sums, Products, and Extremes}
\description{
  Returns a vector whose elements are the cumulative sums, products,
  minima or maxima of the elements of the argument.
}
\usage{
cumsum(x)
cumprod(x)
cummax(x)
cummin(x)
}
\arguments{
  \item{x}{a numeric object.}
}
\details{
  An \code{NA} value in \code{x} causes the corresponding and following
  elements of the return value to be \code{NA}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole. (\code{cumsum} only.)
}
\examples{
cumsum(1:10)
cumprod(1:10)
cummin(c(3:1, 2:0, 4:2))
cummax(c(3:1, 2:0, 4:2))
}
\keyword{arith}
\eof
\name{cut.POSIXt}
\alias{cut.POSIXt}
\alias{cut.Date}
\title{Convert a Date or Date-Time Object to a Factor}
\description{
  Method for \code{\link{cut}} applied to date-time objects.
}
\usage{
\method{cut}{POSIXt}(x, breaks, labels = NULL, start.on.monday = TRUE,
    right = FALSE, \dots)

\method{cut}{Date}(x, breaks, labels = NULL, start.on.monday = TRUE,
    right = FALSE, \dots)
}
\arguments{
  \item{x}{an object inheriting from class \code{"POSIXt"} or \code{"Date"}.}
  \item{breaks}{
    a vector of cut points \emph{or} number giving the number of
    intervals which \code{x} is to be cut into \emph{or} an
    interval specification, one of \code{"sec"}, \code{"min"},
    \code{"hour"}, \code{"day"}, \code{"DSTday"}, \code{"week"},
    \code{"month"} or \code{"year"}, optionally preceded by an integer
    and a space, or followed by \code{"s"}.  For \code{"Date"} objects
    only \code{"day"}, \code{"week"}, \code{"month"} and \code{"year"}
    are allowed.
  }
  \item{labels}{
    labels for the levels of the resulting category.  By default,
    labels are constructed from the left-hand end of the intervals
    (which are include for the default value of \code{right}).  If
    \code{labels = FALSE}, simple integer codes are returned instead
    of a factor.
  }
  \item{start.on.monday}{logical. If \code{breaks = "weeks"}, should the
    week start on Mondays or Sundays?}
  \item{right, \dots}{arguments to be passed to or from other methods.}
}
\value{
  A factor is returned, unless \code{labels = FALSE} which returns
  the integer level codes.
}
\seealso{
  \code{\link{seq.POSIXt}}, \code{\link{seq.Date}}, \code{\link{cut}}
}
\examples{
## random dates in a 10-week period
cut(ISOdate(2001, 1, 1) + 70*86400*runif(100), "weeks")
cut(as.Date("2001/1/1") + 70*runif(100), "weeks")
}
\keyword{manip}
\keyword{chron}
\eof
\name{cut}
\title{Convert Numeric to Factor}
\usage{
cut(x, \dots)

\method{cut}{default}(x, breaks, labels = NULL,
    include.lowest = FALSE, right = TRUE, dig.lab = 3, \dots)
}
\alias{cut}
\alias{cut.default}
\arguments{
  \item{x}{a numeric vector which is to be converted to a factor by cutting.}
  \item{breaks}{either a vector of cut points or number
    giving the number of intervals which \code{x} is to be cut into.}
  \item{labels}{labels for the levels of the resulting category.  By default,
    labels are constructed using \code{"(a,b]"} interval notation. If
    \code{labels = FALSE}, simple integer codes are returned instead of
    a factor.}.
  \item{include.lowest}{logical, indicating if an \sQuote{x[i]} equal to
    the lowest (or highest, for \code{right = FALSE}) \sQuote{breaks}
    value should be included.}
  \item{right}{logical, indicating if the intervals should be closed on
    the right (and open on the left) or vice versa.}
  \item{dig.lab}{integer which is used when labels are not given. It
    determines the number of digits used in formatting the break numbers.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\description{
  \code{cut} divides the range of \code{x} into intervals
  and codes the values in \code{x} according to which
  interval they fall.
  The leftmost interval corresponds to level one,
  the next leftmost to level two and so on.
}
\value{
  A \code{\link{factor}} is returned, unless \code{labels = FALSE} which
  results in the mere integer level codes.
}
\details{
  If a \code{labels} parameter is specified, its values are used
  to name the factor levels. If none is specified, the factor
  level labels are constructed as \code{"(b1, b2]"}, \code{"(b2, b3]"}
  etc. for \code{right=TRUE} and as \code{"[b1, b2)"}, \ldots if
  \code{right=FALSE}.
  In this case, \code{dig.lab} indicates how many digits should be used in
  formatting the numbers \code{b1}, \code{b2}, \ldots.
}
\note{
  Instead of \code{table(cut(x, br))}, \code{hist(x, br, plot = FALSE)} is
  more efficient and less memory hungry.  Instead of \code{cut(*,
    labels = FALSE)}, \code{\link{findInterval}()} is more efficient.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{split}} for splitting a variable according to a group factor;
  \code{\link{factor}}, \code{\link{tabulate}}, \code{\link{table}},
  \code{\link{findInterval}()}.
}
\examples{
Z <- rnorm(10000)
table(cut(Z, br = -6:6))
sum(table(cut(Z, br = -6:6, labels=FALSE)))
sum(   hist  (Z, br = -6:6, plot=FALSE)$counts)

cut(rep(1,5),4)#-- dummy
tx0 <- c(9, 4, 6, 5, 3, 10, 5, 3, 5)
x <- rep(0:8, tx0)
stopifnot(table(x) == tx0)

table( cut(x, b = 8))
table( cut(x, br = 3*(-2:5)))
table( cut(x, br = 3*(-2:5), right = FALSE))

##--- some values OUTSIDE the breaks :
table(cx  <- cut(x, br = 2*(0:4)))
table(cxl <- cut(x, br = 2*(0:4), right = FALSE))
which(is.na(cx));  x[is.na(cx)]  #-- the first 9  values  0
which(is.na(cxl)); x[is.na(cxl)] #-- the last  5  values  8


## Label construction:
y <- rnorm(100)
table(cut(y, breaks = pi/3*(-3:3)))
table(cut(y, breaks = pi/3*(-3:3), dig.lab=4))

table(cut(y, breaks =  1*(-3:3), dig.lab=4))# extra digits don't "harm" here
table(cut(y, breaks =  1*(-3:3), right = FALSE))#- the same, since no exact INT!
}
\keyword{category}
\eof
\name{data}
\alias{data}
\alias{print.packageIQR}
\title{Data Sets}
\description{
  Loads specified data sets, or list the available data sets.
}
\usage{
data(\dots, list = character(0), package = .packages(),
     lib.loc = NULL, verbose = getOption("verbose"),
     envir = .GlobalEnv)
}
\arguments{
  \item{\dots}{a sequence of names or literal character strings.}
  \item{list}{a character vector.}
  \item{package}{a character vector giving the packages to look
    in for data sets.  By default, all packages in the search path are
    used, then the \file{data} subdirectory (if present) of the current
    working directory.}
  \item{lib.loc}{a character vector of directory names of \R libraries,
    or \code{NULL}.  The default value of \code{NULL} corresponds to all
    libraries currently known.  If the default is used, the loaded
    packages are searched before the libraries.}
  \item{verbose}{a logical.  If \code{TRUE}, additional diagnostics are
    printed.}
  \item{envir}{the \link{environment} where the data should be loaded.}
}
\value{
  a character vector of all data sets specified, or information about
  all available data sets in an object of class \code{"packageIQR"} if
  none were specified.
}
\details{
  Currently, four formats of data files are supported:

  \enumerate{
    \item files ending \file{.R} or \file{.r} are
    \code{\link{source}()}d in, with the \R working directory changed
    temporarily to the directory containing the respective file.

    \item files ending \file{.RData} or \file{.rda} are
    \code{\link{load}()}ed.

    \item files ending \file{.tab}, \file{.txt} or \file{.TXT} are read
    using \code{\link{read.table}(\dots, header = TRUE)}, and hence
    result in a data frame.

    \item files ending \file{.csv} or \file{.CSV} are read using
    \code{\link{read.table}(\dots, header = TRUE, sep = ";")},
    and also result in a data frame.
  }
  If more than one matching file name is found, the first on this list
  is used.
  
  The data sets to be loaded can be specified as a sequence of names or
  character strings, or as the character vector \code{list}, or as both.

  For each given data set, the first two types (\file{.R} or \file{.r},
  and \file{.RData} or \file{.rda} files) can create several variables
  in the load environment, which might all be named differently from the
  data set.  The second two (\file{.tab}, \file{.txt}, or \file{.TXT},
  and \file{.csv} or \file{.CSV} files) will always result in the
  creation of a single variable with the same name as the data set. 

  If no data sets are specified, \code{data} lists the available data
  sets.  It looks for a new-style data index in the \file{Meta} or, if
  this is not found, an old-style \file{00Index} file in the \file{data}
  directory of each specified package, and uses these files to prepare a
  listing.  If there is a \file{data} area but no index, available data
  files for loading are computed and included in the listing, and a
  warning is given: such packages are incomplete.  The information about
  available data sets is returned in an object of class
  \code{"packageIQR"}.  The structure of this class is experimental.  In
  earlier versions of R, an empty character vector was returned along
  with listing available data sets.

  If \code{lib.loc} is not specified, the data sets are searched for
  amongst those packages already loaded, followed by the \file{data}
  directory (if any) of the current working directory and then packages
  in the specified libraries.  If \code{lib.loc} \emph{is} specified,
  packages are searched for in the specified libraries, even if they are
  already loaded from another library.

  To just look in the \file{data} directory of the current working
  directory, set \code{package = NULL}.
}
\note{
  The data files can be many small files.  On some file systems it is
  desirable to save space, and the files in the \file{data} directory of
  an installed package can be zipped up as a zip archive
  \file{Rdata.zip}.  You will need to provide a single-column file
  \file{filelist} of file names in that directory.

  One can take advantage of the search order and the fact that a
  \file{.R} file will change directory.  If raw data are stored in
  \file{mydata.txt} then one can set up \file{mydata.R} to read
  \file{mydata.txt} and pre-process it, e.g., using \code{transform}.
  For instance one can convert numeric vectors to factors with the
  appropriate labels.  Thus, the \file{.R} file can effectively contain
  a metadata specification for the plaintext formats.
}
\seealso{
  \code{\link[utils]{help}} for obtaining documentation on data sets,
  \code{\link{save}} for \emph{creating} the second (\file{.rda}) kind
  of data, typically the most efficient one.
}
\examples{
require(utils)
data()                      # list all available data sets
data(package = "base")      # list the data sets in the base package
data(USArrests, "VADeaths") # load the data sets 'USArrests' and 'VADeaths'
help(USArrests)             # give information on data set 'USArrests'
}
\keyword{documentation}
\keyword{datasets}
\eof
\name{data.class}
\alias{data.class}
\title{Object Classes}
\description{
  Determine the class of an arbitrary \R object.
}
\usage{
data.class(x)
}
\arguments{
  \item{x}{an \R object.}
}
\value{
  character string giving the \dQuote{class} of \code{x}.

  The \dQuote{class} is the (first element) of the
  \code{\link[base]{class}} attribute if this is non-\code{NULL}, or
  inferred from the object's \code{dim} attribute if this is
  non-\code{NULL}, or \code{mode(x)}.

  Simply speaking, \code{data.class(x)} returns what is typically useful
  for method dispatching.  (Or, what the basic creator functions already
  and maybe eventually all will attach as a class attribute.)
}
\note{
  For compatibility reasons, there is one exception to the rule above:
  When \code{x} is \code{\link{integer}}, the result of
  \code{data.class(x)} is \code{"numeric"} even when \code{x} is classed.
}
\seealso{
  \code{\link[base]{class}}
}
\examples{
x <- LETTERS
data.class(factor(x))                 # has a class attribute
data.class(matrix(x, nc = 13))        # has a dim attribute
data.class(list(x))                   # the same as mode(x)
data.class(x)                         # the same as mode(x)

stopifnot(data.class(1:2) == "numeric")# compatibility "rule"
}
\keyword{classes}
\keyword{methods}
\eof
\name{data.frame}
\title{Data Frames}
\alias{data.frame}
\description{
  This function creates data frames, tightly coupled
  collections of variables which share many of the properties of
  matrices and of lists, used as the fundamental data structure by most
  of \R's modeling software.
}
\usage{
data.frame(\dots, row.names = NULL, check.rows = FALSE, check.names = TRUE)
}
\arguments{
  \item{\dots}{these arguments are of either the form \code{value} or
    \code{tag=value}.  Component names are created based on the tag (if
    present) or the deparsed argument itself.}
  \item{row.names}{\code{NULL} or an integer or character string specifying
    a column to be used as row names, or a character vector giving the row
    names for the data frame.}
  \item{check.rows}{if \code{TRUE} then the rows are checked for
    consistency of length and names.}
  \item{check.names}{logical.  If \code{TRUE} then the names of the
    variables in the data frame are checked to ensure that they are
    syntactically valid variable names.  If necessary they are adjusted
    (by \code{\link{make.names}}) so that they are.}
}
\value{
  A data frame, a matrix-like structure whose columns may be of
  differing types (numeric, logical, factor and character and so on).
}
\details{
  A data frame is a list of variables of the same length with unique row
  names, given class \code{"data.frame"}.

  \code{data.frame} converts each of its arguments to a data frame by
  calling \code{\link{as.data.frame}(optional=TRUE)}.  As that is a
  generic function, methods can be written to change the behaviour of
  arguments according to their classes: \R comes with many such methods.
  Character variables passed to \code{data.frame} are converted to
  factor columns unless protected by \code{\link{I}}.  If a list or data
  frame or matrix is passed to \code{data.frame} it is as if each
  component or column had been passed as a separate argument.

  Objects passed to \code{data.frame} should have the same number of
  rows, but atomic vectors, factors and character vectors protected by
  \code{\link{I}} will be recycled a whole number of times if necessary.

  If row names are not supplied in the call to \code{data.frame}, the
  row names are taken from the first component that has suitable names,
  for example a named vector or a matrix with rownames or a data frame.
  (If that component is subsequently recycled, the names are discarded
  with a warning.)  If \code{row.names} was supplied as \code{NULL} or no
  suitable component was found the row names are the integer sequence
  starting at one.

  If row names are supplied of length one and the data frame has a
  single row, the \code{row.names} is taken to specify the row names and
  not a column (by name or number).
}
\note{
  In versions of \R prior to 1.4.0 logical columns were converted to
  factors (as in S3 but not S4).
}
\references{
  Chambers, J. M. (1992)
  \emph{Data for models.}
  Chapter 3 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{I}},
  \code{\link[graphics]{plot.data.frame}},
  \code{\link{print.data.frame}},
  \code{\link{row.names}},
  \code{\link{[.data.frame}} for subsetting methods,
  \code{\link{Math.data.frame}} etc, about
  \emph{Group} methods for \code{data.frame}s;
  \code{\link{read.table}},
  \code{\link{make.names}}.
}
\examples{
L3 <- LETTERS[1:3]
(d <- data.frame(cbind(x=1, y=1:10), fac=sample(L3, 10, repl=TRUE)))

## The same with automatic column names:
data.frame(cbind(  1,   1:10),     sample(L3, 10, repl=TRUE))

is.data.frame(d)

## do not convert to factor, using I() :
(dd <- cbind(d, char = I(letters[1:10])))
rbind(class=sapply(dd, class), mode=sapply(dd, mode))

stopifnot(1:10 == row.names(d))# {coercion}

(d0  <- d[, FALSE]) # NULL data frame with 10 rows
(d.0 <- d[FALSE, ]) # <0 rows> data frame  (3 cols)
(d00 <- d0[FALSE,])  # NULL data frame with 0 rows
}
\keyword{classes}
\keyword{methods}
\eof
\name{data.matrix}
\alias{data.matrix}
\title{Data Frame to Numeric Matrix}
\description{
  Return the matrix obtained by converting all the variables in a data
  frame to numeric mode and then binding them together as the columns of
  a matrix.  Factors and ordered factors are replaced by their internal
  codes.
}
\usage{
data.matrix(frame)
}
\arguments{
  \item{frame}{a data frame whose components are logical vectors,
    factors or numeric vectors.}
}
\seealso{
  \code{\link{as.matrix}},
  \code{\link{data.frame}},
  \code{\link{matrix}}.
}
\references{
  Chambers, J. M. (1992)
  \emph{Data for models.}
  Chapter 3 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\keyword{array}
\eof
\name{dataframeHelpers}
\title{Data Frame Auxiliary Functions}
\alias{xpdrows.data.frame}
\description{
  Auxiliary functions for use with data frames.
}
\usage{
xpdrows.data.frame(x, old.rows, new.rows)
}
\arguments{
  \item{x}{object of class \code{data.frame}.}
  \item{old.rows, new.rows}{row names for old and new rows.}
}
\details{
  \code{xpdrows.data.frame} is an auxiliary function which expands the
  rows of a data frame.  It is used by the data frame methods of
  \code{[<-} and \code{[[<-} (which perform subscripted assignments on a
  data frame), and not intended to be called directly.
}
\seealso{
  \code{\link{[.data.frame}}
}
\keyword{internal}
\eof
\name{date}
\alias{date}
\title{System Date and Time}
\description{
  Returns a character string of the current system date and time.
}
\usage{date()}
\value{
  The string has the form \code{"Fri Aug 20 11:11:00 1999"}, i.e.,
  length 24, since it relies on POSIX's \code{ctime} ensuring the above
  fixed format.  Timezone and Daylight Saving Time are taken account of,
  but \emph{not} indicated in the result.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{Sys.time}}
}
\examples{
(d <- date())
nchar(d) == 24
}
\keyword{utilities}
\eof
\name{dcf}
\alias{read.dcf}
\alias{write.dcf}
\title{Read and Write Data in DCF Format}
\description{
  Reads or writes an \R object from/to a file in Debian Control File format.
}
\usage{
read.dcf(file, fields=NULL)
write.dcf(x, file = "", append = FALSE,
          indent = 0.1 * getOption("width"),
          width = 0.9 * getOption("width"))
}
\arguments{
  \item{file}{either a character string naming a file or a connection.
    \code{""} indicates output to the console.}
  \item{fields}{Fields to read from the DCF file. Default is to read all
    fields.}
  \item{x}{the object to be written, typically a data frame.  If not, it
    is attempted to coerce \code{x} to a data frame.}
  \item{append}{logical.  If \code{TRUE}, the output is appended to the
    file.  If \code{FALSE}, any existing file of the name is destroyed.}
  \item{indent}{a positive integer specifying the indentation for
    continuation lines in output entries.}
  \item{width}{a positive integer giving the target column for wrapping
    lines in the output.}
}
\details{
  DCF is a simple format for storing databases in plain text files that
  can easily be directly read and written by humans. DCF is used in
  various places to store R system information, like descriptions and
  contents of packages.

  The DCF rules as implemented in R are:
  \enumerate{
    \item A database consists of one or more records, each with one or
    more named fields. Not every record must contain each field, a
    field may appear only once in a record.
    \item Regular lines start with a non-whitespace character.
    \item Regular lines are of form \code{tag:value}, i.e.,
    have a name tag and a value for the field, separated
    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 separated 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 'splines'
x <- read.dcf(file = system.file("CONTENTS", package = "splines"),
              fields = c("Entry", "Description"))
write.dcf(x)
}
\keyword{print}
\keyword{file}
\eof
\name{debug}
\title{Debug a function}
\usage{
debug(fun)
undebug(fun)
}
\alias{debug}
\alias{undebug}
\arguments{
\item{fun}{any interpreted \R function.}
}
\description{
  Set or unset the debugging flag on a function.
}
\details{
  When a function flagged for debugging is entered, normal execution
  is suspended and the body of function is executed one statement at a time.
  A new browser context is initiated for each step (and the previous one
  destroyed).
  Currently you can only debug functions that have bodies enclosed in braces.
  This is a bug and will be fixed soon.
% -when was this "soon" written? [MM. 1998.9.4]
  You take the next step by typing carriage return, \code{n} or \code{next}.
  You can see the values of variables by typing their names.
  Typing \code{c} or \code{cont} causes the debugger to continue to the
  end of the function.
  You can \code{debug} new functions before you step in to them from inside
  the debugger.
  Typing \code{Q} quits the current execution and returns you to the
  top--level prompt.
  Typing \code{where} causes the debugger to print out the current
  stack trace (all functions that are active).
  If you have variables with names that are identical to the controls
  (eg. \code{c} or \code{n} ) then you need to use \code{print(c)} and
  \code{print(n)} to evaluate them.
}
\seealso{
  \code{\link{browser}}, \code{\link{traceback}} to see the stack after
  an \code{Error: \dots} message; \code{\link[utils]{recover}} for another
  debugging approach.
}
\keyword{programming}
\keyword{environment}
\eof
\name{delay}
\title{Delay Evaluation}
\usage{
delay(x, env=.GlobalEnv)
}
\alias{delay}
\arguments{
\item{x}{an expression.}
\item{env}{an evaluation environment}
}
\description{
  \code{delay} creates a \emph{promise} to evaluate the given
  expression in the specified environment if its value is requested.
  This provides direct access to \emph{lazy evaluation} mechanism
  used by \R for the evaluation of (interpreted) functions.
}
\details{
  This is an experimental feature and its addition is purely
  for evaluation purposes.
}
\value{
  A \emph{promise} to evaluate the expression.
  The value which is returned by \code{delay} can be assigned
  without forcing its evaluation, but any further accesses
  will cause evaluation.
}
\examples{
x <- delay({
    for(i in 1:7)
        cat("yippee!\n")
    10
})

x^2 #- yippee
x^2 #- simple number
}
\keyword{programming}
\keyword{data}
\eof
\name{deparse}
\alias{deparse}
\title{Expression Deparsing}
\description{
  Turn unevaluated expressions into character strings.
}
\usage{
deparse(expr, width.cutoff = 60,
        backtick = mode(expr) \%in\% c("call", "expression", "("))
}
\arguments{
  \item{expr}{any \R expression.}
  \item{width.cutoff}{integer in \eqn{[20, 500]} determining the cutoff
    at which line-breaking is tried.}
  \item{backtick}{logical indicating whether symbolic names should be
    enclosed in backticks if they don't follow the standard syntax.}
}
\details{
  This function turns unevaluated expressions (where \dQuote{expression}
  is taken in a wider sense than the strict concept of a vector of mode
  \code{"expression"} used in \code{\link{expression}}) into character
  strings (a kind of inverse \code{\link{parse}}).

  A typical use of this is to create informative labels for data sets
  and plots.  The example shows a simple use of this facility.  It uses
  the functions \code{deparse} and \code{substitute} to create labels
  for a plot which are character string versions of the actual arguments
  to the function \code{myplot}.

  The default for the \code{backtick} option is not to quote single
  symbols but only composite expressions. This is a compromise to
  avoid breaking existing code.

}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{substitute}},
  \code{\link{parse}},
  \code{\link{expression}}.
}
\examples{
require(stats)
deparse(args(lm))
deparse(args(lm), width = 500)
myplot <-
function(x, y)
    plot(x, y, xlab=deparse(substitute(x)),
        ylab=deparse(substitute(y)))
}
e <- quote(`foo bar`)
deparse(e)
deparse(e, backtick=TRUE)
e <- quote(`foo bar`+1)
deparse(e)
\keyword{programming}
\keyword{manip}
\keyword{data}
\eof
\name{det}
\title{Calculate the Determinant of a Matrix}
\alias{det}
\alias{determinant}
\alias{determinant.matrix}
\usage{
det(x, \dots)
determinant(x, logarithm = TRUE, \dots)
}
\description{
  \code{det} calculates the determinant of a matrix. \code{determinant}
  is a generic function that returns separately the modulus of the determinant,
  optionally on the logarithm scale, and the sign of the determinant.
  }
\arguments{
  \item{x}{numeric matrix.}
  \item{logarithm}{logical; if \code{TRUE} (default) return the
    logarithm of the modulus of the determinant.}
  \item{\dots}{Optional arguments.  At present none are used.  Previous
    versions of \code{det} allowed an optional \code{method} argument.
    This argument will be ignored but will not produce an error.}
}
\value{
  For \code{det}, the determinant of \code{x}.  For \code{determinant}, a
  list with components
  \item{modulus}{a numeric value.  The modulus (absolute value) of the
    determinant if \code{logarithm} is \code{FALSE}; otherwise the
    logarithm of the modulus.}
  \item{sign}{integer; either \eqn{+1} or \eqn{-1} according to whether
    the determinant is positive or negative.}
}
\note{
  Often, computing the determinant is \emph{not} what you should be doing
  to solve a given problem.

  Prior to version 1.8.0 the \code{det} function had a \code{method}
  argument to allow use of either a QR decomposition or an
  eigenvalue-eigenvector decomposition.  The \code{determinant} function now
  uses an LU decomposition and the \code{det} function is simply a
  wrapper around a call to \code{determinant}.
}
%\seealso{\code{\link{eigen}}, \code{\link{qr}}, \code{\link{svd}}}
\examples{
(x <- matrix(1:4, ncol=2))
unlist(determinant(x))
det(x)

det(print(cbind(1,1:3,c(2,0,1))))
}

\keyword{array}
\eof
\name{detach}
\title{Detach Objects from the Search Path}
\usage{
detach(name, pos = 2, version)
}
\alias{detach}
\arguments{
  \item{name}{
    The object to detach.  Defaults to \code{search()[pos]}.
    This can be a name or a character string but \emph{not} a
    character vector.
  }
  \item{pos}{
    Index position in \code{\link{search}()} of database to
    detach.  When \code{name} is a number, \code{pos = name}
    is used.
  }
  \item{version}{A character string denoting a version number of the
    package to be loaded.  If no version is given, a suitable default
    is chosen.}
}
\description{
  Detach a database, i.e., remove it from the \code{\link{search}()} path
  of available \R objects. Usually, this is either a \code{\link{data.frame}}
  which has been \code{\link{attach}}ed or a package which was required
  previously.
}
\value{
  The attached database is returned invisibly, either as
  \code{\link{data.frame}} or as \code{\link{list}}.
}
\note{
  You cannot detach either the workspace (position 1) or the \pkg{base}
  package (the last item in the search list).
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{attach}}, \code{\link{library}}, \code{\link{search}},
  \code{\link{objects}}.
}
\examples{
require(eda)#package
detach(package:eda)
## could equally well use detach("package:eda")
## but NOT  pkg <- "package:eda"; detach(pkg)
## Instead, use
library(eda)
pkg <- "package:eda"
detach(pos = match(pkg, search()))

## careful: do not do this unless 'splines' is not already loaded.
library(splines)
detach(2)# 'pos' used for 'name'
}
\keyword{data}
\eof
\name{.Device}
\alias{.Device}
\alias{.Devices}
\title{
  Lists of Open Graphics Devices
}
\description{
  A list of the names of the open graphics devices is stored in
  \code{.Devices}. The name of the active device is stored in \code{.Device}.
}
\keyword{device}
\eof
\name{diag}
\title{Matrix Diagonals}
\usage{
diag(x = 1, nrow, ncol= )
diag(x) <- value
}
\alias{diag}
\alias{diag<-}
\description{
  Extract or replace the diagonal of a matrix,
  or construct a diagonal matrix.
}
\arguments{
  \item{x}{a matrix, vector or 1D array.}
  \item{nrow, ncol}{Optional dimensions for the result.}
  \item{value}{either a single value or a vector of length equal to that
    of the current diagonal.  Should be of a mode which can be coerced
    to that of \code{x}.}
}
\value{
  If \code{x} is a matrix then \code{diag(x)} returns the diagonal of
  \code{x}.  The resulting vector will have \code{\link{names}} if the
  matrix \code{x} has matching column and row names.

  If \code{x} is a vector (or 1D array) of length two or more,
  then \code{diag(x)} returns a diagonal matrix whose diagonal is \code{x}.

  If \code{x} is a vector of length one then \code{diag(x)} returns an
  identity matrix of order the nearest integer to \code{x}.  The
  dimension of the returned matrix can be specified by \code{nrow} and
  \code{ncol} (the default is square).

  The assignment form sets the diagonal of the matrix \code{x} to the
  given value(s).
}
\note{
  Using \code{diag(x)} can have unexpected effects if \code{x} is a
  vector that could be of length one. Use \code{diag(x, nrow =
    length(x))} for consistent behaviour.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
\code{\link{upper.tri}}, \code{\link{lower.tri}}, \code{\link{matrix}}.
}
\examples{
require(stats)
dim(diag(3))
diag(10,3,4) # guess what?
all(diag(1:3) == {m <- matrix(0,3,3); diag(m) <- 1:3; m})

diag(var(M <- cbind(X=1:5, Y=rnorm(5))))#-> vector with names "X" and "Y"
rownames(M) <- c(colnames(M),rep("",3));
M; diag(M) #  named as well
}
\keyword{array}
\eof
\name{diff}
\alias{diff}
\alias{diff.default}
\alias{diff.POSIXt}
\alias{diff.Date}
\title{Lagged Differences}
\description{
  Returns suitably lagged and iterated differences.
}
\usage{
diff(x, \dots)

\method{diff}{default}(x, lag = 1, differences = 1, \dots)

\method{diff}{POSIXt}(x, lag = 1, differences = 1, \dots)

\method{diff}{Date}(x, lag = 1, differences = 1, \dots)
}
\arguments{
  \item{x}{a numeric vector or matrix containing the values to be
    differenced.}
  \item{lag}{an integer indicating which lag to use.}
  \item{differences}{an integer indicating the order of the difference.}
  \item{\dots}{further arguments to be passed to or from methods.}
}
\details{
  \code{diff} is a generic function with a default method and ones for
  classes \code{"\link[stats]{ts}"}, \code{"\link{POSIXt}"} and
  \code{"\link{Date}"}.

  \code{\link{NA}}'s propagate.
}
\value{
  If \code{x} is a vector of length \code{n} and \code{differences=1},
  then the computed result is equal to the successive differences
  \code{x[(1+lag):n] - x[1:(n-lag)]}.

  If \code{difference} is larger than one this algorithm is applied
  recursively to \code{x}.
  Note that the returned value is a vector which is shorter than
  \code{x}.

  If \code{x} is a matrix then the difference operations are carried out
  on each column separately.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link[stats]{diff.ts}}, \code{\link[stats]{diffinv}}.
}
\examples{
diff(1:10, 2)
diff(1:10, 2, 2)
x <- cumsum(cumsum(1:10))
diff(x, lag = 2)
diff(x, differences = 2)

diff(.leap.seconds)
}
\keyword{ts}
\keyword{arith}
\eof
\name{difftime}
\alias{difftime}
\alias{as.difftime}
\alias{print.difftime}
\alias{round.difftime}
\alias{Ops.difftime}
\alias{*.difftime}
\alias{/.difftime}
\alias{Math.difftime}
\alias{Summary.difftime}
\alias{[.difftime}
\title{Time Intervals}
\description{
  Create, print and round time intervals.
}
\usage{
time1 - time2
difftime(time1, time2, tz = "",
         units = c("auto", "secs", "mins", "hours", "days", "weeks"))
as.difftime(tim, format = "\%X")

\method{round}{difftime}(x, digits = 0)
}
\arguments{
  \item{time1, time2}{date-time objects.}
  \item{tz}{a timezone specification to be used for the conversion.
    System-specific, but \code{""} is the current time zone, and
    \code{"GMT"} is UTC.}
  \item{units}{character.  Units in which the results are desired. Can
    be abbreviated.}
  \item{tim}{character string specifying a time interval.}
  \item{format}{character specifying the format of \code{tim}.}
  \item{x}{an object inheriting from class \code{"difftime"}.}
  \item{digits}{integer.  Number of significant digits to retain.}
}
\details{
  Function \code{difftime} takes a difference of two date/time objects
  (of either class) and returns an object of class \code{"difftime"}
  with an attribute indicating the units.  There is a \code{\link{round}}
  method for objects of this class, as well as methods for the
  group-generic (see \code{\link[base]{Ops}}) logical and
  arithmetic operations.

  If \code{units = "auto"}, a suitable set of units is chosen, the largest
  possible (excluding \code{"weeks"}) in which all the absolute
  differences are greater than one.

  Subtraction of two date-time objects gives an object of this class,
  by calling \code{difftime} with \code{units="auto"}.  Alternatively,
  \code{as.difftime()} works on character-coded time intervals.

  Limited arithmetic is available on \code{"difftime"} objects: they can
  be added or subtracted, and multiplied or divided by a numeric vector.
  In addition, adding or subtracting a numeric vector implicitly
  converts the numeric vector to a \code{"difftime"} object with the
  same units as the \code{"difftime"} object.
}
\seealso{
  \code{\link{DateTimeClasses}}.
}
\examples{
(z <- Sys.time() - 3600)
Sys.time() - z                # just over 3600 seconds.

## time interval between releases of 1.2.2 and 1.2.3.
ISOdate(2001, 4, 26) - ISOdate(2001, 2, 26)

as.difftime(c("0:3:20", "11:23:15"))
as.difftime(c("3:20", "23:15", "2:"), format= "\%H:\%M")# 3rd gives NA
}
\keyword{utilities}
\keyword{chron}
\eof
\name{dim}
\alias{dim}
\alias{dim.data.frame}
\alias{dim<-}
\title{Dimensions of an Object}
\usage{
dim(x)
dim(x) <- value
}
\description{
  Retrieve or set the dimension of an object.
}
\arguments{
  \item{x}{an \R object, for example a matrix, array or data frame.}
  \item{value}{For the default method, either \code{NULL} or
    a numeric vector which coerced to integer (by truncation).}
}
\details{
  The functions \code{dim} and \code{dim<-} are generic.

  \code{dim} has a method for \code{\link{data.frame}}s, which returns
  the length of the \code{row.names} attribute of \code{x} and the
  length of \code{x} (the numbers of \dQuote{rows} and \dQuote{columns}).
}
\value{
  For an array (and hence in particular, for a matrix) \code{dim} retrieves
  the \code{dim} attribute of the object.  It is \code{NULL} or a vector
  of mode \code{\link{integer}}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{ncol}}, \code{\link{nrow}} and \code{\link{dimnames}}.
}
\examples{
x <- 1:12 ; dim(x) <- c(3,4)
x

# simple versions of nrow and ncol could be defined as follows
nrow0 <- function(x) dim(x)[1]
ncol0 <- function(x) dim(x)[2]
}
\keyword{array}
\eof
\name{dimnames}
\title{Dimnames of an Object}
\alias{dimnames}
\alias{dimnames<-}
\alias{dimnames.data.frame}
\alias{dimnames<-.data.frame}
\description{
  Retrieve or set the dimnames of an object.
}
\usage{
dimnames(x)
dimnames(x) <- value
}
\arguments{
  \item{x}{an \R object, for example a matrix, array or data frame.}
  \item{value}{a possible value for \code{dimnames(x)}: see
    \dQuote{Value}.}
}
\details{
  The functions \code{dimnames} and \code{dimnames<-} are generic.

  For an \code{\link{array}} (and hence in particular, for a
  \code{\link{matrix}}), they retrieve or set the \code{dimnames}
  attribute (see \link{attributes}) of the object.  The list
  \code{value} can have names, and these will be used to label the
  dimensions of the array where appropriate.

  Both have methods for data frames.  The dimnames of a data frame are
  its \code{row.names} attribute and its \code{\link{names}}.

  As from \R 1.8.0 factor components of \code{value} will be coerced to
  character. 
}
\value{
  The dimnames of a matrix or array can be \code{NULL} or a list of the
  same length as \code{dim(x)}.  If a list, its components are either
  \code{NULL} or a character vector the length of the appropriate
  dimension of \code{x}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{rownames}}, \code{\link{colnames}};
  \code{\link{array}}, \code{\link{matrix}}, \code{\link{data.frame}}.
}
\examples{
## simple versions of rownames and colnames
## could be defined as follows
rownames0 <- function(x) dimnames(x)[[1]]
colnames0 <- function(x) dimnames(x)[[2]]
}
\keyword{array}
\keyword{manip}
\eof
\name{do.call}
\title{Execute a Function Call}
\usage{
do.call(what, args)
}
\alias{do.call}
\arguments{
  \item{what}{a character string naming the function to be called.}
  \item{args}{a \emph{list} of arguments to the function call.  The
    \code{names} attribute of \code{args} gives the argument names.}
}
\description{
  \code{do.call} executes a function call from the name of the function
  and a list of arguments to be passed to it.
}
\value{
  The result of the (evaluated) function call.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{call}} which creates an unevaluated call.
}
\examples{
do.call("complex", list(imag = 1:3))
}
\keyword{programming}
\eof
\name{double}
\title{Double Precision Vectors}
\alias{double}
\alias{as.double}
\alias{as.double.default}
\alias{is.double}
\alias{single}
\alias{as.single}
\alias{as.single.default}
\description{
  Create, coerce to or test for a double-precision vector.
}
\usage{
double(length = 0)
as.double(x, \dots)
is.double(x)
single(length = 0)
as.single(x, \dots)
}
\arguments{
  \item{length}{desired length.}
  \item{x}{object to be coerced or tested.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\value{
  \code{double} creates a double precision vector of the specified
  length.  The elements of the vector are all equal to \code{0}.

  \code{as.double} attempts to coerce its argument to be of double
  type: like \code{\link{as.vector}} it strips attributes including names.

  \code{is.double} returns \code{TRUE} or \code{FALSE} depending on
  whether its argument is of double type or not.  It is generic:
  you can write methods to handle specific classes of objects,
  see \link{InternalMethods}.
}
\note{
  \emph{\R has no single precision data type.  All real numbers are
    stored in double precision format}.  The functions \code{as.single}
  and \code{single} are identical to \code{as.double} and \code{double}
  except they set the attribute \code{Csingle} that is used in the
  \code{\link{.C}} and \code{\link{.Fortran}} interface, and they are
  intended only to be used in that context.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{integer}}.
}
\examples{
is.double(1)
all(double(3) == 0)
}
\keyword{classes}
\eof
\name{dput}
\alias{dput}
\alias{dget}
\title{Write an Internal Object to a File}
\description{
  Writes an ASCII text representation of an \R object to a file
  or connection, or uses one to recreate the object.
}
\usage{
dput(x, file = "")
dget(file)
}
\arguments{
  \item{x}{an object.}
  \item{file}{either a character string naming a file or a
    connection. \code{""} indicates output to the console.}
}
\details{
  \code{dput} opens \code{file} and deparses the object \code{x} into
  that file.  The object name is not written (contrary to \code{dump}).
  If \code{x} is a function the associated environment is stripped.
  Hence scoping information can be lost.

  Using \code{dget}, the object can be recreated (with the limitations
  mentioned above).

  \code{dput} will warn if fewer characters were written to a file than
  expected, which may indicate a full or corrupt file system.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{deparse}}, \code{\link{dump}}, \code{\link{write}}.
}
\examples{
## Write an ASCII version of mean to the file "foo"
dput(mean, "foo")
## And read it back into 'bar'
bar <- dget("foo")
unlink("foo")
}
\keyword{file}
\keyword{programming}
\keyword{connection}
\eof
\name{drop}
\alias{drop}
\title{Drop Redundant Extent Information}
\description{
  Delete the dimensions of an array which have only one level.
}
\usage{
drop(x)
}
\arguments{
  \item{x}{an array (including a matrix).}
}
\value{
  If \code{x} is an object with a \code{dim} attribute (e.g., a matrix
  or \code{\link{array}}), then \code{drop} returns an object like
  \code{x}, but with any extents of length one removed.  Any
  accompanying \code{dimnames} attribute is adjusted and returned with
  \code{x}.

  Array subsetting (\code{\link{[}}) performs this reduction unless used
  with \code{drop = FALSE}, but sometimes it is useful to invoke
  \code{drop} directly.
}
\seealso{
  \code{\link[stats]{drop1}} which is used for dropping terms in models.
}
\examples{
dim(drop(array(1:12, dim=c(1,3,1,1,2,1,2))))# = 3 2 2
drop(1:3 \%*\% 2:4)# scalar product
}
\keyword{array}
\eof
\name{dump}
\title{Text Representations of R Objects}
\usage{
dump(list, file = "dumpdata.R", append = FALSE, envir = parent.frame())
}
\alias{dump}
\description{
  This function takes a vector of names of \R objects and produces
  text representations of the objects on a file or connection.
  A \code{dump} file can be \code{\link{source}}d into another
  \R (or S) session.
}
\arguments{
  \item{list}{character. The names of one or more \R objects to be dumped.}

  \item{file}{either a character string naming a file or a
    connection. \code{""} indicates output to the console.}

  \item{append}{if \code{TRUE}, output will be appended to
    \code{file}; otherwise, it will overwrite the contents of
    \code{file}.}

  \item{envir}{the environment to search for objects.}
}
\details{
  At present the implementation of \code{dump} is very
  incomplete and it really only works for functions and
  simple vectors.

  \code{dump} will warn if fewer characters were written to a file than
  expected, which may indicate a full or corrupt file system.

  The function \code{\link{save}} is designed to be used for
  transporting \R data between machines.
}
\note{
  The \code{envir} argument was added at version 1.7.0, and changed the
  search path for named objects to include the environment from which
  \code{dump} was called.

  As \code{dump} is defined in the base namespace, the \pkg{base}
  package will be searched \emph{before} the global environment unless
  \code{dump} is called from the top level or the \code{envir} argument
  is given explicitly.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}

\seealso{\code{\link{dput}}, \code{\link{dget}},\code{\link{write}}.
}
\examples{
x <- 1; y <- 1:10
dump(ls(patt='^[xyz]'), "xyz.Rdmped")
unlink("xyz.Rdmped")
}
\keyword{file}
\keyword{connection}
\eof
\name{duplicated}
\alias{duplicated}
\alias{duplicated.default}
\alias{duplicated.data.frame}
\alias{duplicated.matrix}
\alias{duplicated.array}
\title{Determine Duplicate Elements}
\description{
  Determines which elements of a vector of data frame are duplicates
  of elements with smaller subscripts, and returns a logical vector
  indicating which elements (rows) are duplicates.
}
\usage{
duplicated(x, incomparables = FALSE, \dots)

\method{duplicated}{array}(x, incomparables = FALSE, MARGIN = 1, \dots)
}
\arguments{
  \item{x}{an atomic vector or a data frame or an array.}
  \item{incomparables}{a vector of values that cannot be compared.
    Currently, \code{FALSE} is the only possible value, meaning that all
    values can be compared.}
  \item{\dots}{arguments for particular methods.}
  \item{MARGIN}{the array margin to be held fixed: see
    \code{\link{apply}}.}
}
\details{
  This is a generic function with methods for vectors, data frames and
  arrays (including matrices).

  The data frame method works by pasting together a character
  representation of the rows separated by \code{\r}, so may be imperfect
  if the data frame has characters with embedded carriage returns or
  columns which do not reliably map to characters.

  The array method calculates for each element of the sub-array
  specified by \code{MARGIN} if the remaining dimensions are identical
  to those for an earlier element (in row-major order).  This would most
  commonly be used to find duplicated rows (the default) or columns
  (with \code{MARGIN = 2}).
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{\code{\link{unique}}.}
\examples{
x <- c(9:20, 1:5, 3:7, 0:8)
## extract unique elements
(xu <- x[!duplicated(x)])
## xu == unique(x) but unique(x) is more efficient

data(iris)
duplicated(iris)[140:143]

data(iris3)
duplicated(iris3, MARGIN = c(1, 3))
}
\keyword{logic}
\keyword{manip}
\eof
\name{dyn.load}
\alias{dyn.load}
\alias{dyn.unload}
\alias{is.loaded}
\alias{symbol.C}
\alias{symbol.For}
\title{Foreign Function Interface}
\description{
  Load or unload shared libraries, and test whether a C function or
  Fortran subroutine is available.
}
\usage{
dyn.load(x, local = TRUE, now = TRUE)
dyn.unload(x)

is.loaded(symbol, PACKAGE="")
symbol.C(name)
symbol.For(name)
}
\arguments{
  \item{x}{a character string giving the pathname to a shared library or
    DLL.}
  \item{local}{a logical value controlling whether the symbols in the
    shared library are stored in their own local table and not shared
    across shared libraries,
    or added to the global symbol table.  Whether this has any effect is
    system-dependent.
#ifdef windows
    It is ignored on Windows.
#endif
  }
  \item{now}{a logical controlling whether all symbols are resolved (and
    relocated) immediately the library is loaded or deferred until they
    are used.  This control is useful for developers testing whether a
    library is complete and has all the necessary symbols and for users
    to ignore missing symbols. Whether this has any effect is system-dependent.
#ifdef windows
    It is ignored on Windows.
#endif
  }
  \item{symbol}{a character string giving a symbol name.}
  \item{PACKAGE}{if supplied, confine the search for the \code{name} to
    the DLL given by this argument (plus the conventional extension,
    \code{.so}, \code{.sl}, \code{.dll}, \dots).  This is intended to
    add safety for packages, which can ensure by using this argument
    that no other package can override their external symbols.  Use
    \code{PACKAGE="base"} for symbols linked in to \R.  This is used in the
    same way as in \code{\link{.C}}, \code{\link{.Call}},
    \code{\link{.Fortran}} and \code{\link{.External}} functions}
  \item{name}{a character string giving either the name of a C function
    or Fortran subroutine.  Fortran names probably need to be given
    entirely in lower case (but this may be system-dependent).}
}
\details{
  See
#ifdef windows
  file \file{readme.packages},
#endif
  \sQuote{See Also} and the \emph{Writing R Extensions} manual for how to
  create a suitable shared library.  Note that unlike some versions of
  S-PLUS, \code{dyn.load} does not load an object (\code{.o}) file but a
  shared library or DLL.

  Unfortunately a very few platforms (Compaq Tru64) do not handle the
  \code{PACKAGE} argument correctly, and may incorrectly find symbols
  linked into \R.
  
  The additional arguments to \code{dyn.load} mirror the different
  aspects of the mode argument to the dlopen() routine on UNIX
  systems. They are available so that users can exercise greater control
  over the loading process for an individual library.  In general, the
  defaults values are appropriate and one should override them only if 
  there is good reason and you understand the implications.

#ifdef unix
  The \code{local} argument allows one to control whether the symbols in
  the DLL being attached are visible to other DLLs.  While maintaining
  the symbols in their own namespace is good practice, the ability to
  share symbols across related \dQuote{chapters} is useful in many
  cases.  Additionally, on certain platforms and versions of an
  operating system, certain libraries must have their symbols loaded
  globally to successfully resolve all symbols.

  One should be careful of the potential side-effect of using lazy
  loading via the \code{now} argument as \code{FALSE}.  If a routine is
  called that has a missing symbol, the process will terminate
  immediately and unsaved session variables will be lost.  The intended
  use is for library developers to call specify a value \code{TRUE} to
  check that all symbols are actually resolved and for regular users to
  all with \code{FALSE} so that missing symbols can be ignored and the
  available ones can be called.

  The initial motivation for adding these was to avoid such termination
  in the \code{_init()} routines of the Java virtual machine library.
  However, symbols loaded locally may not be (read probably) available
  to other DLLs.  Those added to the global table are available to all
  other elements of the application and so can be shared across two
  different DLLs.

  Some systems do not provide (explicit) support for local/global and
  lazy/eager symbol resolution.  This can be the source of subtle bugs.
  One can arrange to have warning messages emitted when unsupported
  options are used.  This is done by setting either of the options
  \code{verbose} or \code{warn} to be non-zero via the
  \code{\link{options}} function.  Currently, we know of only 2
  platforms that do not provide a value for local load (RTLD\_LOCAL).
  These are IRIX6.4 and unpatched versions of Solaris 2.5.1.

  There is a short discussion of these additional arguments with some
  example code available at
  \url{http://cm.bell-labs.com/stat/duncan/R/dynload}.
#endif

#ifdef windows
  External code must not change the floating point control word, but
  many DLLs do so.  Common changes are to set it to use 53 bit 
  precision instead of R's default 64 bit precision, or to unmask 
  some exceptions.  \code{dyn.load} detects such changes, 
  and restores R's control word to its default value of hex 8001F.  
  This may cause the DLL to malfunction; if so, it should be rewritten
  to save and restore the control word itself.  If \code{warn.FPU}
  is set to \code{TRUE} using the \code{\link{options}} function, 
  a warning will be printed.  (If the warning says
  that the control word was changed from some other value than 8001F, 
  please   report the circumstances to the Windows maintainers:  
  that probably indicates an internal bug.)
#endif
}
\value{
  The function \code{dyn.load} is used for its side effect which links
  the specified shared library to the executing \R image.  Calls to
  \code{.C}, \code{.Fortran} and \code{.External} can then be used to
  execute compiled C functions or Fortran subroutines contained in the
  library. 

  The function \code{dyn.unload} unlinks the shared library.

  Functions \code{symbol.C} and \code{symbol.For} map function or
  subroutine names to the symbol name in the compiled code:
  \code{is.loaded} checks if the symbol name is loaded and hence
  available for use in \code{.C} or \code{.Fortran}.
}
\note{
  The creation of shared libraries and the runtime linking of them into
  executing programs is very platform dependent.  In recent years there
  has been some simplification in the process because the C subroutine
  call \code{dlopen} has become the standard for doing this under UNIX.
  Under UNIX \code{dyn.load} uses the \code{dlopen} mechanism and should
  work on all platforms which support it.  On Windows it uses the
  standard mechanisms for loading 32-bit DLLs.

  The original code for loading DLLs in UNIX was provided by Heiner
  Schwarte.  The compatibility code for HP-UX was provided by Luke
  Tierney.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{library.dynam}} to be used inside a package's
  \code{\link{.First.lib}} initialization.

#ifdef unix
  \code{\link[utils]{SHLIB}} for how to create suitable shared objects.
#endif
#ifdef windows
  \code{\link[utils]{SHLIB}} for how to create suitable DLLs.
#endif
  
  \code{\link{.C}},
  \code{\link{.Fortran}},
  \code{\link{.External}},
  \code{\link{.Call}}.
}
\examples{
is.loaded(symbol.For("hcass2")) #-> probably TRUE, as stats is loaded
}
\keyword{interface}
\eof
\name{eigen}
\alias{eigen}
\title{Spectral Decomposition of a Matrix}
\usage{
eigen(x, symmetric, only.values = FALSE, EISPACK = FALSE)
}
\arguments{
  \item{x}{a matrix whose spectral decomposition is to be computed.}
  \item{symmetric}{if \code{TRUE}, the matrix is assumed to be symmetric
    (or Hermitian if complex) and only its lower triangle is used.
    If \code{symmetric} is not specified, the matrix is inspected for
    symmetry.}
  \item{only.values}{if \code{TRUE}, only the eigenvalues are computed
    and returned, otherwise both eigenvalues and eigenvectors are
    returned.}
  \item{EISPACK}{logical. Should EISPACK be used (for compatibility with
    \R < 1.7.0)?}
}
\description{
  Computes eigenvalues and eigenvectors.
}
\details{
  By default \code{eigen} uses the LAPACK routines DSYEVR/DSYEV,
  DGEEV, ZHEEV and ZGEEV whereas \code{eigen(EISPACK=TRUE)} provides an
  interface to the EISPACK routines \code{RS}, \code{RG}, \code{CH}
  and \code{CG}.
   
  If \code{symmetric} is unspecified, the code attempts to
  determine if the matrix is symmetric up to plausible numerical
  inaccuracies.  It is faster and surer to set the value yourself.

  \code{eigen} is preferred to \code{eigen(EISPACK = TRUE)}
  for new projects, but its eigenvectors may differ in sign and
  (in the asymmetric case) in normalization. (They may also differ
  between methods and between platforms.)

  In the real symmetric case, LAPACK routine DSYEVR is used which
  requires IEEE 754 arithmetic.  Should this not be supported on
  your platform, DSYEV is used, with a warning.

  Computing the eigenvectors is the slow part for large matrices.
}
\value{
  The spectral decomposition of \code{x} is returned as components of a
  list with components
  
  \item{values}{a vector containing the \eqn{p} eigenvalues of \code{x},
    sorted in \emph{decreasing} order, according to \code{Mod(values)}
    in the asymmetric case when they might be complex (even for real
    matrices).  For real asymmetric matrices the vector will be
    complex only if complex conjugate pairs of eigenvalues are detected.
  }
  \item{vectors}{either a \eqn{p\times p}{p * p} matrix whose columns
    contain the eigenvectors of \code{x}, or \code{NULL} if
    \code{only.values} is \code{TRUE}.
    
    For \code{eigen(, symmetric = FALSE, EISPACK =TRUE)} the choice of
    length of the eigenvectors is not defined by EISPACK. In all other
    cases the vectors are normalized to unit length.

    Recall that the eigenvectors are only defined up to a constant: even
    when the length is specified they are still only defined up to a
    scalar of modulus one (the sign for real matrices).
  }
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Smith, B. T, Boyle, J. M., Dongarra, J. J., Garbow, B. S., Ikebe,Y.,
  Klema, V., and  Moler, C. B. (1976).
  \emph{Matrix Eigensystems Routines -- EISPACK Guide}.
  Springer-Verlag Lecture Notes in Computer Science.

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

\seealso{
  \code{\link{svd}}, a generalization of \code{eigen}; \code{\link{qr}}, and
  \code{\link{chol}} for related decompositions.

  To compute the determinant of a matrix, the \code{\link{qr}}
  decomposition is much more efficient: \code{\link{det}}.

  \code{\link{capabilities}} to test for IEEE 754 arithmetic.
}
\examples{
eigen(cbind(c(1,-1),c(-1,1)))
eigen(cbind(c(1,-1),c(-1,1)), symmetric = FALSE)# same (different algorithm).

eigen(cbind(1,c(1,-1)), only.values = TRUE)
eigen(cbind(-1,2:1)) # complex values
eigen(print(cbind(c(0,1i), c(-1i,0))))# Hermite ==> real Eigen values
## 3 x 3:
eigen(cbind( 1,3:1,1:3))
eigen(cbind(-1,c(1:2,0),0:2)) # complex values

}
\keyword{algebra}
\keyword{array}
\eof
\name{environment}
\alias{environment}
\alias{environment<-}
\alias{.GlobalEnv}
\alias{globalenv}
\alias{is.environment}
\alias{new.env}
\alias{parent.env}
\alias{parent.env<-}
\alias{.BaseNamespaceEnv}
\title{Environment Access}
\description{
  Get, set, test for and create environments.
}
\usage{
environment(fun = NULL)
environment(fun) <- value
is.environment(obj)
.GlobalEnv
globalenv()
.BaseNamespaceEnv
new.env(hash=FALSE, parent=parent.frame())
parent.env(env)
parent.env(env) <- value
}
\arguments{
  \item{fun}{a \code{\link{function}}, a \code{\link[stats]{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 object \code{.BaseNamespaceEnv} is the namespace environment for
  the base package.  The environment of the base package itself is
  represented by \code{NULL}.

  The replacement function \code{parent.env<-} is extremely dangerous as
  it can be used to destructively change environments in ways that
  violate assumptions made by the internal C code.  It may be removed
  in the near future.

  \code{is.environment} is generic: you can write methods to handle
  specific classes of objects, see \link{InternalMethods}.
}
\seealso{
  The \code{envir} argument of \code{\link{eval}}.
}
\examples{
##-- all three give the same:
environment()
environment(environment)
.GlobalEnv

ls(envir=environment(approxfun(1:2,1:2, method="const")))

is.environment(.GlobalEnv) # TRUE

e1 <- new.env(TRUE, NULL)  # these two have parent package:base.
e2 <- new.env(FALSE, NULL)
assign("a", 3, env=e2)
parent.env(e1) <- e2
get("a", env=e1)

}
\keyword{data}
\keyword{programming}
\eof
\name{esoph}
\docType{data}
\alias{esoph}
\title{Smoking, Alcohol and (O)esophageal Cancer}
\description{
  Data from a case-control study of (o)esophageal cancer in
  Ile-et-Vilaine, France.
}
\usage{data(esoph)}
\format{
  A data frame with records for 88 age/alcohol/tobacco combinations.

  \tabular{rlll}{
    [,1] \tab "agegp" \tab Age group \tab 1  25--34 years\cr
    \tab \tab \tab 2  35--44\cr
    \tab \tab \tab 3  45--54\cr
    \tab \tab \tab 4  55--64\cr
    \tab \tab \tab 5  65--74\cr
    \tab \tab \tab 6  75+\cr
    [,2] \tab "alcgp" \tab Alcohol consumption \tab 1   0--39 gm/day\cr
    \tab \tab \tab 2  40--79\cr
    \tab \tab \tab 3  80--119\cr
    \tab \tab \tab 4  120+\cr
    [,3] \tab "tobgp" \tab Tobacco consumption \tab 1   0-- 9 gm/day\cr
    \tab \tab \tab 2  10--19\cr
    \tab \tab \tab 3  20--29\cr
    \tab \tab \tab 4  30+\cr
    [,4] \tab "ncases" \tab Number of cases \tab \cr
    [,5] \tab "ncontrols" \tab Number of controls \tab
  }
}
\source{
  Breslow, N. E. and Day, N. E. (1980)
  \emph{Statistical Methods in Cancer Research. 1: The Analysis of
    Case-Control Studies.}  IARC Lyon / Oxford University Press.
}
\author{Thomas Lumley}
\examples{
require(stats)
require(graphics)
data(esoph)
summary(esoph)
## effects of alcohol, tobacco and interaction, age-adjusted
model1 <- glm(cbind(ncases, ncontrols) ~ agegp + tobgp * alcgp,
              data = esoph, family = binomial())
anova(model1)
## Try a linear effect of alcohol and tobacco
model2 <- glm(cbind(ncases, ncontrols) ~ agegp + unclass(tobgp)
                                         + unclass(alcgp),
              data = esoph, family = binomial())
summary(model2)
## Re-arrange data for a mosaic plot
ttt <- table(esoph$agegp, esoph$alcgp, esoph$tobgp)
ttt[ttt == 1] <- esoph$ncases
tt1 <- table(esoph$agegp, esoph$alcgp, esoph$tobgp)
tt1[tt1 == 1] <- esoph$ncontrols
tt <- array(c(ttt, tt1), c(dim(ttt),2),
            c(dimnames(ttt), list(c("Cancer", "control"))))
mosaicplot(tt, main = "esoph data set", color = TRUE)
}
\keyword{datasets}
\eof
\name{euro}
\docType{data}
\alias{euro}
\alias{euro.cross}
\title{Conversion Rates of Euro Currencies}
\description{Conversion rates between the various Euro currencies.}
\usage{data(euro)}
\format{
  \code{euro} is a named vector of length 11, \code{euro.cross} a named
  matrix of size 11 by 11.
}
\details{
  The data set \code{euro} contains the value of 1 Euro in all
  currencies participating in the European monetary union (Austrian
  Schilling ATS, Belgian Franc BEF, German Mark DEM, Spanish Peseta ESP,
  Finnish Markka FIM, French Franc FRF, Irish Punt IEP, Italian Lira
  ITL, Luxembourg Franc LUF, Dutch Guilder NLG and Portugese Escudo
  PTE).  These conversion rates were fixed by the European Union on
  December 31, 1998.  To convert old prices to Euro prices, divide by
  the respective rate and round to 2 digits.

  The data set \code{euro.cross} contains conversion rates between the
  various Euro currencies, i.e., the result of
  \code{outer(1 / euro, euro)}.
}
\examples{
data(euro)
cbind(euro)

## These relations hold:
euro == signif(euro,6) # [6 digit precision in Euro's definition]
all(euro.cross == outer(1/euro, euro))

## Convert 20 Euro to Belgian Franc
20 * euro["BEF"]
## Convert 20 Austrian Schilling to Euro
20 / euro["ATS"]
## Convert 20 Spanish Pesetas to Italian Lira
20 * euro.cross["ESP", "ITL"]

require(graphics)
dotchart(euro,
         main = "euro data: 1 Euro in currency unit")
dotchart(1/euro,
         main = "euro data: 1 currency unit in Euros")
dotchart(log(euro, 10),
         main = "euro data: log10(1 Euro in currency unit)")
}
\keyword{datasets}
\eof
\name{eurodist}
\docType{data}
\alias{eurodist}
\title{Distances Between European Cities}
\description{
  The data give the road distances (in km) between 21 cities in Europe.
  The data are taken from a table in \dQuote{The Cambridge Encyclopaedia}.
}
\usage{data(eurodist)}
\format{
  A \code{dist} object based on 21 objects.
  (You must have the \pkg{stats} package loaded to have the methods for this
  kind of object available).
}
\source{
  Crystal, D. Ed. (1990)
  \emph{The Cambridge Encyclopaedia}.
  Cambridge: Cambridge University Press,
}
\keyword{datasets}
\eof
\name{eval}
\alias{eval}
\alias{evalq}
\alias{eval.parent}
\alias{local}
\title{Evaluate an (Unevaluated) Expression}
\description{
  Evaluate an \R expression in a specified environment.
}
\usage{
eval(expr, envir = parent.frame(),
     enclos = if(is.list(envir) || is.pairlist(envir)) parent.frame())
evalq(expr, envir, enclos)
eval.parent(expr, n = 1)
local(expr, envir = new.env())
}
\arguments{
  \item{expr}{object of mode \code{\link{expression}} or \code{call} or
    an \dQuote{unevaluated expression}.}
  \item{envir}{the \code{\link{environment}} in which \code{expr} is to
    be evaluated.  May also be a list, a data frame, or an integer as in
    \code{sys.call}.}
  \item{enclos}{Relevant when \code{envir} is a list or a data frame.
    Specifies the
    enclosure, i.e., where \R looks for objects not found in
    \code{envir}.}
  \item{n}{parent generations to go back}
}
\details{
  \code{eval} evaluates the expression \code{expr} argument in the
  environment specified by \code{envir} and returns the computed value.
  If \code{envir} is not specified, then
  \code{\link{sys.frame}(\link{sys.parent}())}, the environment where
  the call to \code{eval} was made is used.

  The \code{evalq} form is equivalent to \code{eval(quote(expr), \dots)}.

  As \code{eval} evaluates its first argument before passing it to the
  evaluator, it allows you to assign complicated expressions to symbols
  and then evaluate them.  \code{evalq} avoids this.

  \code{eval.parent(expr, n)} is a shorthand for \code{eval(expr,
    parent.frame(n))}.

  \code{local} evaluates an expression in a local environment.  It is
  equivalent to \code{evalq} except the its default argument creates a
  new, empty environment.  This is useful to create anonymous recursive
  functions and as a kind of limited namespace feature since variables
  defined in the environment are not visible from the outside.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole. (\code{eval} only.)
}
\seealso{
  \code{\link{expression}}, \code{quote}, \code{\link{sys.frame}},
  \code{\link{parent.frame}}, \code{\link{environment}}.
}
\note{
  Due to the difference in scoping rules, there are some differences
  between \R and S in this area.  In particular, the default enclosure
  in S is the global environment.

  When evaluating expressions in data frames that has been passed as
  argument to a function, the relevant enclosure is often the caller's
  environment, i.e., one needs
  \code{eval(x, data, parent.frame())}.
}
\examples{
eval(2 ^ 2 ^ 3)
mEx <- expression(2^2^3); mEx; 1 + eval(mEx)
eval({ xx <- pi; xx^2}) ; xx

a <- 3 ; aa <- 4 ; evalq(evalq(a+b+aa, list(a=1)), list(b=5)) # == 10
a <- 3 ; aa <- 4 ; evalq(evalq(a+b+aa, -1), list(b=5))         # == 12

ev <- function() {
   e1 <- parent.frame()
   ## Evaluate a in e1
   aa <- eval(expression(a),e1)
   ## evaluate the expression bound to a in e1
   a <- expression(x+y)
   list(aa = aa, eval = eval(a, e1))
}
tst.ev <- function(a = 7) { x <- pi; y <- 1; ev() }
tst.ev()#-> aa : 7,  eval : 4.14

##
## Uses of local()
##

# Mutual recursives.
# gg gets value of last assignment, an anonymous version of f.

gg <- local({
    k <- function(y)f(y)
    f <- function(x) if(x) x*k(x-1) else 1
})
gg(10)
sapply(1:5, gg)

# Nesting locals. a is private storage accessible to k
gg <- local({
    k <- local({
        a <- 1
        function(y){print(a <<- a+1);f(y)}
    })
    f <- function(x) if(x) x*k(x-1) else 1
})
sapply(1:5, gg)

ls(envir=environment(gg))
ls(envir=environment(get("k", envir=environment(gg))))
}
\keyword{data}
\keyword{programming}
\eof
\name{exists}
\alias{exists}
\title{Is an Object Defined?}
\description{
  Look for an \R object of the given name.
}
\usage{
exists(x, where = -1, envir = , frame, mode = "any", inherits = TRUE)
}
\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 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
    searched?}
}
\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 in the specified environment. If \code{inherits} is \code{TRUE} and
  a value is not found for \code{x} in the specified environment, the
  enclosing frames of the environment (and the search path) are searched
  until the name \code{x} is encountered.  \bold{Warning:}
  \code{inherits=TRUE} is the default behaviour for \R but not for S.

  If \code{mode} is specified then only objects of that mode are sought.
  The \code{mode} may specify collections such as \code{"numeric"} and
  \code{"function"}: any member of the collection will suffice.
}
\value{
  Logical, true if and only if an object of the correct name and mode is
  found.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{get}}.
}
\examples{
##  Define a substitute function if necessary:
if(!exists("some.fun", mode="function"))
  some.fun <- function(x) { cat("some.fun(x)\n"); x }
search()
exists("ls", 2) # true even though ls is in pos=3
exists("ls", 2, inherits = FALSE) # false
}
\keyword{data}
\eof
\name{expand.grid}
\title{Create a Data Frame from All Combinations of Factors}
\usage{
expand.grid(\dots)
}
\alias{expand.grid}
\arguments{
  \item{\dots}{Vectors, factors or a list containing these. }
}
\description{
  Create a data frame from all combinations of the supplied vectors or
  factors.  See the description of the return value for precise details of
  the way this is done.
}
\value{
  A data frame containing one row for each combination of the supplied
  factors.  The first factors vary fastest.  The columns are labelled by
  the factors if these are supplied as named arguments or named
  components of a list.

  Attribute \code{"out.attrs"} is a list which gives the dimension and
  dimnames for use by \code{\link[stats]{predict}} methods.
}

\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S.}
  Wadsworth \& Brooks/Cole.
}
\examples{
expand.grid(height = seq(60, 80, 5), weight = seq(100, 300, 50),
            sex = c("Male","Female"))
}
\keyword{models}
\keyword{array}
\eof
\name{expression}
\alias{expression}
\alias{is.expression}
\alias{as.expression}
\alias{as.expression.default}
\title{Unevaluated Expressions}
\description{
  Creates or tests for objects of mode \code{"expression"}.
}
\usage{
expression(\dots)

is.expression(x)
as.expression(x, \dots)
}
\arguments{
  \item{\dots}{valid \R expressions.}
  \item{x}{an arbitrary \R object.}
}
\value{
  \code{expression} returns a vector of mode \code{"expression"}
  containing its arguments as unevaluated \dQuote{\link{call}s}.

  \code{is.expression} returns \code{TRUE} if \code{expr} is an
  expression object and \code{FALSE} otherwise.

  \code{as.expression} attempts to coerce its argument into an
  expression object.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{call}},
  \code{\link{eval}},
  \code{\link{function}}.
  Further,
  \code{\link[graphics]{text}} and
  \code{\link[graphics]{legend}}
  for plotting math expressions.
}
\examples{
length(ex1 <- expression(1+ 0:9))# 1
ex1
eval(ex1)# 1:10

length(ex3 <- expression(u,v, 1+ 0:9))# 3
mode(ex3 [3]) # expression
mode(ex3[[3]])# call
rm(ex3)
}
\keyword{programming}
\keyword{dplot}
\eof
\name{factor}
\title{Factors}
\alias{factor}
\alias{ordered}
\alias{is.factor}
\alias{is.ordered}
\alias{as.factor}
\alias{as.ordered}
\alias{is.na<-.factor}
\concept{categorical variable}
\description{
  The function \code{factor} is used to encode a vector as a factor (the
  names category and enumerated type are also used for factors).  If
  \code{ordered} is \code{TRUE}, the factor levels are assumed to be ordered.
  For compatibility with S there is also a function \code{ordered}.

  \code{is.factor}, \code{is.ordered}, \code{as.factor} and \code{as.ordered}
  are the membership and coercion functions for these classes.
}
\usage{
factor(x, levels = sort(unique.default(x), na.last = TRUE),
       labels = levels, exclude = NA, ordered = is.ordered(x))
ordered(x, \dots)

is.factor(x)
is.ordered(x)

as.factor(x)
as.ordered(x)
}
\arguments{
  \item{x}{a vector of data, usually taking a small number of distinct values}
  \item{levels}{an optional vector of the values that \code{x} might
    have taken. The default is the set of values taken by \code{x},
    sorted into increasing order.}
  \item{labels}{\emph{either} an optional vector of labels for the
    levels (in the same order as \code{levels} after removing those in
    \code{exclude}), \emph{or} a character string of length 1.}
  \item{exclude}{a vector of values to be excluded when forming the
    set of levels. This should be of the same type as \code{x}, and
    will be coerced if necessary.}
  \item{ordered}{logical flag to determine if the levels should be regarded
    as ordered (in the order given).}
  \item{\dots}{(in \code{ordered(.)}): any of the above, apart from
    \code{ordered} itself.}
}
\value{
  \code{factor} returns an object of class \code{"factor"} which has a
  set of numeric codes the length of \code{x} with a \code{"levels"}
  attribute of mode \code{\link{character}}.  If \code{ordered} is true
  (or \code{ordered} is used) the result has class
  \code{c("ordered", "factor")}.

  Applying \code{factor} to an ordered or unordered factor returns a
  factor (of the same type) with just the levels which occur: see also
  \code{\link{[.factor}} for a more transparent way to achieve this.

  \code{is.factor} returns \code{TRUE} or \code{FALSE} depending on
  whether its argument is of type factor or not.  Correspondingly,
  \code{is.ordered} returns \code{TRUE} when its
  argument is ordered and \code{FALSE} otherwise.

  \code{as.factor} coerces its argument to a factor.
  It is an abbreviated form of \code{factor}.

  \code{as.ordered(x)} returns \code{x} if this is ordered, and
  \code{ordered(x)} otherwise.
}
\details{
  The type of the vector \code{x} is not restricted.

  Ordered factors differ from factors only in their class, but methods
  and the model-fitting functions treat the two classes quite differently.

  The encoding of the vector happens as follows. First all the values
  in \code{exclude} are removed from \code{levels}. If \code{x[i]} equals
  \code{levels[j]}, then the \code{i}-th element of the result is
  \code{j}.  If no match is found for \code{x[i]} in \code{levels},
  then the \code{i}-th element of the result is set to \code{\link{NA}}.

  Normally the \sQuote{levels} used as an attribute of the result are
  the reduced set of levels after removing those in \code{exclude}, but
  this can be altered by supplying \code{labels}. This should either
  be a set of new labels for the levels, or a character string, in
  which case the levels are that character string with a sequence
  number appended.

  \code{factor(x, exclude=NULL)} applied to a factor is a no-operation
  unless there are unused levels: in that case, a factor with the
  reduced level set is returned.  If \code{exclude} is used it should
  also be a factor with the same level set as \code{x} or a set of codes
  for the levels to be excluded.

  The codes of a factor may contain \code{\link{NA}}. For a numeric
  \code{x}, set \code{exclude=NULL} to make \code{\link{NA}} an extra
  level (\code{"NA"}), by default the last level.

  If \code{"NA"} is a level, the way to set a code to be missing is to
  use \code{\link{is.na}} on the left-hand-side of an assignment.
  Under those circumstances missing values are printed as \code{<NA>}.

  \code{is.factor} is generic: you can write methods to handle
  specific classes of objects, see \link{InternalMethods}.
}
\section{Warning}{
  The interpretation of a factor depends on both the codes and the
  \code{"levels"} attribute.  Be careful only to compare factors with
  the same set of levels (in the same order).  In particular,
  \code{as.numeric} applied to a factor is meaningless, and may
  happen by implicit coercion.	To \dQuote{revert} a factor \code{f} to
  its original numeric values, \code{as.numeric(levels(f))[f]} is
  recommended and slightly more efficient than
  \code{as.numeric(as.character(f))}.

  The levels of a factor are by default sorted, but the sort order
  may well depend on the locale at the time of creation, and should
  not be assumed to be ASCII.
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{[.factor}} for subsetting of factors.

  \code{\link{gl}} for construction of \dQuote{balanced} factors and
  \code{\link[stats]{C}} for factors with specified contrasts.
  \code{\link{levels}} and \code{\link{nlevels}} for accessing the
  levels, and \code{\link{unclass}} to get integer codes.
}
\examples{
(ff <- factor(substring("statistics", 1:10, 1:10), levels=letters))
as.integer(ff) # the internal codes
factor(ff)	# drops the levels that do not occur
ff[, drop=TRUE] # the same, more transparently

factor(letters[1:20], label="letter")

class(ordered(4:1))# "ordered", inheriting from "factor"

## suppose you want "NA" as a level, and to allowing missing values.
(x <- factor(c(1, 2, "NA"), exclude = ""))
is.na(x)[2] <- TRUE
x  # [1] 1    <NA> NA, <NA> used because NA is a level.
is.na(x)
# [1] FALSE  TRUE FALSE
}
\keyword{category}
\keyword{NA}
\eof
\name{faithful}
\docType{data}
\alias{faithful}
\title{Old Faithful Geyser Data}
\description{
  Waiting time between eruptions and the duration of the eruption for
  the Old Faithful geyser in Yellowstone National Park, Wyoming, USA.
}
\usage{data(faithful)}
\format{A data frame with 272 observations on 2 variables.
  \tabular{rlll}{
    [,1]  \tab eruptions  \tab numeric  \tab Eruption time in mins \cr
    [,2]  \tab waiting    \tab numeric  \tab Waiting time to next
    eruption \cr
  }
}
\source{W. Härdle.}
\references{
  Härdle, W. (1991)
  \emph{Smoothing Techniques with Implementation in S}.
  New York: Springer.

  Azzalini, A. and Bowman, A. W. (1990).
  A look at some data on the Old Faithful geyser.
  \emph{Applied Statistics} \bold{39}, 357--365.
}
\details{
  A closer look at \code{faithful$eruptions} reveals that these are
  heavily rounded times originally in seconds, where multiples of 5 are
  more frequent than expected under non-human measurement.  For a
  \dQuote{better} version of the eruptions times, see the example below.

  There are many versions of this dataset around: Azzalini and Bowman
  (1990) use a more complete version.
}
\seealso{
  \code{geyser} in package \pkg{MASS} for the Azzalini-Bowman version.
}
\examples{
data(faithful)
f.tit <-  "faithful data: Eruptions of Old Faithful"

ne60 <- round(e60 <- 60 * faithful$eruptions)
all.equal(e60, ne60)             # relative diff. ~ 1/10000
table(zapsmall(abs(e60 - ne60))) # 0, 0.02 or 0.04
faithful$better.eruptions <- ne60 / 60
te <- table(ne60)
te[te >= 4]                      # (too) many multiples of 5 !
plot(names(te), te, type="h", main = f.tit, xlab = "Eruption time (sec)")

plot(faithful[, -3], main = f.tit,
     xlab = "Eruption time (min)",
     ylab = "Waiting time to next eruption (min)")
lines(lowess(faithful$eruptions, faithful$waiting, f = 2/3, iter = 3),
      col = "red")
}
\keyword{datasets}
\eof
\name{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 the series being transformed
  is highly composite (i.e., has many factors).  If this is not the
  case, the transform may take a long time to compute and will use a
  large amount of memory.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Singleton, R. C. (1979)
  Mixed Radix Fast Fourier Transforms,
  in \emph{Programs for Digital Signal Processing},
  IEEE Digital Signal Processing Committee eds.
  IEEE Press.
}
\seealso{
  \code{\link{convolve}}, \code{\link{nextn}}.
}
\examples{
x <- 1:4
fft(x)
fft(fft(x), inverse = TRUE)/length(x)
}
\keyword{math}
\keyword{dplot}
\eof
\name{file.access}
\alias{file.access}
\title{Ascertain File Accessibility}
\description{
  Utility function to access information about files on the user's
  file systems.
}
\usage{
file.access(names, mode = 0)
}
\arguments{
  \item{names}{character vector containing file names.}
  \item{mode}{integer specifying access mode required.}
}
\details{
  The \code{mode} value can be the exclusive or of the following values
  \describe{
    \item{0}{test for existence.}
    \item{1}{test for execute permission.}
    \item{2}{test for write permission.}
    \item{4}{test for read permission.}
  }
#ifdef unix
Permission will be computed for real user ID and real group ID (rather
than the effective IDs).
#endif
#ifdef windows
Execute permission is ignored (always granted) under Windows, and all
directories have both read and write permissions.
#endif
}
\value{
  An integer vector with values \code{0} for success and \code{-1} for failure.
}

\note{
  This is intended as a replacement for the S-PLUS function
  \code{access}, a wrapper for the C function of the same name, which
  explains the return value encoding.  Note that
  the return value is \bold{false} for \bold{success}.
}

\seealso{\code{\link{file.info}}}

\examples{
fa <- file.access(dir("."))
table(fa) # count successes & failures
}
\keyword{file}
\eof
\name{file.choose}
\alias{file.choose}
\title{Choose a File Interactively}
\description{
 Choose a file interactively.
}
\usage{
file.choose(new = FALSE)
}
\arguments{
 \item{new}{Logical: choose the style of dialog box
     presented to the user: at present only new = FALSE is used.}
}
\value{
  A character vector of length one giving the file path.
}

\seealso{\code{\link{list.files}} for non-interactive selection.
#ifdef windows    
\code{\link[utils]{choose.files}} for selecting multiple files interactively.
#endif
}
\keyword{file}
\eof
\name{file.info}
\alias{file.info}
\title{Extract File Information}
\description{
  Utility function to extract information about files on the user's
  file systems.
}
\usage{
file.info(\dots)
}
\arguments{
  \item{\dots}{character vectors containing file names.}
}
\details{
  What is meant by \dQuote{file access} and hence the last access time
  is system-dependent.

#ifdef unix
  On most systems symbolic links are followed, so information is given
  about the file to which the link points rather than about the link.
#endif
#ifdef windows
  File modes are probably only useful on Windows NT/2000 machines.
#endif
}
\value{
  A data frame with row names the file names and columns
  \item{size}{integer: File size in bytes.}
  \item{isdir}{logical: Is the file a directory?}
  \item{mode}{integer of class \code{"octmode"}.  The file permissions,
    printed in octal, for example \code{644}.}
  \item{mtime, ctime, atime}{integer of class \code{"POSIXct"}:
    file modification, creation and last access times.}
#ifdef unix
  \item{uid}{integer: the user ID of the file's owner.}
  \item{gid}{integer: the group ID of the file's group.}
  \item{uname}{character: \code{uid} interpreted as a user name.}
  \item{grname}{character: \code{gid} interpreted as a group name.}
  Unknown user and group names will be \code{NA}.
#endif

Entries for non-existent or non-readable files will be \code{NA}.
#ifdef unix
The \code{uid}, \code{gid}, \code{uname} and \code{grname} columns
may not be supplied on a non-POSIX Unix system.
#endif
}
\note{
  This function will only be operational on systems with the
  \code{stat} system call, but that seems very widely available.
}

\seealso{
  \code{\link{files}}, \code{\link{file.access}},
  \code{\link{list.files}},
  and \code{\link{DateTimeClasses}} for the date formats.
}
\examples{
%-- the output of this should be "diff"able, says MM: why?
ncol(finf <- file.info(dir()))# at least six
\dontrun{finf # the whole list}
## Those that are more than 100 days old :
finf[difftime(Sys.time(), finf[,"mtime"], units="days") > 100 , 1:4]

file.info("no-such-file-exists")
}
\keyword{file}
\eof
\name{file.path}
\alias{file.path}
\title{Construct Path to File}
\description{
  Construct the path to a file from components in a platform-independent
  way.
}
\usage{
file.path(\dots, fsep = .Platform$file.sep)
}
\arguments{
  \item{\dots}{character vectors.}
  \item{fsep}{the path separator to use.}
}
\value{
  A character vector of the arguments concatenated term-by-term and
  separated by \code{fsep} if all arguments have positive length;
  otherwise, an empty character vector.
}
\keyword{file}
\eof
\name{file.show}
\alias{file.show}
\title{Display One or More Files}
\description{Display one or more files.}
\usage{
file.show(\dots, header = rep("",nfiles), title = "R Information",
          delete.file=FALSE, pager=getOption("pager"))
}
\arguments{
  \item{\dots}{one or more character vectors containing the names of the
    files to be displayed.}
  \item{header}{character vector (of the same length as the number of files
    specified in \code{\dots}) giving a header for each file being
    displayed.  Defaults to empty strings.}
  \item{title}{an overall title for the display.  If a single separate
    window is used for the display, \code{title} will be used as the window
    title. If multiple windows are used, their titles should combine the title
    and the file-specific header.}
  \item{delete.file}{should the files be deleted after display?  Used
    for temporary files.}
  \item{pager}{the pager to be used.}
}
\details{
  This function provides the core of the R help system, but it can be
  used for other purposes as well.
}
\note{
  How the pager is implemented is highly system dependent.

  The basic Unix version concatenates the files (using the headers) to a
  temporary file, and displays it in the
  pager selected by the \code{pager} argument, which is a character
  vector specifying a system command to run on the set of files.

  Most GUI systems will use a separate pager window for each file,
  and let the user leave it up while \R
  continues running.  The selection of such pagers could either be done
  using \dQuote{magic} pager names being intercepted by lower-level code
  (such as \code{"internal"} and \code{"console"} on Windows), or
  by letting \code{pager} be an R function which will be called with the
  same arguments as \code{file.show} and take care of interfacing to the
  GUI.

  Not all implementations will honour \code{delete.file}.
#ifdef windows
  In particular, using an external pager on Windows does not, as there
  is no way to know when the external application has finished with
  the file.
#endif
}
\author{Ross Ihaka, Brian Ripley.}
\seealso{
  \code{\link{files}},
  \code{\link{list.files}},
  \code{\link[utils]{help}}.
}
\examples{
file.show(file.path(R.home(), "COPYRIGHTS"))
}
\keyword{file}
\eof
\name{files}
\alias{files}
\title{File Manipulation}
\usage{
file.create(\dots)
file.exists(\dots)
file.remove(\dots)
file.rename(from, to)
file.append(file1, file2)
file.copy(from, to, overwrite = FALSE)
file.symlink(from, to)
dir.create(path, showWarnings = TRUE)
}
\alias{file.append}
\alias{file.copy}
\alias{file.create}
\alias{file.exists}
\alias{file.remove}
\alias{file.rename}
\alias{file.symlink}
\alias{dir.create}
\arguments{
  \item{\dots, file1, file2, from, to}{character vectors,
    containing file names.}
  \item{path}{a character vector containing a single path name.}
  \item{overwrite}{logical; should the destination files be overwritten?}
  \item{showWarnings}{logical; should the warnings on failure be shown?}
}
\description{
  These functions provide a low-level interface to the computer's
  file system.
}
\details{
  The \code{\dots} arguments are concatenated to form one character
  string: you can specify the files separately or as one vector.
  All of these functions expand path names: see \code{\link{path.expand}}.

  \code{file.create} creates files with the given names if they
  do not already exist and truncates them if they do.

  \code{file.exists} returns a logical vector indicating whether
  the files named by its argument exist.

  \code{file.remove} attempts to remove the files named in its
  argument.

  \code{file.rename} attempts to rename a single file.
#ifdef windows
  On Windows 9x/ME rename is not atomic, so it is possible that
  \code{to} will be deleted but \code{from} will not be renamed.
#endif

  \code{file.append} attempts to append the files named by its
  second argument to those named by its first.  The \R subscript
  recycling rule is used to align names given in vectors
  of different lengths.

  \code{file.copy} works in a similar way to \code{file.append} but with
  the arguments in the natural order for copying. Copying to existing
  destination files is skipped unless \code{overwrite = TRUE}.
  The \code{to} argument can specify a single existing directory.

  \code{file.symlink} makes symbolic links on those Unix-like platforms
  which support them.  The \code{to} argument can specify a single
  existing directory.
  
  \code{dir.create} creates the last element of the path.
}
\value{
  \code{dir.create} and \code{file.rename} return a logical,
  true for success.

  The remaining functions return a logical vector indicating which
  operation succeeded for each of the files attempted.

  \code{dir.create} will return failure if the directory already exists. 
}
\author{
  Ross Ihaka, Brian Ripley
}
\seealso{
  \code{\link{file.info}}, \code{\link{file.access}}, \code{\link{file.path}},
  \code{\link{file.show}}, \code{\link{list.files}},
  \code{\link{unlink}}, \code{\link{basename}}, \code{\link{path.expand}}.
}

\examples{
cat("file A\n", file="A")
cat("file B\n", file="B")
file.append("A", "B")
file.create("A")
file.append("A", rep("B", 10))
if(interactive()) file.show("A")
file.copy("A", "C")
dir.create("tmp")
file.copy(c("A", "B"), "tmp")
list.files("tmp")
#ifdef unix
setwd("tmp")
file.remove("B")
file.symlink(file.path("..", c("A", "B")), ".")
setwd("..")
#endif
unlink("tmp", recursive=TRUE)
file.remove("A", "B", "C")
}
\keyword{file}
\eof
\name{findInterval}
\alias{findInterval}
\title{Find Interval Numbers or Indices}
\usage{
findInterval(x, vec, rightmost.closed = FALSE, all.inside = FALSE)
}
\arguments{
  \item{x}{numeric.}
  \item{vec}{numeric, sorted (weakly) increasingly, of length \code{N},
    say.}
  \item{rightmost.closed}{logical; if true, the rightmost interval,
    \code{vec[N-1] .. vec[N]} is treated as \emph{closed}, see below.}
  \item{all.inside}{logical; if true, the returned indices are coerced
    into \eqn{\{1,\dots,N-1\}}, i.e., 0 is mapped to 1 and \eqn{N} to
    \eqn{N-1}.}
}
\description{
  Find the indices of \code{x} in \code{vec}, where \code{vec} must be
  sorted (non-decreasingly); i.e., if \code{i <- findInterval(x,v)},
  we have \eqn{v_{i_j} \le x_j < v_{i_j + 1}}{v[i[j]] <= x[j] < v[i[j] + 1]}
  where \eqn{v_0 := -\infty}{v[0] := - Inf},
  \eqn{v_{N+1} := +\infty}{v[N+1] := + Inf}, and \code{N <- length(vec)}.
  At the two boundaries, the returned index may differ by 1, depending
  on the optional arguments \code{rightmost.closed} and \code{all.inside}.
}
\details{
  The function \code{findInterval} finds the index of one vector \code{x} in
  another, \code{vec}, where the latter must be non-decreasing.  Where
  this is trivial, equivalent to \code{apply( outer(x, vec, ">="), 1, sum)},
  as a matter of fact, the internal algorithm uses interval search
  ensuring \eqn{O(n \log N)}{O(n * log(N))} complexity where
  \code{n <- length(x)} (and \code{N <- length(vec)}).  For (almost)
  sorted \code{x}, it will be even faster, basically \eqn{O(n)}.

  This is the same computation as for the empirical distribution
  function, and indeed, \code{findInterval(t, sort(X))} is
  \emph{identical} to \eqn{n F_n(t; X_1,\dots,X_n)}{n * Fn(t;
    X[1],..,X[n])} where \eqn{F_n}{Fn} is the empirical distribution
  function of \eqn{X_1,\dots,X_n}{X[1],..,X[n]}.

  When \code{rightmost.closed = TRUE}, the result
  for \code{x[j] = vec[N]} (\eqn{ = \max(vec)}), is \code{N - 1} as for
  all other values in the last interval.
}
\value{
  vector of length \code{length(x)} with values in \code{0:N} (and
  \code{NA}) where \code{N <- length(vec)}, or values coerced to
  \code{1:(N-1)} iff \code{all.inside = TRUE} (equivalently coercing all
  x values \emph{inside} the intervals).  Note that \code{\link{NA}}s are
  propagated from \code{x}, and \code{\link{Inf}} values are allowed in
  both \code{x} and \code{vec}.
}
\author{Martin Maechler}
\seealso{\code{\link{approx}(*, method = "constant")} which is a
  generalization of \code{findInterval()}, \code{\link[stats]{ecdf}} for
  computing the empirical distribution function which is (up to a factor
  of \eqn{n}) also basically the same as findInterval(.).
}
\examples{
N <- 100
X <- sort(round(rt(N, df=2), 2))
tt <- c(-100, seq(-2,2, len=201), +100)
it <- findInterval(tt, X)
tt[it < 1 | it >= N] # only first and last are outside range(X)
}
\keyword{arith}
\keyword{utilities}
\eof
\name{force}
\alias{force}
\title{Force evaluation of an Argument}
\description{
  Forces the evaluation of a function argument.
}
\usage{
force(x)
}
\arguments{
  \item{x}{a formal argument.}
}
\details{
  \code{force} forces the evaluation of a formal argument.  This can
  be useful if the argument will be captured in a closure by the lexical
  scoping rules and will later be altered by an explicit assignment or
  an implicit assignment in a loop or an apply function.
}
\examples{
f <- function(y) function() y
lf <- vector("list", 5)
for (i in seq(along = lf)) lf[[i]] <- f(i)
lf[[1]]()  # returns 5

g <- function(y) { force(y); function() y }
lg <- vector("list", 5)
for (i in seq(along = lg)) lg[[i]] <- g(i)
lg[[1]]()  # returns 1
}
\keyword{data}
\keyword{programming}
\eof
\name{formals}
\alias{formals}
\alias{formals<-}
\title{Access to and Manipulation of the Formal Arguments}
\description{
  Get or set the formal arguments of a function.
}
\usage{
formals(fun = sys.function(sys.parent()))
formals(fun, envir = parent.frame()) <- value
}
\arguments{
  \item{fun}{a function object, or see Details.}
  \item{envir}{environment in which the function should be defined.}
  \item{value}{a list of \R expressions.}
}
\value{
  \code{formals} returns the formal argument list of the function
  specified.

  The assignment form sets the formals of a function to the list on the
  right hand side.
}
\details{
  For the first form, \code{fun} can be a character string
  naming the function to be manipulated, which is searched for from the
  parent environment.
  If it is not specified, the function calling \code{formals} is used.
}
\seealso{
  \code{\link{args}} for a \dQuote{human-readable} version,
  \code{\link{alist}},
  \code{\link{body}},
  \code{\link{function}}.
}
\examples{
length(formals(lm))      # the number of formal arguments
names(formals(boxplot))  # formal arguments names

f <- function(x)a+b
formals(f) <- alist(a=,b=3) # function(a,b=3)a+b
f(2) # result = 5
}
\keyword{programming}
\eof
\name{format.Date}
\alias{format.Date}
\alias{as.character.Date}
\alias{as.Date}
\alias{as.Date.character}
\alias{as.Date.default}
\alias{as.Date.factor}
\alias{as.Date.POSIXct}
\alias{as.Date.date}
\alias{as.Date.dates}

\title{Date Conversion Functions to and from Character}
\description{
  Functions to convert between character representations and objects of
  classes \code{"Date"} representing calendar dates and times.
}
\usage{
as.Date(x, \ldots)
\method{as.Date}{character}(x, format = "", \dots)

\method{format}{Date}(x, \dots)

\method{as.character}{Date}(x, \dots)
}
\arguments{
  \item{x}{An object to be converted.}
  \item{format}{A character string.  The default is
    \code{"\%Y-\%m-\%d"}.  For details see \code{\link{strftime}}.}
  \item{\dots}{Further arguments to be passed from or to other methods,
    including \code{format} for \code{as.character} and \code{as.Date}
    methods.}
}
\details{
  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 \code{as.Date} methods accept character strings, factors, logical
  \code{NA} and objects of class \code{"\link{POSIXct}"}, which are
  converted to days by ignoring the time to be midnight in the
  representation of the time in UTC.  Also objects of class
  \code{"date"} (from package \pkg{\link[date:as.date]{date}} or
  \pkg{\link[survival:as.date]{survival}}) and
  \code{"dates"} (from package \pkg{\link[chron]{chron}}).

  The \code{format} and \code{as.character} methods ignore any
  fractional part of the date.
}
\value{
  The \code{format} and \code{as.character} methods return a character vector
  representing the date.

  The \code{as.Date} methods return an object of class \code{"\link{Date}"}.
}
\note{
  The default formats follow the rules of the ISO 8601 international
  standard which expresses a day as \code{"2001-02-03"}.

  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 a missing
  year, month or day is the current one.  If it specifies a date
  incorrectly, reliable implementations will give an error and the date
  is reported as \code{NA}.  Unfortunately some common implementations
  (such as \samp{glibc}) are unreliable and guess at the intended meaning.

  Years before 1CE (aka 1AD) will probably not be handled 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{Date} for details of the date class;
  \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.
#ifdef windows
  Windows users will find no help page for \code{strptime}: code based
  on \samp{glibc} is used (with corrections), so all the format
  specifiers described here are supported, but with no alternative
  number representation nor era available in any locale.
#endif
}
\examples{
## locale-specific version of the date
format(Sys.Date(), "\%a \%b \%d")

## 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 <- as.Date(x, "\%d\%b\%Y")
## Sys.setlocale("LC_TIME", lct)
z

## read in date/time info in format 'm/d/y'
dates <- c("02/27/92", "02/27/92", "01/14/92", "02/28/92", "02/01/92")
as.Date(x, "\%m/\%d/\%y \%H:\%M:\%S")
}
\keyword{utilities}
\keyword{chron}
\eof
\name{format}
\title{Encode in a Common Format}
\usage{
format(x, \dots)

\method{format}{AsIs}(x, width = 12, \dots)

\method{format}{data.frame}(x, \dots, justify = "none")

\method{format}{default}(x, trim = FALSE, digits = NULL,
       nsmall = 0, justify = c("left", "right", "none"),
       big.mark = "",   big.interval = 3,
     small.mark = "", small.interval = 5,
   decimal.mark = ".", \dots)

\method{format}{factor}(x, \dots)

format.pval(pv, digits = max(1, getOption("digits") - 2),
            eps = .Machine$double.eps, na.form = "NA")

prettyNum(x, big.mark = "",   big.interval = 3,
           small.mark = "", small.interval = 5,
         decimal.mark = ".", \dots)
}
\alias{format}
\alias{format.AsIs}
\alias{format.data.frame}
\alias{format.default}
\alias{format.factor}
\alias{format.pval}
\alias{prettyNum}
\description{
  Format an \R object for pretty printing: \code{format.pval} is
  intended for formatting p-values.
}
\arguments{
  \item{x}{any \R object (conceptually); typically numeric.}
  \item{trim}{logical; if \code{TRUE}, leading blanks are trimmed off the
    strings.}
  \item{digits}{how many significant digits are to be used for
    \code{\link{numeric} x}.  The default, \code{NULL}, uses
    \code{\link{options}()$digits}.  This is a suggestion: enough decimal
    places will be used so that the smallest (in magnitude) number has
    this many significant digits.}
  \item{nsmall}{number of digits which will always appear to the right of
    the decimal point in formatting real/complex numbers in
    non-scientific formats. Allowed values \code{0 <= nsmall <= 20}.}
  \item{justify}{should character vector be left-justified,
    right-justified or left alone.  When justifying, the field width is
    that of the longest string.}

  \item{big.mark}{character; if not empty used as mark between every
    \code{big.interval} decimals \emph{before} (hence \code{big}) the
    decimal point.}
  \item{big.interval}{see \code{big.mark} above; defaults to 3.}
  \item{small.mark}{character; if not empty used as mark between every
    \code{small.interval} decimals \emph{after} (hence \code{small}) the
    decimal point.}
  \item{small.interval}{see \code{small.mark} above; defaults to 5.}
  \item{decimal.mark}{the character used to indicate the numeric
    decimal point.}

  \item{pv}{a numeric vector.}
  \item{eps}{a numerical tolerance: see Details.}
  \item{na.form}{character representation of \code{NA}s.}
  \item{width}{the returned vector has elements of at most \code{width}.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\details{
  These functions convert their first argument to a vector (or array) of
  character strings which have a common format (as is done by
  \code{\link{print}}), fulfilling \code{length(format*(x, *)) ==
    length(x)}.  The trimming with \code{trim = TRUE} is useful
  when the strings are to be used for plot \code{\link[graphics]{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[stats]{print.summary.lm}} etc., and does separate formatting for
  fixed, floating point and very small values; those less than
  \code{eps} are formatted as \code{"< [eps]"} (where \dQuote{[eps]}
  stands for \code{format(eps, digits)}.

  The function \code{\link{formatC}} provides a rather more flexible
  formatting facility for numbers, but does \emph{not} provide a common
  format for several numbers, nor it is platform-independent.

  \code{format.data.frame} formats the data frame column by column,
  applying the appropriate method of \code{format} for each column.

  \code{prettyNum} is the utility function for prettifying \code{x}. If
  \code{x} is not a character, \code{format(x[i], ...)} is applied to
  each element, and then it is left unchanged if all the other arguments
  are at their defaults.  Note that \code{prettyNum(x)} may behave
  unexpectedly if \code{x} is a \code{character} not resulting from
  something like \code{format(<number>)}.
}
\note{
  Currently \code{format} drops trailing zeroes, so \code{format(6.001,
    digits=2)} gives \code{"6"} and \code{format(c(6.0, 13.1),
    digits=2)} gives \code{c(" 6", "13")}.

  Character(s) \code{"} in input strings \code{x} are escaped to \code{\\"}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}

\seealso{
  \code{\link{format.info}} indicates how something would be formatted;
  \code{\link{formatC}}, \code{\link{paste}}, \code{\link{as.character}},
  \code{\link{sprintf}}.
}
\examples{
format(1:10)

zz <- data.frame("(row names)"= c("aaaaa", "b"), check.names=FALSE)
format(zz)
format(zz, justify="left")

## use of nsmall
format(13.7)
format(13.7, nsmall=3)

r <- c("76491283764.97430", "29.12345678901", "-7.1234", "-100.1","1123")
## American:
prettyNum(r, big.mark = ",")
## Some Europeans:
prettyNum(r, big.mark = "'", decimal.mark = ",")

(dd <- sapply(1:10, function(i)paste((9:0)[1:i],collapse="")))
prettyNum(dd, big.mark="'")

pN <- stats::pnorm(1:7, lower=FALSE)
cbind(format (pN, small.mark = " ", digits = 15))
cbind(formatC(pN, small.mark = " ", digits = 17, format = "f"))
}
\keyword{character}
\keyword{print}
\eof
\name{format.info}
\title{format(.) Information}
\usage{
format.info(x, nsmall = 0)
}
\alias{format.info}
\arguments{
 \item{x}{(numeric) vector; potential argument of
   \code{\link{format}(x,\dots)}.}
 \item{nsmall}{ (see \code{\link{format}(*, nsmall)}).}
}
\description{
  Information is returned on how \code{\link{format}(x, digits =
    options("digits"))} would be formatted.
}
\value{
  An \code{\link{integer}} \code{\link{vector}} of length 3, say
  \code{r}.
  \item{r[1]}{width (number of characters) used for \code{format(x)}}
  \item{r[2]}{number of digits after decimal point.}
  \item{r[3]}{in \code{0:2}; if \eqn{\ge}{>=}\code{1}, \emph{exponential}
    representation would be used, with exponent length of \code{r[3]+1}.}
}
\note{The result \bold{depends} on the value of
  \code{\link{options}("digits")}.}
\seealso{\code{\link{format}}, \code{\link{formatC}}.}
\examples{
dd <- options("digits") ; options(digits = 7) #-- for the following
format.info(123) # 3 0 0
format.info(pi)  # 8 6 0
format.info(1e8) # 5 0 1 - exponential "1e+08"
format.info(1e222)#6 0 2 - exponential "1e+222"

x <- pi*10^c(-10,-2,0:2,8,20)
names(x) <- formatC(x,w=1,dig=3,format="g")
cbind(sapply(x,format))
t(sapply(x, format.info))

## using at least 8 digits right of "."
t(sapply(x, format.info, nsmall = 8))

# Reset old options:
options(dd)
}
\keyword{character}
\keyword{print}
\keyword{programming}
\eof
\name{formatDL}
\alias{formatDL}
\title{Format Description Lists}
\description{Format vectors of items and their descriptions as 2-column
  tables or LaTeX-style description lists.
}
\usage{
formatDL(x, y, style = c("table", "list"),
         width = 0.9 * getOption("width"), indent = NULL)
}
\arguments{
  \item{x}{a vector giving the items to be described, or a list of
    length 2 or a matrix with 2 columns giving both items and
    descriptions.}
  \item{y}{a vector of the same length as \code{x} with the
    corresponding descriptions.  Only used if \code{x} does not already
    give the descriptions.}
  \item{style}{a character string specifying the rendering style of the
    description information.  If \code{"table"}, a two-column table with
    items and descriptions as columns is produced (similar to Texinfo's
    \code{@table} environment.  If \code{"list"}, a LaTeX-style tagged
    description list is obtained.}  
  \item{width}{a positive integer giving the target column for wrapping
    lines in the output.}
  \item{indent}{a positive integer specifying the indentation of the
    second column in table style, and the indentation of continuation
    lines in list style.  Must not be greater than \code{width/2}, and
    defaults to \code{width/3} for table style and \code{width/9} for
    list style.} 
}
\value{
  a character vector with the formatted entries.
}
\details{
  After extracting the vectors of items and corresponding descriptions
  from the arguments, both are coerced to character vectors.
  
  In table style, items with more than \code{indent - 3} characters are
  displayed on a line of their own.
}
\examples{
## Use R to create the 'INDEX' for package 'splines' from its 'CONTENTS'
x <- read.dcf(file = system.file("CONTENTS", package = "splines"),
               fields = c("Entry", "Description"))
x <- as.data.frame(x)
writeLines(formatDL(x$Entry, x$Description))
## or equivalently: writeLines(formatDL(x))
## Same information in tagged description list style:
writeLines(formatDL(x$Entry, x$Description, style = "list"))
## or equivalently: writeLines(formatDL(x, style = "list"))
}
\keyword{print}
\eof
\name{formatC}
\title{Formatting Using C-style Formats}
\usage{
formatC(x, digits = NULL, width = NULL,
        format = NULL, flag = "", mode = NULL,
        big.mark = "", big.interval = 3,
      small.mark = "", small.interval = 5,
    decimal.mark = ".")

format.char(x, width = NULL, flag = "-")
}
\alias{formatC}
\alias{format.char}
\arguments{
  \item{x}{an atomic numerical or character object, typically a vector
    of real numbers.}

  \item{digits}{the desired number of digits after the decimal
    point (\code{format = "f"}) or \emph{significant} digits
    (\code{format = "g"}, \code{= "e"} or \code{= "fg"}).

    Default: 2 for integer, 4 for real numbers.  If less than 0,
    the C default of 6 digits is used.}

  \item{width}{the total field width; if both \code{digits} and
    \code{width} are unspecified, \code{width} defaults to 1,
    otherwise to \code{digits + 1}.  \code{width = 0} will use
    \code{width = digits}, \code{width < 0} means left
    justify the number in this field (equivalent to \code{flag ="-"}).
    If necessary, the result will have more characters than \code{width}.}

  \item{format}{equal to \code{"d"}  (for integers), \code{"f"},
    \code{"e"}, \code{"E"}, \code{"g"}, \code{"G"}, \code{"fg"} (for
    reals), or \code{"s"} (for strings). Default is \code{"d"} for
    integers, \code{"g"} for reals.

    \code{"f"} gives numbers in the usual
    \code{xxx.xxx} format;  \code{"e"} and \code{"E"} give \code{n.ddde+nn} or
    \code{n.dddE+nn} (scientific format); \code{"g"} and \code{"G"} put
    \code{x[i]} into scientific format only if it saves space to do so.

    \code{"fg"} uses fixed format as \code{"f"}, but \code{digits} as
    the minimum number of \emph{significant} digits.  That this can lead
    to quite long result strings, see examples below.  Note that unlike
    \code{\link{signif}} this prints large numbers with
    more significant digits than \code{digits}.}

  \item{flag}{format modifier as in Kernighan and Ritchie (1988, page 243).
    \code{"0"}  pads leading zeros; \code{"-"} does left adjustment,
    others are \code{"+"}, \code{" "}, and \code{"#"}.}

  \item{mode}{\code{"double"} (or \code{"real"}), \code{"integer"} or
    \code{"character"}.
    Default: Determined from the storage mode of \code{x}.}

  \item{big.mark, big.interval,
    small.mark, small.interval,
    decimal.mark}{used for prettying longer decimal sequences, passed to
    \code{\link{prettyNum}}: that help page explains the details.}
}
\description{
    Formatting numbers individually and flexibly, using \code{C} style
    format specifications.  \code{format.char} is a helper function for
    \code{formatC}.
}
\value{
  A character object of same size and attributes as \code{x}.
  Unlike \code{\link{format}}, each number is formatted individually.
  Looping over each element of \code{x}, \code{sprintf(\dots)} is
  called (inside the C function \code{str_signif}).

  \code{format.char(x)} and \code{formatC}, for character \code{x}, do
  simple (left or right) padding with white space.
}
\details{
  If you set \code{format} it over-rides the setting of \code{mode}, so
  \code{formatC(123.45, mode="double", format="d")} gives \code{123}.

  The rendering of scientific format is platform-dependent: some systems
  use \code{n.ddde+nnn} or \code{n.dddenn} rather than \code{n.ddde+nn}.

  \code{formatC} does not necessarily align the numbers on the decimal
  point, so \code{formatC(c(6.11, 13.1), digits=2, format="fg")} gives
  \code{c("6.1", " 13")}.  If you want common formatting for several
  numbers, use \code{\link{format}}.
}
\author{
  Originally written by Bill Dunlap, later much improved by Martin Maechler,
  it was first adapted for \R by Friedrich Leisch.
}
\references{
  Kernighan, B. W. and Ritchie, D. M. (1988)
  \emph{The C Programming Language.}  Second edition. Prentice Hall.
}
\seealso{
  \code{\link{format}}, \code{\link{sprintf}} for more general C like
  formatting.
}
\examples{
xx  <- pi * 10^(-5:4)
cbind(format(xx, digits=4), formatC(xx))
cbind(formatC(xx, wid = 9, flag = "-"))
cbind(formatC(xx, dig = 5, wid = 8, format = "f", flag = "0"))
cbind(format(xx, digits=4), formatC(xx, dig = 4, format = "fg"))

format.char(c("a", "Abc", "no way"), wid = -7)  # <=> flag = "-"
formatC(    c("a", "Abc", "no way"), wid = -7)  # <=> flag = "-"
formatC(c((-1:1)/0,c(1,100)*pi), wid=8, dig=1)

xx <- c(1e-12,-3.98765e-10,1.45645e-69,1e-70,pi*1e37,3.44e4)
##       1        2             3        4      5       6
formatC(xx)
formatC(xx, format="fg")       # special "fixed" format.
formatC(xx, format="f", dig=80)#>> also long strings
}
\keyword{character}
\keyword{print}
\eof
\name{function}
\title{Function Definition}
\usage{
function( arglist ) expr
return(value)
}
\alias{function}
\alias{return}
\description{
  These functions provide the base mechanisms for defining
  new functions in the \R language.
}
\arguments{
    \item{arglist}{Empty or one or more name or name=expression terms.}
    \item{value}{An expression.}
}
\details{
  In \R (unlike S) the names in an argument list cannot be quoted
  non-standard names.

  If \code{value} is missing, \code{NULL} is returned.  If it is a
  single expression, the value of the evaluated expression is returned.

  If the end of a function is reached without calling \code{return}, the
  value of the last evaluated expression is returned.
}
\section{Warning}{
  Prior to \R 1.8.0, \code{value} could be a series of non-empty
  expressions separated by commas.  In that case the value
  returned is a list of the evaluated expressions, with names set to
  the expressions where these are the names of \R objects. That is,
  \code{a=foo()} names the list component \code{a} and gives it value
  the result of evaluating \code{foo()}.

  This has been deprecated (and a warning is given), as it was never
  documented in S, and whether or not the list is named differs by S versions.
}
\seealso{
  \code{\link{args}} and \code{\link{body}} for accessing the arguments
  and body of a function.

  \code{\link{debug}} for debugging; \code{\link{invisible}} for
  \code{return(.)}ing \emph{invisibly}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
norm <- function(x) sqrt(x\%*\%x)
norm(1:4)

## An anonymous function:
(function(x,y){ z <- x^2 + y^2; x+y+z })(0:7, 1)
}
\keyword{programming}
\eof
\name{gc}
\title{Garbage Collection}
\usage{
gc(verbose = getOption("verbose"))
gcinfo(verbose)
}
\alias{gc}
\alias{gcinfo}
\arguments{
  \item{verbose}{logical; if \code{TRUE}, the garbage collection prints
    statistics about cons cells and the vector heap.}
}
\description{
  A call of \code{gc} causes a garbage collection to take place.
  \code{gcinfo} sets a flag so that
  automatic collection is either silent (\code{verbose=FALSE}) or
  prints memory usage statistics (\code{verbose=TRUE}).
}
\details{
  A call of \code{gc} causes a garbage collection to take place.
  This takes place automatically without user intervention, and the
  primary purpose of calling \code{gc} is for the report on memory usage.

  However, it can be useful to call \code{gc} after a large object
  has been removed, as this may prompt \R to return memory to the
  operating system.
}

\value{
  \code{gc} returns a matrix with rows \code{"Ncells"} (\emph{cons
    cells}, usually 28 bytes each on 32-bit systems and 56 bytes on
  64-bit systems, and \code{"Vcells"} (\emph{vector cells}, 8 bytes
  each), and columns \code{"used"} and \code{"gc trigger"},
  each also interpreted in megabytes (rounded up to the next 0.1Mb).

  If maxima have been set for either \code{"Ncells"} or \code{"Vcells"},
  a fifth column is printed giving the current limits in Mb (with
  \code{NA} denoting no limit).

  \code{gcinfo} returns the previous value of the flag.
}
\seealso{\code{\link{Memory}} on \R's memory management
  and \code{\link{gctorture}} if you are an \R hacker.}
\examples{
gc() #- do it now
gcinfo(TRUE) #-- in the future, show when R does it
x <- integer(100000); for(i in 1:18) x <- c(x,i)
gcinfo(verbose = FALSE)#-- don't show it anymore

gc(TRUE)
}
\keyword{environment}
\eof
\name{gc.time}
\alias{gc.time}
\title{Report Time Spent in Garbage Collection}
\description{
  This function reports the time spent in garbage collection so far in
  the \R session while GC timing was enabled..
}
\usage{
gc.time(on = TRUE)
}
\arguments{
  \item{on}{logical; if \code{TRUE}, GC timing is enabled.}
}
\value{
  A numerical vector of length 5 giving the user CPU time, the system
  CPU time, the elapsed time and children's user and system CPU times
  (normally both zero).
}
#ifdef windows
\note{
  CPU times will be returned as \code{NA} on Windows 9x/ME systems, but
  are genuine times on NT4/2000/XP systems.  Times of child processes are
  not available and will always be given as \code{NA}.
}
#endif
\section{Warnings}{
  This is experimental functionality, likely to be removed as soon as
  the next release.

  The timings are rounded up by the sampling interval for timing
  processes, and so are likely to be over-estimates.
}
\seealso{\code{\link{gc}},
  \code{\link{proc.time}} for the timings for the session.}

\examples{
gc.time()
}
\keyword{utilities}
\eof
\name{gctorture}
\title{Torture Garbage Collector}
\usage{
gctorture(on = TRUE)
}
\alias{gctorture}
\arguments{
  \item{on}{logical; turning it on/off.}
}
\description{
  Provokes garbage collection on (nearly) every memory allocation.
  Intended to ferret out memory protection bugs.  Also makes \R run
  \emph{very} slowly, unfortunately.
}
\value{
  Previous value.
}
\author{Peter Dalgaard}
\keyword{environment}

\eof
\name{get}
\alias{get}
\alias{mget}
\title{Return the Value of a Named Object}
\description{
  Search for an \R object with a given name and return it.
}
\usage{
get(x, pos=-1, envir=as.environment(pos), mode="any", inherits=TRUE)
mget(x, envir, mode = "any",
     ifnotfound = list(function(x) stop(paste("value for \"", 
    x, "\" not found", sep = ""), call. = FALSE)), inherits = FALSE)
}
\arguments{
  \item{x}{a variable name (given as a character string).}
  \item{pos}{where to look for the object (see the details section); if
    omitted, the function will search as if the name of the object
    appeared 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
    searched?}
  \item{ifnotfound}{A \code{list} of values to be used if the item is
    not found.}
}
\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.

  This function looks to see if the name \code{x} has a value bound to
  it in the specified environment. If \code{inherits} is \code{TRUE} and
  a value is not found for \code{x} in the specified environment, the
  enclosing frames of the environment (and the search path) are searched
  until the name \code{x} is encountered.  \bold{Warning:}
  \code{inherits=TRUE} is the default behaviour for \R but not for S.

  The \code{mode} may specify collections such as \code{"numeric"} and
  \code{"function"}: any member of the collection will suffice.

  Using a \code{NULL} environment is equivalent to using the current
  environment.

  For \code{mget} multiple values are returned in a named
  \code{list}. This is true even if only one value is requested. The
  value in \code{mode} and \code{ifnotfound} can be either the same length
  as the number of requested items or of length 1. The argument
  \code{ifnotfound} must be a list containing either the value to use if
  the requested item is not found or a function of one argument which
  will be called if the item is not found. The argument is the name of
  the item being requested. The default value for \code{inherits} is
  \code{FALSE}, in contrast to the default behavior for \code{get}.
}
\value{
  The object found.  (If no object is found an error results.)
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{exists}}.
}
\examples{
get("\%o\%")

##test mget
e1 <- new.env()
mget(letters, e1, ifnotfound=LETTERS)
}
\keyword{data}
\eof
\name{getNativeSymbolInfo}
\alias{getNativeSymbolInfo}
\title{Obtain a description of a native (C/Fortran) symbol}
\description{
  This finds and returns as comprehensive a description of a
  dynamically loaded or \dQuote{exported} built-in native
  symbol. It returns information about the
  name of the symbol, the library in which it is located
  and, if available, the number of arguments it expects
  and by which interface it should be called (i.e
  \code{\link{.Call}},   \code{\link{.C}},
  \code{\link{.Fortran}},  or \code{\link{.External}}).
  Additionally, it returns the address of the symbol and this
  can be passed to other C routines which can invoke.
  Specifically, this provides a way to explicitly share
  symbols between different dynamically loaded package libraries.
  Also, it provides a way to query where symbols were resolved,
  and aids diagnosing strange behavior associated with dynamic
  resolution.
}
\usage{
getNativeSymbolInfo(name, PACKAGE)
}
\arguments{
  \item{name}{the name of the native symbol as used in a call
    to \code{\link{is.loaded}}, etc.}
  \item{PACKAGE}{an optional argument that specifies to which
    dynamically loaded library we restrict the search for this symbol.
    If this is \code{"base"}, we search in the R executable itself.}
}
\details{
  This uses the same mechanism for resolving symbols as is used
  in all the native interfaces (\code{\link{.Call}}, etc.).
  If the symbol has been explicitly registered by the shared library
  in which it is contained, information about the number of arguments
  and the interface by which it should be called will be returned.
  Otherwise, a generic native symbol object is returned.
}
\value{
  If the symbol is not found, an error is raised.
  Otherwise, the value is a list containing the following elements:
  \item{name}{the name of the symbol, as given by the
  \code{name} argument.}
  \item{address}{the native memory address of the symbol which can
    be used to invoke the routine, and also
    compare with other symbol address. This is an external pointer
    object and of class \code{NativeSymbol}.}
  \item{package}{a list containing 3 elements:
    \describe{
      \item{name}{the short form of the library name which can be used
	as the value of the \code{PACKAGE} argument in
	the different native interface functions.}
      \item{path}{the fully qualified name of the shared library file.}
      \item{dynamicLookup}{a logical value indicating whether dynamic
	resolution is used when looking for symbols in this library,
	or only registered routines can be located.}
    }    
  }
  The class of this list object is \code{NativeSymbolInfo}.
  If the routine was explicitly registered by the dynamically
  loaded library, the list contains a fourth field
  \item{numParameters}{the number of arguments that should be passed
    in a call to this routine.}
  Additionally, the list will have an additional class,
  being \code{CRoutine},   \code{CallRoutine},
  \code{FortranRoutine} or \code{ExternalRoutine}
  corresponding to the R interface by which it should be invoked.
  
}
\references{
  For information about registering native routines,
  see \dQuote{In Search of {C/C++} \& {FORTRAN} Routines},
  R News, volume 1, number 3, 2001, p20--23
  (\url{http://CRAN.R-project.org/doc/Rnews/}).  
}
\author{Duncan Temple Lang}
\note{
  One motivation for accessing this reflectance information
  is to be able to pass native routines to 
  C routines as \dQuote{function pointers} in C.
  This allows us to treat native routines and R functions
  in a similar manner, such as when passing an R function
  to C code that makes callbacks to that function
  at different points in its computation
  (e.g., \code{\link[stats]{nls}}).
  Additionally, we can resolve the symbol just once and
  avoid resolving it repeatedly or using the internal
  cache.
  In the future, one may be able to treat \code{NativeSymbol}
  objects as directly callback objects.
}
\seealso{
  \code{\link{is.loaded}},
  \code{\link{.C}},
  \code{\link{.Fortran}},
  \code{\link{.External}},
  \code{\link{.Call}},
  \code{\link{dyn.load}}.  
}

\examples{
library(stats) # normally loaded
getNativeSymbolInfo("dansari")

getNativeSymbolInfo(symbol.For("hcass2"))
}
\keyword{interface}
\eof
\name{Sys.getenv}
\title{Get Environment Variables}
\usage{
Sys.getenv(x)
}
\alias{Sys.getenv}
\arguments{
  \item{x}{a character vector, or missing}
}
\description{
  \code{Sys.getenv} obtains the values of the environment variables named by
  \code{x}.
}
\value{
  A vector of the same length as \code{x}, with the variable names as
  its \code{names} attribute.  Each element holds the value of the
  environment variable named by the corresponding component of \code{x}
  (or \code{""} if no environment variable with that name was found).

  On most platforms \code{Sys.getenv()} will return a named vector giving
  the values of all the environment variables.
}
\seealso{
  \code{\link{Sys.putenv}},
  \code{\link{getwd}} for the working directory.
}
\examples{
Sys.getenv(c("R_HOME", "R_PAPERSIZE", "R_PRINTCMD", "HOST"))
}
\keyword{environment}
\keyword{utilities}
\eof
\name{getpid}
\alias{Sys.getpid}

\title{Get the Process ID of the R Session}
\description{
  Get the process ID of the \R Session.  It is guaranteed by the
  operating system that two \R sessions running simultaneously will
  have different IDs, but it is possible that \R sessions running at
  different times will have the same ID.
}
\usage{
Sys.getpid()
}
\value{
  An integer, usually a small integer between 0 and 32767 under
  Unix-alikes and a much small integer under Windows.
}
\examples{
Sys.getpid()
}
\keyword{utilities}
\eof
\name{getwd}
\alias{getwd}
\alias{setwd}
\title{Get or Set Working Directory}
\usage{
getwd()
setwd(dir)
}
\arguments{
  \item{dir}{A character string.}
}
\description{
  \code{getwd} returns an absolute filename representing the current
  working directory of the \R process; \code{setwd(dir)} is used to set
  the working directory to \code{dir}.
}
\note{
  These functions are not implemented on all platforms.
}
\seealso{\code{\link{list.files}} for the \emph{contents} of a directory.
}
\value{
  \code{getwd} returns a character vector, or \code{NULL} if the
  working directory is not available on that platform.

  \code{setwd} returns \code{NULL} invisibly.  It will give an error if
  it does not succeed.
}
\examples{
(WD <- getwd())
if (!is.null(WD)) setwd(WD)
}
\keyword{utilities}
\eof
\name{gl}
\alias{gl}
\title{Generate Factor Levels}
\description{
  Generate factors by specifying the pattern of their levels.
}
\usage{
gl(n, k, length = n*k, labels = 1:n, ordered = FALSE)
}
\arguments{
  \item{n}{an integer giving the number of levels.}
  \item{k}{an integer giving the number of replications.}
  \item{length}{an integer giving the length of the result.}
  \item{labels}{an optional vector of labels for the resulting factor
    levels.}
  \item{ordered}{a logical indicating whether the result should be
    ordered or not.}
}
\value{
  The result has levels from \code{1} to \code{n} with each value
  replicated in groups of length \code{k} out to a total length of
  \code{length}.

  \code{gl} is modelled on the \emph{GLIM} function of the same name.
}
\seealso{
  The underlying \code{\link{factor}()}.
}
\examples{
## First control, then treatment:
gl(2, 8, label = c("Control", "Treat"))
## 20 alternating 1s and 2s
gl(2, 1, 20)
## alternating pairs of 1s and 2s
gl(2, 2, 20)
}
\keyword{category}
\keyword{arith}
\eof
\name{grep}
\title{Pattern Matching and Replacement}
\alias{grep}
\alias{sub}
\alias{gsub}
\alias{regexpr}
\description{
  \code{grep} searches for matches to \code{pattern} (its first
  argument) within the character vector \code{x} (second
  argument).  \code{regexpr} does too, but returns more detail in a
  different format.

  \code{sub} and \code{gsub} perform replacement of matches determined
  by regular expression matching.
}
\usage{
grep(pattern, x, ignore.case = FALSE, extended = TRUE, perl = FALSE,
     value = FALSE, fixed = FALSE)
sub(pattern, replacement, x,
    ignore.case = FALSE, extended = TRUE, perl = FALSE)
gsub(pattern, replacement, x,
     ignore.case = FALSE, extended = TRUE, perl = FALSE)
regexpr(pattern, text,  extended = TRUE, perl = FALSE, fixed = FALSE)
}
\arguments{
  \item{pattern}{character string containing a \link{regular expression}
    (or character string for \code{fixed = TRUE}) to be matched
    in the given character vector.}
  \item{x, text}{a character vector where matches are sought.}
  \item{ignore.case}{if \code{FALSE}, the pattern matching is \emph{case
      sensitive} and if \code{TRUE}, case is ignored during matching.}
  \item{extended}{if \code{TRUE}, extended regular expression matching
    is used, and if \code{FALSE} basic regular expressions are used.}
  \item{perl}{logical. Should perl-compatible regexps be used?
    Has priority over \code{extended}.}
  \item{value}{if \code{FALSE}, a vector containing the (\code{integer})
    indices of the matches determined by \code{grep} is returned, and if
    \code{TRUE}, a vector containing the matching elements themselves is
    returned.}
  \item{fixed}{logical.  If \code{TRUE}, \code{pattern} is a string to be
    matched as is.  Overrides all other arguments.}
  \item{replacement}{a replacement for matched pattern in \code{sub} and
    \code{gsub}.}
}
\details{
  Arguments which should be character strings or character vectors are
  coerced to character if possible.

  The two \code{*sub} functions differ only in that \code{sub} replaces
  only the first occurrence of a \code{pattern} whereas \code{gsub}
  replaces all occurrences.

  For \code{regexpr} it is an error for \code{pattern} to be \code{NA},
  otherwise \code{NA} is permitted and matches only itself.

  The regular expressions used are those specified by POSIX 1003.2,
  either extended or basic, depending on the value of the
  \code{extended} argument, unless \code{perl = TRUE} when they are
  those of PCRE,
  \url{ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/}.
  (The exact set of patterns supported may depend on the version of
  PCRE installed on the system in use.)
}
\value{
  For \code{grep} a vector giving either the indices of the elements of
  \code{x} that yielded a match or, if \code{value} is \code{TRUE}, the
  matched elements.

  For \code{sub} and \code{gsub} a character vector of the same length
  as the original.

  For \code{regexpr} an integer vector of the same length as \code{text}
  giving the starting position of the first match, or \eqn{-1} if there
  is none, with attribute \code{"match.length"} giving the length of the
  matched text (or \eqn{-1} for no match).
}
\section{Warning}{
  The standard regular-expression code has been reported to be very slow
  or give errors when applied to extremely long character strings
  (tens of thousands of characters or more): the code used when
  \code{perl=TRUE} seems faster and more reliable for such usages.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole (\code{grep})
}
\seealso{
  \link{regular expression} (aka \code{\link{regexp}}) for the details
% the `aka' above is for ESS (and ?reg....) where a space is problematic
  of the pattern specification.

  \code{\link{agrep}} for approximate matching.

  \code{\link{tolower}}, \code{\link{toupper}} and \code{\link{chartr}}
  for character translations.
  \code{\link{charmatch}}, \code{\link{pmatch}}, \code{\link{match}}.
  \code{\link[utils]{apropos}} uses regexps and has nice examples.
}
\examples{
grep("[a-z]", letters)

txt <- c("arm","foot","lefroo", "bafoobar")
if(any(i <- grep("foo",txt)))
   cat("'foo' appears at least once in\n\t",txt,"\n")
i # 2 and 4
txt[i]

## Double all 'a' or 'b's;  "\\" must be escaped, i.e., 'doubled'
%% and escaped even once more in this *.Rd file!
gsub("([ab])", "\\\\1_\\\\1_", "abc and ABC")

txt <- c("The", "licenses", "for", "most", "software", "are",
  "designed", "to", "take", "away", "your", "freedom",
  "to", "share", "and", "change", "it.",
   "", "By", "contrast,", "the", "GNU", "General", "Public", "License",
   "is", "intended", "to", "guarantee", "your", "freedom", "to",
   "share", "and", "change", "free", "software", "--",
   "to", "make", "sure", "the", "software", "is",
   "free", "for", "all", "its", "users")
( i <- grep("[gu]", txt) ) # indices
stopifnot( txt[i] == grep("[gu]", txt, value = TRUE) )
(ot <- sub("[b-e]",".", txt))
txt[ot != gsub("[b-e]",".", txt)]#- gsub does "global" substitution

txt[gsub("g","#", txt) !=
    gsub("g","#", txt, ignore.case = TRUE)] # the "G" words

regexpr("en", txt)

## trim trailing white space
str = 'Now is the time      '
sub(' +$', '', str)  ## spaces only
sub('[[:space:]]+$', '', str) ## white space, POSIX-style
sub('\\\\s+$', '', str, perl = TRUE) ## Perl-style white space
}
\keyword{character}
\keyword{utilities}
\eof
\name{groupGeneric}
\alias{.Method}
\alias{.Generic}
\alias{.Group}
\alias{.Class}
\alias{Math}
\alias{Math.data.frame}
\alias{Math.factor}
\alias{Ops}
\alias{Ops.data.frame}
\alias{Ops.factor}
\alias{Ops.ordered}
\alias{Summary}
\alias{Summary.data.frame}
\alias{Summary.factor}
\alias{Arith}
\alias{Compare}
\alias{Complex}
\alias{Math2}
\alias{group generic}
\title{Group Generic Functions}
\description{
  Group generic functions can be defined with either S3 and S4 methods
  (with different groups).  Methods are defined for the group of functions
  as a whole.

  A method defined for an individual member of the group takes
  precedence over a method defined for the group as a whole.

  When package \pkg{methods} is attached there are objects visible with
  the names of the group generics: these functions should never be
  called directly (a suitable error message will result if they are).
}
\synopsis{
Math.data.frame(x, \dots)
Math.factor(x, \dots)

Ops.data.frame(e1, e2 = NULL)
Ops.factor(e1, e2)
Ops.ordered(e1, e2)

Summary.data.frame(x, \dots)
Summary.factor(x, \dots)
}
\usage{
## S3 methods have prototypes:
Math(x, \dots)
Ops(e1, e2)
Summary(x, \dots)
Complex(z)

## S4 methods have prototypes:
Arith(e1, e2)
Compare(e1, e2)
Ops(e1, e2)
Math(x)
Math2(x, digits)
Summary(x, \dots, na.rm = FALSE)
Complex(z)
}
\arguments{
  \item{x, z, e1, e2}{objects.}
  \item{digits}{number of digits to be used in \code{round} or \code{signif}.}
  \item{\dots}{further arguments passed to or from methods.}
  \item{na.rm}{logical: should missing values be removed?}
}
 
\section{S3 Group Dispatching}{
  %% --------------- grep -nw DispatchGroup src/*/*[ch]

  There are four \emph{groups} for which S3 methods can be written,
  namely the \code{"Math"}, \code{"Ops"}, \code{"Summary"} and
  \code{"Complex"} groups.  These are not \R objects, but methods can be
  supplied for them and base \R contains \code{\link{factor}},
  \code{\link{data.frame}} and \code{\link{difftime}} methods for
  the first three groups.
  (There are also a \code{\link{ordered}} method for \code{Ops},
  \code{\link{POSIXt}} methods for \code{Math} and \code{Ops}, as well as a
  \code{\link[stats]{ts}} method for \code{Ops} in package \pkg{stats}.)
  
%   A function \emph{\code{f}} belonging to one of these groups must be
%   \code{\link{.Internal}} or \code{\link{.Primitive}} and will
%   automatically be using \emph{\code{<grp>.<class> (ob)}} when
%   \emph{\code{f(<ob>)}} is called, \emph{\code{f}} belongs to group
%   \emph{\code{<grp>}} and \emph{\code{<ob>}} is of
%   \code{\link[base]{class}} \emph{\code{<class>}}.
    
  \enumerate{
    \item Group \code{"Math"}:
    \itemize{
      \item
      \code{abs}, \code{sign}, \code{sqrt}, \cr
      \code{floor}, \code{ceiling}, \code{trunc},\cr
      \code{round}, \code{signif}

      \item \code{exp}, \code{log}, \cr
      \code{cos}, \code{sin}, \code{tan},\cr
      \code{acos}, \code{asin}, \code{atan}
      
      \code{cosh}, \code{sinh}, \code{tanh},\cr
      \code{acosh}, \code{asinh}, \code{atanh}
            
      \item
      \code{lgamma}, \code{gamma}, \code{gammaCody},\cr
      \code{digamma}, \code{trigamma}, \code{tetragamma},
      \code{pentagamma}
      %   do_math1() [arithmetic.c:794]: if (DispatchGroup("Math",...))
      % 
      %
      % "atan", "round", "log", "signif":
      % do_atan()  [arithmetic.c:958]: if (DispatchGroup("Math", ..))
      % do_round() [arithmetic.c:981]: if (DispatchGroup("Math", ..))
      % do_log()   [arithmetic.c:1011]:if (DispatchGroup("Math", ..))
      % do_signif()[arithmetic.c:1034]:if (DispatchGroup("Math", ..))
      
      \item \code{cumsum}, \code{cumprod}, \code{cummax}, \code{cummin}
      % do_cum()   [cum.c:140]:    if (DispatchGroup("Math", ...))
    }
        
    \item Group \code{"Ops"}:
    \itemize{
      \item
      \code{"+"}, \code{"-"}, \code{"*"}, \code{"/"},
      \code{"^"}, \code{"\%\%"}, \code{"\%/\%"}
      % do_arith() [arithmetic.c:240]: if (DispatchGroup("Ops", ...))
            
      \item \code{"&"}, \code{"|"}, \code{"!"}
      % do_logic() [logic.c:32]:   if (DispatchGroup("Ops",...))
            
      \item \code{"=="}, \code{"!="}, 
      \code{"<"}, \code{"<="}, \code{">="}, \code{">"}
      % do_relop() [relop.c:35]:   if (DispatchGroup("Ops", ...))
    }
        
    \item Group \code{"Summary"}:
    \itemize{
      \item \code{all}, \code{any}
      % do_logic3()[logic.c:278]:  if(DispatchGroup("Summary", ...))
      \item \code{sum}, \code{prod}
      % /*NOMORE:\code{mean}, */
      \item \code{min}, \code{max}
      % do_summary() [summary.c:322]: if(DispatchGroup("Summary",...))
      \item \code{range}
    }

    \item Group \code{Complex}:
    \itemize{
      \item \code{Arg}, \code{Conj}, \code{Im}, \code{Mod}, \code{Re}
      % do_cmathfuns() [complex.c:267]: if(DispatchGroup("Complex",...))
    }
  }

  Note that a method will used for either one of these groups or one of
  its members \emph{only} if it corresponds to a \code{"class"}
  attribute, as the internal code dispatches on \code{\link{oldClass}}
  and not on \code{\link{class}}.  This is for efficiency: having to
  dispatch on, say, \code{Ops.integer} would be too slow.

  The number of arguments supplied for \code{"Math"} group generic
  methods is not checked prior to dispatch. (Most have default methods
  expecting one argument, but three expect two.)
}
\section{S4 Group Dispatching}{
  When package \pkg{methods} is attached, formal (S4) methods can be
  defined for groups.
  
  The functions belonging to the various groups are as follows:
  \describe{
    \item{\code{Arith}}{\code{"+"}, \code{"-"}, \code{"*"}, \code{"^"},
      \code{"\%\%"}, \code{"\%/\%"}, \code{"/"}}
    \item{\code{Compare}}{\code{"=="}, \code{">"}, \code{"<"},
      \code{"!="}, \code{"<="}, \code{">="}}
    \item{\code{Ops}}{\code{"Arith"}, \code{"Compare"}}
    \item{\code{Math}}{\code{"log"}, \code{"sqrt"}, \code{"log10"},
      \code{"cumprod"}, \code{"abs"}, \code{"acos"}, \code{"acosh"},
      \code{"asin"}, \code{"asinh"}, \code{"atan"}, \code{"atanh"},
      \code{"ceiling"}, \code{"cos"}, \code{"cosh"}, \code{"cumsum"},
      \code{"exp"}, \code{"floor"}, \code{"gamma"}, \code{"lgamma"},
      \code{"sin"}, \code{"sinh"}, \code{"tan"}, \code{"tanh"},
      \code{"trunc"}}
    \item{\code{Math2}}{\code{"round"}, \code{"signif"}}
    \item{\code{Summary}}{\code{"max"}, \code{"min"}, \code{"range"},
      \code{"prod"}, \code{"sum"}, \code{"any"}, \code{"all"}}
    \item{\code{Complex}}{\code{"Arg"}, \code{"Conj"}, \code{"Im"},
      \code{"Mod"}, \code{"Re"}}
  }
  Functions with the group names exist in the \pkg{methods} package but
  should not be called directly.

  All the functions in these groups (other than the group generics
  themselves) are basic functions in R.  They are not by default S4 generic
  functions, and many of them are defined as primitives, meaning that
  they do not have formal arguments.  However, you can still define
  formal methods for them.  The effect of doing so is to create an S4 generic
  function with the appropriate arguments, in the environment where the
  method definition is to be stored.  It all works more or less as you
  might expect, admittedly via a bit of trickery in the background.
}
\references{
  Appendix A, \emph{Classes and Methods} of\cr
  Chambers, J. M.  and Hastie, T. J. eds (1992)
  \emph{Statistical Models in S.}
  Wadsworth & Brooks/Cole.

  Chambers, J. M. (1998) \emph{Programming with Data.} Springer, pp. 352--4.
}
\seealso{
  \code{\link[utils]{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. ...
\dontshow{
if(.isMethodsDispatchOn()) {
  setClass("testComplex", representation(zz = "complex"))
  setMethod("Complex", "testComplex", function(z) c("groupMethod", callGeneric(z@zz)))
  setMethod("Arg", "testComplex", function(z)  c("ArgMethod", Arg(z@zz)))
  z1 = 1+2i
  z2 = new("testComplex", zz = z1)
  stopifnot(identical(Mod(z2), c("groupMethod", Mod(z1))))
  stopifnot(identical(Arg(z2), c("ArgMethod", Arg(z1))))
}
}
}
\keyword{methods}
\eof
\name{gzcon}
\alias{gzcon}
\title{
  (De)compress I/O Through Connections
}
\description{
  \code{gzcon} provides a modified connection that wraps an existing
  connection, and decompresses reads or compresses writes through that
  connection.  Standard \code{gzip} headers are assumed.
}
\usage{
gzcon(con, level = 6, allowNonCompressed = TRUE)
}
\arguments{
  \item{con}{a connection.}
  \item{level}{integer between 0 and 9, the compression level when writing.}
  \item{allowNonCompressed}{logical.  When reading, should
    non-compressed files (lacking the \code{gzip} magic header) be allowed?}
}
\details{
  If \code{con} is open then the modified
  connection is opened.  Closing the
  wrapper connection will also close the underlying connection.

  Reading from a connection which does not supply a \code{gzip} magic
  header is equivalent to reading from the original connection if
  \code{allowNonCompressed} is true, otherwise an error.

  The original connection is unusable: any object pointing to it will
  now refer to the modified connection.
}
\value{
  An object inheriting from class \code{"connection"}.  This is the same
  connection \emph{number} as supplied, but with a modified internal structure.
}
\seealso{\code{\link{gzfile}}}
\examples{
\dontrun{## This example may not still be available
## print the value to see what objects were created.
con <- url("http://hesweb1.med.virginia.edu/biostat/s/data/sav/kprats.sav")
print(load(con))}

## gzfile and gzcon can inter-work.
## Of course here one would used gzfile, but file() can be replaced by
## any other connection generator.
zz <- gzfile("ex.gz", "w")
cat("TITLE extra line", "2 3 5 7", "", "11 13 17", file = zz, sep = "\n")
close(zz)
readLines(zz<-gzcon(file("ex.gz")))
close(zz)
unlink("ex.gz")

zz <- gzcon(file("ex.gz", "wb"))
cat("TITLE extra line", "2 3 5 7", "", "11 13 17", file = zz, sep = "\n")
close(zz)
readLines(zz<-gzfile("ex.gz"))
close(zz)
unlink("ex.gz")
}
\keyword{file}
\keyword{connection}
\eof
\name{identical}
\alias{identical}
\title{ Test Objects for Exact Equality }
\description{
  The safe and reliable way to test two objects for being
  \emph{exactly} equal.  It returns \code{TRUE} in this case,
  \code{FALSE} in every other case.
}
\usage{
identical(x, y)
}
\arguments{
  \item{x, y}{any \R objects.}
}
\details{
  A call to \code{identical} is the way to test exact equality in
  \code{if} and \code{while} statements, as well as in logical
  expressions that use \code{&&} or \code{||}.  In all these
  applications you need to be assured of getting a single logical
  value.

  Users often use the comparison operators, such as \code{==} or
  \code{!=}, in these situations.  It looks natural, but it is not what
  these operators are designed to do in R.  They return an object like
  the arguments.  If you expected \code{x} and \code{y} to be of length
  1, but it happened that one of them wasn't, you will \emph{not} get a
  single \code{FALSE}.  Similarly, if one of the arguments is \code{NA},
  the result is also \code{NA}.  In either case, the expression
  \code{if(x == y)....} won't work as expected.

  The function \code{all.equal} is also sometimes used to test equality
  this way, but it was intended for something different.  First, it
  tries to allow for \dQuote{reasonable} differences in numeric results.
  Second, it returns a descriptive character vector instead of
  \code{FALSE} when the objects do not match.  Therefore, it is not the
  right function to use for reliable testing either.  (If you \emph{do} want
  to allow for numeric fuzziness in comparing objects, you can combine
  \code{all.equal} and \code{identical}, as shown in the examples
  below.)

  The computations in \code{identical} are also reliable and usually
  fast.  There should never be an error.  The only known way to kill
  \code{identical} is by having an invalid pointer at the C level,
  generating a memory fault.  It will usually find inequality quickly.
  Checking equality for two large, complicated objects can take longer
  if the objects are identical or nearly so, but represent completely
  independent copies.  For most applications, however, the computational cost
  should be negligible.

  As from \R 1.6.0, \code{identical} sees \code{NaN} as different from
  \code{as.double(NA)}, but all \code{NaN}s are equal (and all \code{NA}
  of the same type are equal).
}
\value{
  A single logical value, \code{TRUE} or \code{FALSE}, never \code{NA}
  and never anything other than a single value.
}
\author{John Chambers}

\references{
  Chambers, J. M. (1998)
  \emph{Programming with Data. A Guide to the S Language}.
  Springer.
}
\seealso{
  \code{\link{all.equal}} for descriptions of how two objects differ;
  \link{Comparison} for operators that generate elementwise comparisons.
}
\examples{
identical(1, NULL) ## FALSE -- don't try this with ==
identical(1, 1.)   ## TRUE in R (both are stored as doubles)
identical(1, as.integer(1)) ## FALSE, stored as different types

x <- 1.0; y <- 0.99999999999
## how to test for object equality allowing for numeric fuzz
identical(all.equal(x, y), TRUE)
## If all.equal thinks the objects are different, it returns a
## character string, and this expression evaluates to FALSE

# even for unusual R objects :
identical(.GlobalEnv, environment())
}
\keyword{ programming }
\keyword{ logic }
\keyword{ iteration }
\eof
\name{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}.
}
\arguments{
  \item{test}{an object which can be coerced to logical mode.}
  \item{yes}{return values for true elements of \code{test}.}
  \item{no}{return values for false elements of \code{test}.}
}
\details{
  If \code{yes} or \code{no} are too short, their elements are recycled.
  \code{yes} will be evaluated if and only if any element of \code{test}
  is true, and analogously for \code{no}.

  Missing values in \code{test} giving missing values in the result.
}
\value{
  A vector of the same length and attributes (including
  class) as \code{test} and data values from the values of
  \code{yes} or \code{no}.  The mode of the answer will be coerced to
  logical to accommodate first any values taken from \code{yes} and then
  any values taken from \code{no}.
}
\section{Warning}{
  The mode of the result may depend on the value of \code{test}, and the
  class attribute of the result is taken from \code{test} and may be
  inappropriate for the values selected from \code{yes} and \code{no}.

  Sometimes it is better to use a construction such as
  \code{(tmp <- yes; tmp[!test] <- no[!test]; tmp)}, possibly extended
  to handle missing values in \code{test}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
\code{\link{if}}.
}
\examples{
x <- c(6:-4)
sqrt(x)#- gives warning
sqrt(ifelse(x >= 0, x, NA))# no warning

## Note: the following also gives the warning !
ifelse(x >= 0, sqrt(x), NA)
}
\keyword{logic}
\keyword{programming}
\eof
\name{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[utils]{help}},
  \code{\link[utils]{example}}
}
\keyword{utilities}
\eof
\name{infert}
\docType{data}
\alias{infert}
\title{Infertility after Spontaneous and Induced Abortion}
\description{
  This is a matched case-control study dating from before the
  availability of conditional logistic regression.
}
\usage{data(infert)}
\format{
  \tabular{rll}{
    1.  \tab Education  \tab 0 = 0-5  years \cr
        \tab            \tab 1 = 6-11 years \cr
        \tab            \tab 2 = 12+  years  \cr
    2.  \tab age        \tab age in years of case \cr
    3.  \tab parity     \tab count \cr
    4.  \tab number of prior \tab 0 = 0 \cr
        \tab induced abortions \tab 1 = 1 \cr
        \tab            \tab 2 = 2 or more \cr
    5.  \tab case status\tab 1 = case \cr
        \tab            \tab 0 = control \cr
    6.  \tab number of prior \tab 0 = 0 \cr
        \tab spontaneous abortions \tab 1 = 1 \cr
        \tab            \tab 2 = 2 or more \cr
    7.  \tab matched set number \tab 1-83 \cr
    8.  \tab stratum number \tab 1-63}
}
\source{
  Trichopoulos et al. (1976)
  \emph{Br. J. of Obst. and Gynaec.} \bold{83}, 645--650.
}
\note{
  One case with two prior spontaneous abortions and two prior induced
  abortions is omitted.
}
\examples{
require(stats)
data(infert)
model1 <- glm(case ~ spontaneous+induced, data=infert,family=binomial())
summary(model1)
## adjusted for other potential confounders:
summary(model2 <- glm(case ~ age+parity+education+spontaneous+induced,
                data=infert,family=binomial()))
## Really should be analysed by conditional logistic regression
## which is in the survival package
if(require(survival)){
  model3 <- clogit(case~spontaneous+induced+strata(stratum),data=infert)
  summary(model3)
  detach()# survival (conflicts)
}
}
\keyword{datasets}
\eof
\name{integer}
\alias{integer}
\alias{as.integer}
\alias{as.integer.default}
\alias{is.integer}
\title{Integer Vectors}
\description{
  Creates or tests for objects of type \code{"integer"}.
}
\usage{
integer(length = 0)
as.integer(x, \dots)
is.integer(x)
}
\arguments{
  \item{length}{desired length.}
  \item{x}{object to be coerced or tested.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\value{
  \code{integer} creates a integer vector of the specified length.
  Each element of the vector is equal to \code{0}.
  Integer vectors exist so that data can be passed to C or Fortran code
  which expects them.

  \code{as.integer} attempts to coerce its argument to be of integer
  type. The answer will be \code{NA} unless the coercion succeeds.
  Real values larger in modulus than the largest integer are coerced to
  \code{NA} (unlike S which gives the most extreme integer of the same sign).
  Non-integral numeric values are truncated towards zero (i.e.,
  \code{as.integer(x)} equals \code{\link{trunc}(x)} there), and
  imaginary parts of complex numbers are discarded (with a warning).
  Like \code{\link{as.vector}} it strips attributes including names.

  \code{is.integer} returns \code{TRUE} or \code{FALSE} depending on
  whether its argument is of integer type or not.
  \code{is.integer} is generic: you can write methods to handle
  specific classes of objects, see \link{InternalMethods}.
  Note that factors are true for \code{is.integer} but false for
  \code{\link{is.numeric}}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{round}} (and \code{ceiling} and \code{floor} on that help
  page) to convert to integral values.
}
\examples{
  ## as.integer() truncates:
  x <- pi * c(-1:1,10)
  as.integer(x)
}
\keyword{classes}
\eof
\name{interaction}
\title{Compute Factor Interactions}
\usage{
interaction(\dots, drop = FALSE)
}
\alias{interaction}
\arguments{
  \item{\dots}{the factors for which interaction is to be computed, or a
    single list giving those factors.}
  \item{drop}{if \code{drop} is \code{TRUE}, empty factor levels
    are dropped from the result.  The default is to retain all
    factor levels.}
}
\description{
  \code{interaction} computes a factor which represents the interaction
  of the given factors.  The result of \code{interaction} is always unordered.
}
\value{
  A factor which represents the interaction of the given factors.
  The levels are labelled as the levels of the individual factors joined
  by \code{.}.
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{factor}}, \code{\link{:}}
}

\examples{
a <- gl(2, 2, 8)
b <- gl(2, 4, 8)
interaction(a, b)
}
\keyword{category}
\eof
\name{interactive}
\alias{interactive}
\title{Is R Running Interactively?}
\description{ 
  Return \code{TRUE} when \R is being used interactively and
  \code{FALSE} otherwise.
}
\usage{
interactive()
}
\seealso{
  \code{\link{source}},
  \code{\link{.First}}
}
\examples{
 .First <- function() if(interactive()) x11()
}
\keyword{environment}
\keyword{programming}
\eof
\name{invisible}
\alias{invisible}
\title{Change the Print Mode to Invisible}
\description{
  Return a (temporarily) invisible copy of an object.
}
\usage{invisible(x)}
\arguments{
  \item{x}{an arbitrary \R object.}
}
\details{
  This function can be useful when it is desired to have functions
  return values which can be assigned, but which do not print when they
  are not assigned.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{return}},
  \code{\link{function}}.
}
\examples{
# These functions both return their argument
f1 <- function(x) x
f2 <- function(x) invisible(x)
f1(1)# prints
f2(1)# does not
}
\keyword{programming}
\eof
\name{iris}
\docType{data}
\alias{iris}
\alias{iris3}
\title{Edgar Anderson's Iris Data}
\description{
  This famous (Fisher's or Anderson's) iris data set gives the
  measurements in centimeters of the variables sepal length and width
  and petal length and width, respectively, for 50 flowers from each
  of 3 species of iris.  The species are \emph{Iris setosa},
  \emph{versicolor}, and \emph{virginica}.
}
\usage{
data(iris)
data(iris3)
}
\format{
  \code{iris} is a data frame with 150 cases (rows) and 5 variables
  (columns) named \code{Sepal.Length}, \code{Sepal.Width},
  \code{Petal.Length}, \code{Petal.Width}, and \code{Species}.

  \code{iris3} gives the same data arranged as a 3-dimensional array
  of size 50 by 4 by 3, as represented by S-PLUS.  The first dimension
  gives the case number within the species subsample, the second the
  measurements with names \code{Sepal L.}, \code{Sepal W.},
  \code{Petal L.}, and \code{Petal W.}, and the third the species.
}
\source{
  Fisher, R. A. (1936)
  The use of multiple measurements in taxonomic problems.
  \emph{Annals of Eugenics},
  \bold{7}, Part II, 179--188.

  The data were collected by
  Anderson, Edgar (1935).
  The irises of the Gaspe Peninsula,
  \emph{Bulletin of the American Iris Society},
  \bold{59}, 2--5.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole. (has \code{iris3} as \code{iris}.)
}
\seealso{
  \code{\link[graphics]{matplot}} some examples of which use
  \code{iris}.
}
\examples{
data(iris3)
dni3 <- dimnames(iris3)
ii <- data.frame(matrix(aperm(iris3, c(1,3,2)), ncol=4,
                   dimnames=list(NULL, sub(" L.",".Length",
                                           sub(" W.",".Width", dni3[[2]])))),
                 Species = gl(3,50,lab=sub("S","s",sub("V","v",dni3[[3]]))))
data(iris)
all.equal(ii, iris) # TRUE
}
\keyword{datasets}
\eof
\name{is.finite}
\title{Finite, Infinite and NaN Numbers}
\usage{
is.finite(x)
is.infinite(x)
Inf
NaN
is.nan(x)
}
\alias{is.finite}
\alias{is.infinite}
\alias{Inf}
\alias{NaN}
\alias{is.nan}
\description{
  \code{is.finite} and \code{is.infinite} return a vector of the same
  length as \code{x}, indicating which elements are finite (not infinite
  and not missing).

  \code{Inf} and \code{-Inf} are positive and negative \dQuote{infinity}
  whereas \code{NaN} means \dQuote{Not a Number}.
}
\arguments{
  \item{x}{(numerical) object to be tested.}
}
\details{
  \code{is.finite} returns a vector of the same length as \code{x}
  the jth element of which is \code{TRUE} if \code{x[j]} is
  finite (i.e., it is not one of the values \code{NA}, \code{NaN},
  \code{Inf} or \code{-Inf}).  All elements of character and
  generic (list) vectors are false, so \code{is.finite} is only useful for
  logical, integer, numeric and complex vectors.  Complex numbers are
  finite if both the real and imaginary parts are.

  \code{is.infinite} returns a vector of the same length as \code{x}
  the jth element of which is \code{TRUE} if \code{x[j]} is
  infinite (i.e., equal to one of \code{Inf} or \code{-Inf}).

  \code{is.nan} tests if a numeric value is \code{NaN}.  Do not test
  equality to \code{NaN}, or even use \code{\link{identical}},
  since systems typically have many different NaN values.
  In most ports of \R one of these is used for the numeric missing
  value \code{NA}.  It is generic: you can write methods to handle
  specific classes of objects, see \link{InternalMethods}.
}
\note{
  In \R, basically all mathematical functions (including basic
  \code{\link{Arithmetic}}), are supposed to work properly with
  \code{+/- Inf} and \code{NaN} as input or output.

  The basic rule should be that calls and relations with \code{Inf}s
  really are statements with a proper mathematical \emph{limit}.
}
\seealso{
  \code{\link{NA}}, \sQuote{\emph{Not Available}} which is not a number
  as well, however usually used for missing values and applies to many
  modes, not just numeric.
}
\references{
%%- better ones ?!??
    ANSI/IEEE 754 Floating-Point Standard.

 This link does not work any more (2003/12)
    Currently (6/2002), Bill Metzenthen's \email{billm@suburbia.net} tutorial
    and examples at \cr \url{http://www.suburbia.net/~billm/}
}
\examples{
pi / 0 ## = Inf a non-zero number divided by zero creates infinity
0 / 0  ## =  NaN

1/0 + 1/0# Inf
1/0 - 1/0# NaN

stopifnot(
    1/0 == Inf,
    1/Inf == 0
)
sin(Inf)
cos(Inf)
tan(Inf)
}
\keyword{programming}
\keyword{math}
\eof
\name{is.function}
\alias{is.function}
\title{Is an Object of Type Function?}
\usage{is.function(x)}
\description{Checks whether its argument is a function.}
\arguments{
  \item{x}{an \R object.}
}
\details{
  \code{is.function} is generic: you can write methods to handle
  specific classes of objects, see \link{InternalMethods}.
}
\value{\code{TRUE} if \code{x} is a function, and \code{FALSE}
  otherwise.}
}
\keyword{programming}
\eof
\name{is.language}
\alias{is.language}
\title{Is an Object a Language Object?}
\usage{
is.language(x)
}
\description{
  \code{is.language} returns \code{TRUE} if \code{x} is either a
  variable \code{\link{name}}, a \code{\link{call}}, or an
  \code{\link{expression}}.
}
\arguments{
  \item{x}{object to be tested.}
}
\details{
  \code{is.language} is generic: you can write methods to handle
  specific classes of objects, see \link{InternalMethods}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
ll <- list(a = expression(x^2 - 2*x + 1), b = as.name("Jim"),
           c = as.expression(exp(1)), d = call("sin", pi))
sapply(ll, typeof)
sapply(ll, mode)
stopifnot(sapply(ll, is.language))
}
\keyword{programming}
\eof
\name{is.object}
\alias{is.object}
\title{Is an Object ``internally classed''?}
\usage{
is.object(x)
}
\description{
    A function rather for internal use.  It returns \code{TRUE} if the
    object \code{x} has the \R internal \code{OBJECT} attribute set, and
    \code{FALSE} otherwise.
}
\arguments{
  \item{x}{object to be tested.}
}
\details{
  \code{is.object} is generic: you can write methods to handle
  specific classes of objects, see \link{InternalMethods}.
}
\seealso{\code{\link[base]{class}}, and \code{\link[utils]{methods}}.}

\examples{
is.object(1) # FALSE
is.object(as.factor(1:3)) # TRUE
}
\keyword{methods}
\keyword{classes}
\eof
\name{is.recursive}
\alias{is.atomic}
\alias{is.recursive}
\title{Is an Object Atomic or Recursive?}
\usage{
is.atomic(x)
is.recursive(x)
}
\description{
  \code{is.atomic} returns \code{TRUE} if \code{x} does not have a list
  structure and \code{FALSE} otherwise.

  \code{is.recursive} returns \code{TRUE} if \code{x} has a recursive
  (list-like) structure and \code{FALSE} otherwise.
}
\arguments{
  \item{x}{object to be tested.}
}
\details{
  These are generic: you can write methods to handle specific classes
  of objects, see \link{InternalMethods}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{is.list}},
  \code{\link{is.language}}, etc,
  and the \code{demo("is.things")}.
}
\examples{
is.a.r <- function(x) c(is.atomic(x), is.recursive(x))

is.a.r(c(a=1,b=3))      # TRUE FALSE
is.a.r(list())          # FALSE TRUE ??
is.a.r(list(2))         # FALSE TRUE
is.a.r(lm)              # FALSE TRUE
is.a.r(y ~ x)           # FALSE TRUE
is.a.r(expression(x+1)) # FALSE TRUE (not in 0.62.3!)
}
\keyword{programming}
\keyword{classes}
\eof
\name{is.single}
\title{Is an Object of Single Precision Type?}
\usage{is.single(x)}
\alias{is.single}
\description{
\code{is.single} reports an error. There are no single precision
values in R.
}
\arguments{
  \item{x}{object to be tested.}
}
\details{
  \code{is.single} is generic: you can write methods to handle
  specific classes of objects, see \link{InternalMethods}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\keyword{classes}
\eof
\name{is.R}
\title{Are we using R, rather than S?}
\usage{
is.R()
}
\alias{is.R}
\description{
  Test if running under \R.
}

\details{
  The function has been written such as to correctly run in all versions
  of \R, S and S-PLUS.
  In order for code to be runnable in both \R and S dialects, either
  your the code must define \code{is.R} or use it as

  \code{if (exists("is.R") && is.function(is.R) && is.R()) \{}\cr
  \code{    }\emph{\#\# R-specific code}\cr
  \code{\} else \{}\cr
  \code{    }\emph{\#\# S-version of code}\cr
  \code{\}}
}
\value{
  \code{is.R} returns \code{TRUE} if we are using \R and \code{FALSE}
  otherwise.
}
\seealso{\code{\link{R.version}}, \code{\link{system}}.}
\examples{
x <- runif(20); small <- x < 0.4
## 'which()' only exists in R:
if(is.R()) which(small) else seq(along=small)[small]
}
\keyword{environment}
\keyword{utilities}
\eof
\name{islands}
\docType{data}
\alias{islands}
\title{Areas of the World's Major Landmasses}
\description{
  The areas in thousands of square miles of the landmasses which exceed
  10,000 square miles.
}
\usage{data(islands)}
\format{A named vector of length 48.}
\source{The World Almanac and Book of Facts, 1975, page 406.}
\references{
  McNeil, D. R. (1977)
  \emph{Interactive Data Analysis}.
  Wiley.
}
\examples{
require(graphics)
data(islands)
dotchart(log(islands, 10),
   main = "islands data: log10(area) (log10(sq. miles))")
dotchart(log(islands[order(islands)], 10),
   main = "islands data: log10(area) (log10(sq. miles))")
}
\keyword{datasets}
\eof
\name{jitter}
\alias{jitter}
\title{Add `Jitter' (Noise) to Numbers}
\usage{
jitter(x, factor=1, amount = NULL)
}
\arguments{
  \item{x}{numeric to which \emph{jitter} should be added.}
  \item{factor}{numeric }
  \item{amount}{numeric; if positive, used as \emph{amount} (see below),
    otherwise, if \code{= 0} the default is \code{factor * z/50}.

    Default (\code{NULL}): \code{factor * d/5} where \code{d} is about
    the smallest difference between \code{x} values.}
}
\description{
  Add a small amount of noise to a numeric vector.
}
\value{
  \code{jitter(x,\dots)} returns a numeric of the same length as
  \code{x}, but with an \code{amount} of noise added in order to break
  ties. 
}
\details{
  The result, say \code{r}, is \code{r <- x + runif(n, -a, a)}
  where \code{n <- length(x)} and \code{a} is the \code{amount}
  argument (if specified).

  Let \code{z <- max(x) - min(x)} (assuming the usual case).
  The amount \code{a} to be added is either provided as \emph{positive}
  argument \code{amount} or otherwise computed from \code{z}, as
  follows:

  If \code{amount == 0}, we set \code{a <- factor * z/50} (same as S).

  If \code{amount} is \code{NULL} (\emph{default}), we set
  \code{a <- factor * d/5} where \emph{d} is the smallest
  difference between adjacent unique (apart from fuzz) \code{x} values.
}
\references{
  Chambers, J. M., Cleveland, W. S., Kleiner, B. and Tukey, P.A. (1983)
  \emph{Graphical Methods for Data Analysis.} Wadsworth; figures 2.8,
  4.22, 5.4.

  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S.}
  Wadsworth \& Brooks/Cole.
}
\author{Werner Stahel and Martin Maechler, ETH Zurich}
\seealso{
  \code{\link[stats]{rug}} which you may want to combine with \code{jitter}.
}
\examples{
round(jitter(c(rep(1,3),  rep(1.2, 4), rep(3,3))), 3)
## These two 'fail' with S-plus 3.x:
jitter(rep(0, 7))
jitter(rep(10000,5))
}
\keyword{dplot}
\keyword{utilities}
\eof
\name{kappa}
\title{Estimate the Condition Number}
\usage{
kappa(z, \dots)
\method{kappa}{lm}(z, \dots)
\method{kappa}{default}(z, exact = FALSE, \dots)
\method{kappa}{qr}(z, \dots) 

kappa.tri(z, exact = FALSE, \dots)
}
\alias{kappa}
\alias{kappa.default}
\alias{kappa.lm}
\alias{kappa.qr}
\alias{kappa.tri}
\arguments{
  \item{z}{A matrix or a the result of \code{\link{qr}} or a fit from a class
    inheriting from \code{"lm"}.}
  \item{exact}{logical. Should the result be exact?}
  \item{\dots}{further arguments passed to or from other methods.}
}
\description{
 An estimate of the condition number of a matrix or of the \eqn{R} matrix of a
 \eqn{QR} decomposition, perhaps of a linear fit.  The condition number is
 defined as the ratio of the largest to the smallest \emph{non-zero}
 singular value of the matrix.
}
\details{
 If \code{exact = FALSE} (the default) the condition number is estimated
 by a cheap approximation. Following S, this uses the LINPACK routine
 \file{dtrco.f}.  However, in \R (or S) the exact calculation is also
 likely to be quick enough.

 \code{kappa.tri} is an internal function called by \code{kappa.qr}.
}
\value{
  The condition number, \eqn{kappa}, or an approximation if
  \code{exact = FALSE}.  
}
\references{
  Chambers, J. M. (1992)
  \emph{Linear models.}
  Chapter 4 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\author{
  The design was inspired by (but differs considerably from)
  the S function of the same name described in Chambers (1992).
}
  
\seealso{
  \code{\link{svd}} for the singular value decomposition and
  \code{\link{qr}} for the \eqn{QR} one.
}
\examples{
kappa(x1 <- cbind(1,1:10))# 15.71
kappa(x1, exact = TRUE)        # 13.68
kappa(x2 <- cbind(x1,2:11))# high! [x2 is singular!]

hilbert <- function(n) { i <- 1:n; 1 / outer(i - 1, i, "+") }
sv9 <- svd(h9 <- hilbert(9))$ d
kappa(h9)# pretty high!
kappa(h9, exact = TRUE) == max(sv9) / min(sv9)
kappa(h9, exact = TRUE) / kappa(h9) # .677 (i.e., rel.error = 32\%)
}
\keyword{math}
\eof
\name{kronecker}

\title{Kronecker products on arrays}

\usage{
kronecker(X, Y, FUN = "*", make.dimnames = FALSE, \dots)
X \%x\% Y
}

\alias{kronecker}
\alias{\%x\%}

\arguments{
 \item{X}{A vector or array.}
 \item{Y}{A vector or array.}
 \item{FUN}{a function; it may be a quoted string.}
 \item{make.dimnames}{Provide dimnames that are the product of the
dimnames of \code{X} and \code{Y}.}
 \item{\dots}{optional arguments to be passed to \code{FUN}.}
}

\description{
Computes the generalised kronecker product of two arrays,
\code{X} and \code{Y}.  \code{kronecker(X, Y)} returns an array
\code{A} with dimensions \code{dim(X) * dim(Y)}.}

\details{If \code{X} and \code{Y} do not have the same number of
dimensions, the smaller array is padded with dimensions of size
one.  The returned array comprises submatrices constructed by
taking \code{X} one term at a time and expanding that term as
\code{FUN(x, Y, ...)}.

\code{\%x\%} is an alias for \code{kronecker} (where
\code{FUN} is hardwired to \code{"*"}).
}

\references{
  Shayle R. Searle (1982)
  \emph{Matrix Algebra Useful for Statistics.} John Wiley and Sons.
}

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

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

\examples{
# simple scalar multiplication
( M <- matrix(1:6, ncol=2) )
kronecker(4, M)
# Block diagonal matrix:
kronecker(diag(1, 3), M)

# ask for dimnames

fred <- matrix(1:12, 3, 4, dimnames=list(LETTERS[1:3], LETTERS[4:7]))
bill <- c("happy" = 100, "sad" = 1000)
kronecker(fred, bill, make.dimnames = TRUE)

bill <- outer(bill, c("cat"=3, "dog"=4))
kronecker(fred, bill, make.dimnames = TRUE)
}

\keyword{array}
\eof
\name{labels}
\title{Find Labels from Object}
\usage{
labels(object, \dots)
}
\alias{labels}
\alias{labels.default}
\alias{labels.terms}
\alias{labels.lm}
\arguments{
  \item{object}{Any \R object: the function is generic.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\description{
  Find a suitable set of labels from an object for use in printing or
  plotting, for example.  A generic function.
}
\value{
  A character vector or list of such vectors. For a vector the results
  is the names or \code{seq(along=x)}, for a data frame or array it is
  the dimnames (with \code{NULL} expanded to \code{seq(len=d[i])}), for
  a \code{terms} object it is the term labels and for an \code{lm}
  object it is the term labels for estimable terms.
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S.}
  Wadsworth \& Brooks/Cole.
}
\keyword{print}
\keyword{models}
\eof
\name{lapply}
\title{Apply a Function over a List or Vector}
\usage{
lapply(X, FUN, \dots)
sapply(X, FUN, \dots, simplify = TRUE, USE.NAMES = TRUE)

replicate(n, expr, simplify = TRUE) 
}
\alias{lapply}
\alias{sapply}
\alias{replicate}
\arguments{
  \item{X}{list or vector to be used.}
  \item{FUN}{the function to be applied.
    In the case of functions like \code{+},
    \code{\%*\%}, etc., the function name must be quoted.}
  \item{\dots}{optional arguments to \code{FUN}.}
  \item{simplify}{logical; should the result be simplified to a vector
    or matrix if possible?}
  \item{USE.NAMES}{logical; if \code{TRUE} and if \code{X} is character,
    use \code{X} as \code{\link{names}} for the result unless it had names
    already.}
  \item{n}{Number of replications.}
  \item{expr}{Expression to evaluate repeatedly.}
}
\description{
  \code{lapply} returns a list of the same length as \code{X}.  Each
  element of which is the result of applying \code{FUN} to the
  corresponding element of \code{X}.

  \code{sapply} is a \dQuote{user-friendly} version of \code{lapply}
  also accepting vectors as \code{X}, and returning a vector or matrix
  with \code{dimnames} if appropriate.

  \code{replicate} is a wrapper for the common use of \code{sapply} for
  repeated evaluation of an expression (which will usually involve
  random number generation).
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{apply}}, \code{\link{tapply}}.
}
\examples{
x <- list(a = 1:10, beta = exp(-3:3), logic = c(TRUE,FALSE,FALSE,TRUE))
# compute the list mean for each list element
lapply(x,mean)
# median and quartiles for each list element
lapply(x, quantile, probs = 1:3/4)
sapply(x, quantile)
i39 <- sapply(3:9, seq) # list of vectors
sapply(i39, fivenum)

hist(replicate(100, mean(rexp(10))))
}
\keyword{iteration}
\keyword{list}
\eof
\name{length}
\alias{length}
\alias{length<-}
\alias{length<-.factor}
\title{Length of an Object}
\description{
  Get or set the length of vectors (including lists) and factors, and of
  any other \R object for which a method has been defined.
}
\usage{
length(x)
length(x) <- value
}
\arguments{
  \item{x}{a vector or list or factor.}
  \item{value}{an integer.}
}
\value{
  The length of \code{x} as an \code{\link{integer}} of length 1,
  if \code{x} is (or can be coerced to) a vector or list.  Otherwise,
  \code{length} returns \code{NA}.
}
\details{
  Both functions are generic: you can write methods to handle specific
  classes of objects, see \link{InternalMethods}.

  The replacement form can be used to reset the length of a vector.  If
  a vector is shortened, extra values are discarded and when a vector is
  lengthened, it is padded out to its new length with \code{\link{NA}}s.
}
\seealso{\code{nchar} for counting the number of characters in
  character vectors.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
length(diag(4))# = 16 (4 x 4)
length(options())# 12 or more
length(y ~ x1 + x2 + x3)# 3
length(expression(x, {y <- x^2; y+2}, x^y)) # 3
}
\keyword{attribute}

\eof
\name{levels}
\alias{levels}
\alias{levels<-}
\alias{levels<-.default}
\alias{levels<-.factor}
\title{Levels Attributes}
\usage{
levels(x)
levels(x) <- value
}
\description{
  \code{levels} provides access to the levels attribute of a variable.
  The first form returns the value of the levels of its argument
  and the second sets the attribute.

  The assignment form (\code{"levels<-"}) of \code{levels} is a generic
  function and new methods can be written for it.
  The most important method is that for \code{\link{factor}}s:
}
\arguments{
  \item{x}{an object, for example a factor.}
  \item{value}{A valid value for \code{levels(x)}.
    For the default method, \code{NULL} or a character vector.  For the
    \code{factor} method, a vector of character strings with length at
    least the number of levels of \code{x}, or a named list specifying how to
    rename the levels.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{nlevels}}.
}
\examples{
## assign individual levels
x <- gl(2, 4, 8)
levels(x)[1] <- "low"
levels(x)[2] <- "high"
x

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

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

## same, using a named list
z <- gl(3, 2, 12)
levels(z) <- list(A=c(1,3), B=2)
z

## we can add levels this way:
f <- factor(c("a","b"))
levels(f) <- c("c", "a", "b")
f

f <- factor(c("a","b"))
levels(f) <- list(C="C", A="a", B="b")
f
}
\keyword{category}
\eof
\name{library}
\title{Loading and Listing of Packages}
\alias{library}
\alias{require}
\alias{R_LIBS}
\alias{.Autoloaded}
\alias{.First.lib}
\alias{.Last.lib}
\alias{.Library}
\alias{.find.package}
\alias{.packages}
\alias{.path.package}
\alias{.libPaths}
\alias{.noGenerics}
\alias{print.libraryIQR}
\alias{print.packageInfo}
\description{
  \code{library} and \code{require} load add-on packages.

  \code{.First.lib} is called when a package is loaded;
  \code{.Last.lib} is called when a package is detached.

  \code{.packages} returns information about package availability.

  \code{.path.package} returns information about where a package was
  loaded from.

  \code{.find.package} returns the directory paths of installed
  packages.
}
\usage{
library(package, help, pos = 2, lib.loc = NULL, character.only = FALSE,
        logical.return = FALSE, warn.conflicts = TRUE,
        keep.source = getOption("keep.source.pkgs"),
        verbose = getOption("verbose"), version)
require(package, quietly = FALSE, warn.conflicts = TRUE,
        keep.source = getOption("keep.source.pkgs"),
        character.only = FALSE, version, save = TRUE)

.First.lib(libname, pkgname)
.Last.lib(libpath)

.packages(all.available = FALSE, lib.loc = NULL)
.path.package(package = .packages(), quiet = FALSE)
.find.package(package, lib.loc = NULL, quiet = FALSE,
              verbose = getOption("verbose"))
.libPaths(new)

.Library
.Autoloaded
}
\arguments{
  \item{package, help}{the name of a package, given as a \link{name} or
    literal character string, or a character string, depending on
    whether \code{character.only} is \code{FALSE} (default) or
    \code{TRUE}).}
  \item{pos}{the position on the search list at which to attach the
    loaded package.  Note that \code{.First.lib} may attach other
    packages, and \code{pos} is computed \emph{after} \code{.First.lib}
    has been run.  Can also be the name of a position on the current
    search list as given by \code{\link{search}()}.}
  \item{lib.loc}{a character vector describing the location of \R
    library trees to search through, or \code{NULL}.  The default value
    of \code{NULL} corresponds to all libraries currently known.}
  \item{character.only}{a logical indicating whether \code{package} or
    \code{help} can be assumed to be character strings.}
  \item{version}{A character string denoting a version number of the
     package to be loaded.  If no version is given, a suitable default
     is chosen.}
  \item{logical.return}{logical.  If it is \code{TRUE},  \code{FALSE} or
    \code{TRUE} is returned to indicate success.}
  \item{warn.conflicts}{logical.  If \code{TRUE}, warnings are
    printed about \code{\link{conflicts}} from attaching the new
    package, unless that package contains an object \code{.conflicts.OK}.}
  \item{keep.source}{logical.  If \code{TRUE}, functions \dQuote{keep their
    source} including comments, see argument \code{keep.source} to
    \code{\link{options}}.}
  \item{verbose}{a logical.  If \code{TRUE}, additional diagnostics are
    printed.}
  \item{quietly}{a logical.  If \code{TRUE}, no message confirming
    package loading is printed.}
  \item{save}{logical or environment.  If \code{TRUE}, a call to
  \code{require} from the source for a package will save the name of
  the required package in the variable \code{".required"}, allowing
  function \code{\link{detach}} to warn if a required package is
  detached. See section \sQuote{Packages that require other packages} below.}
  \item{libname}{a character string giving the library directory where
    the package was found.}
  \item{pkgname}{a character string giving the name of the package.}
  \item{libpath}{a character string giving the complete path to the
    package.}
  \item{all.available}{logical; if \code{TRUE} return a character vector
    of all available packages in \code{lib.loc}.}
  \item{quiet}{logical.
    For \code{.path.package}, should this not give warnings or an error
    if the package(s) are not loaded?
    For \code{.find.package}, should this not give warnings or an error
    if the package(s) are not found?}
  \item{new}{a character vector with the locations of \R library trees.}
}
\details{
  \code{library(package)} and \code{require(package)} both load the
  package with name \code{package}.  \code{require} is designed for use
  inside other functions; it returns \code{FALSE} and gives a warning
  (rather than an error as \code{library()} does) if the package does
  not exist.  Both functions check and update the list of currently
  loaded packages and do not reload code that is already loaded.

  For large packages, setting \code{keep.source = FALSE} may save quite
  a bit of memory.

  If \code{library} is called with no \code{package} or \code{help}
  argument, it lists all available packages in the libraries specified
  by \code{lib.loc}, and returns the corresponding information in an
  object of class \code{"libraryIQR"}.  The structure of this class may
  change in future versions.  In earlier versions of R, only the names
  of all available packages were returned; use \code{.packages(all =
    TRUE)} for obtaining these.  Note that
  \code{\link[utils]{installed.packages}()} returns even more information.

  \code{library(help = somename)} computes basic information about the
  package \code{somename}, and returns this in an object of class
  \code{"packageInfo"}.  The structure of this class may change in
  future versions.  When used with the default value (\code{NULL}) for
  \code{lib.loc}, the loaded packages are searched before the libraries.

  \code{.First.lib} is called when a package is loaded by
  \code{library}.  It is called with two arguments, the name of the
  library directory where the package was found (i.e., the corresponding
  element of \code{lib.loc}), and the name of the package (in that
  order).  It is a good place to put calls to \code{\link{library.dynam}}
  which are needed when loading a package into this function (don't call
  \code{library.dynam} directly, as this will not work if the package
  is not installed in a \dQuote{standard} location).  \code{.First.lib}
  is invoked after the search path interrogated by \code{search()}
  has been updated, so
  \code{as.environment(match("package:name", search()))} will return the
  environment in which the package is stored.  If calling
  \code{.First.lib} gives an error the loading of the package is
  abandoned, and the package will be unavailable.  Similarly, if the
  option \code{".First.lib"} has a list element with the package's name,
  this element is called in the same manner as \code{.First.lib} when
  the package is loaded.  This mechanism allows the user to set package
  \dQuote{load hooks} in addition to startup code as provided by the package
  maintainers.

  \code{.Last.lib} is called when a package is detached.  Beware
  that it might be called if \code{.First.lib} has failed, so it
  should be written defensively. (It is called within \code{\link{try}},
  so errors will not stop the package being detached.)

  \code{.packages()} returns the \dQuote{base names} of the currently
  attached packages \emph{invisibly} whereas
  \code{.packages(all.available = TRUE)} gives (visibly) \emph{all}
  packages available in the library location path \code{lib.loc}.

  \code{.path.package} returns the paths from which the named packages
  were loaded, or if none were named, for all currently loaded packages.
  Unless \code{quiet = TRUE} it will warn if some of the packages named
  are not loaded, and given an error if none are.  This function is not
  meant to be called by users, and its interface might change in future
  versions.

  \code{.find.package} returns the paths to the locations where the
  given packages can be found.  If \code{lib.loc} is \code{NULL}, then
  then attached packages are searched before the libraries.  If a
  package is found more than once, the first match is used.  Unless
  \code{quiet = TRUE} a warning will be given about the named packages
  which are not found, and an error if none are.  If \code{verbose} is
  true, warnings about packages found more than once are given.  This
  function is not meant to be called by users, and its interface might
  change in future versions.

  \code{.Autoloaded} contains the \dQuote{base names} of the packages for
  which autoloading has been promised.

  \code{.Library} is a character string giving the location of the
  default library, the \file{library} subdirectory of \env{R\_HOME}.
  \code{.libPaths} is used for getting or setting the library trees that
  \R knows about (and hence uses when looking for packages).  If called
  with argument \code{new}, the library search path is set to
  the existing files in \code{unique(new, .Library)} and this is
  returned.  If given no argument, a character vector with the currently
  known library trees is returned.

#ifdef unix
  The library search path is initialized at startup from the environment
  variable \env{R\_LIBS} (which should be a colon-separated list of
  directories at which \R library trees are rooted) by calling
  \code{.libPaths} with the directories specified in \env{R\_LIBS}.
#endif
#ifdef windows
  The library search path is initialized at startup from the environment
  variable \env{R\_LIBS} (which should be a semicolon-separated list of
  directories at which \R library trees are rooted) by calling
  \code{.libPaths} with the directories specified in \env{R\_LIBS}.
#endif
}
\value{
  \code{library} returns the list of loaded (or available) packages
  (or \code{TRUE} if \code{logical.return} is \code{TRUE}).
  \code{require} returns a logical indicating whether the required
  package is available.
}
\section{Packages that require other packages}{The source code for a
  package that requires one or more other packages should have a call
  to \code{require}, preferably near the beginning of the source, and
  of course before any code that uses functions, classes or methods
  from the other package.  The default for argument \code{save} will
  save the names of all required packages in the environment of the
  new package.  The saved package names are used by
  \code{\link{detach}} when a package is detached to warn if other
  packages still require the detached package.  Also, if a package is
  installed with saved image (see \link[utils]{INSTALL}), the saved package
  names are used to require these packages when the new package is attached.}
\section{Formal methods}{
  \code{library} takes some further actions when package \pkg{methods}
  is attached (as it is by default).  Packages may define formal generic
  functions as well as re-defining functions in other packages (notably
  \pkg{base}) to be generic, and this information is cached whenever
  such a package is loaded after \pkg{methods} and re-defined functions
  are excluded from the list of conflicts.  The check requires looking
  for a pattern of objects; the pattern search may be avoided by
  defining an object \code{.noGenerics}
  (with any value) in the package.  Naturally, if the package
  \emph{does} have any such methods, this will prevent them from being used.
}
\note{
  \code{library} and \code{require} can only load an \emph{installed}
  package, and this is detected by having a \file{DESCRIPTION} file
  containing a \code{Built:} field.  Packages
  installed prior to 1.2.0 (released in December 2000) will need to be
  re-installed.

  Under Unix-alikes, the code checks that the package was installed
  under a similar operating system as given by \code{R.version$platform}
  (the canonical name of the platform under which R was compiled),
  provided it contains compiled code.  Packages which do not contain
  compiled code can be shared between Unix-alikes, but not to other OSes
  because of potential problems with line endings and OS-specific help
  files.

  \code{library} and \code{require} use the underlying file system
  services to locate the libraries, with the result that on
  case-sensitive file systems package names are case-sensitive
  (i.e., \code{library(foo)} is different from
  \code{library(Foo)}), but they are not distinguished on
  case-insensitive file systems such as MS Windows.  A warning
  is issued if the user specifies a name which isn't a perfect match
  to the package name, because future versions of \R will require
  exact matches.

}
\author{
  R core;
  Guido Masarotto for the \code{all.available=TRUE} part of
  \code{.packages}.
}
\seealso{
  \code{\link{attach}}, \code{\link{detach}}, \code{\link{search}},
  \code{\link{objects}}, \code{\link{autoload}},
  \code{\link{library.dynam}}, \code{\link{data}},
  \code{\link[utils]{install.packages}} and
  \code{\link[utils]{installed.packages}};
  \code{\link[utils]{INSTALL}}, \code{\link[utils]{REMOVE}}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
(.packages())               # maybe just "base"
.packages(all = TRUE)       # return all available as character vector
library()                   # list all available packages
library(lib = .Library)     # list all packages in the default library
library(help = eda)         # documentation on package 'eda'
library(eda)                # load package 'eda'
require(eda)                # the same
(.packages())               # "eda", too
detach("package:eda")

# if the package name is in a character vector, use
pkg <- "eda"
library(pkg, character.only = TRUE)
detach(pos = match(paste("package", pkg, sep=":"), search()))

require(pkg, character.only = TRUE)
detach(pos = match(paste("package", pkg, sep=":"), search()))

.path.package()
.Autoloaded                 # maybe "ctest"

.libPaths()                 # all library trees R knows about

require(nonexistent)        # FALSE
\dontrun{
## Suppose a package needs to call a shared library named 'fooEXT',
## where 'EXT' is the system-specific extension.  Then you should use
.First.lib <- function(lib, pkg) {
  library.dynam("foo", pkg, lib)
}

## if you want to mask as little as possible, use
library(mypkg, pos = "package:base")
}}
\keyword{data}
\eof
\name{library.dynam}
\alias{library.dynam}
\alias{library.dynam.unload}
\alias{.dynLibs}
\title{Loading Shared Libraries}
\description{
  Load the specified file of compiled code if it has not been loaded
  already, or unloads it.
}
\usage{
library.dynam(chname, package = .packages(), lib.loc = NULL,
              verbose = getOption("verbose"),
              file.ext = .Platform$dynlib.ext, \dots)
library.dynam.unload(chname, libpath,
              verbose = getOption("verbose"),
              file.ext = .Platform$dynlib.ext)
.dynLibs(new)
}
\arguments{
  \item{chname}{a character string naming a shared library to load.}
  \item{package}{a character vector with the names of packages to search
    through.}
  \item{lib.loc}{a character vector describing the location of \R
    library trees to search through, or \code{NULL}.  The default value
    of \code{NULL} corresponds to all libraries currently known.}
  \item{libpath}{the path to the loaded package whose shared library is
    to be unloaded.}
  \item{verbose}{a logical value indicating whether an announcement
    is printed on the console before loading the shared library.  The
    default value is taken from the verbose entry in the system
    options.}
  \item{file.ext}{the extension to append to the file name to specify
    the library to be loaded. This defaults to the appropriate value
    for the operating system.}
  \item{\dots}{additional arguments needed by some libraries that
    are passed to the call to \code{\link{dyn.load}} to control
    how the library is loaded.}
  \item{new}{a character vector of packages which have loaded shared
    libraries.}
}
\details{
  \code{library.dynam} is designed to be used inside a package rather
  than at the command line, and should really only be used inside
  \code{\link{.First.lib}} on \code{\link{.onLoad}}.  The
  system-specific extension for shared libraries
#ifdef unix
  (e.g., \file{.so} or \file{.sl} on Unix systems)
#endif
#ifdef windows
  (\file{.dll} on Windows)
#endif
  should not be added.

  \code{library.dynam.unload} is designed for use in \code{\link{.Last.lib}} or
  \code{\link{.onUnload}}.

  \code{.dynLibs} is used for getting or setting the packages that have
  loaded shared libraries (using \code{library.dynam}).  Versions of \R
  prior to 1.6.0 used an internal global variable \code{.Dyn.libs} for
  storing this information: this variable is now defunct.
}
\value{
  \code{library.dynam} returns a character vector with the names of
  packages which have used it in the current \R session to load shared
  libraries.  This vector is returned as \code{\link{invisible}}, unless
  the \code{chname} argument is missing.

  \code{library.dynam.unload} returns the updated character vector, invisibly.
}
\seealso{
  \code{\link{.First.lib}}, \code{\link{library}},
  \code{\link{dyn.load}}, \code{\link{.packages}},
  \code{\link{.libPaths}}

#ifdef unix
  \code{\link[utils]{SHLIB}} for how to create suitable shared libraries.
#endif
#ifdef windows
  \code{\link[utils]{SHLIB}} for how to create suitable DLLs.
#endif
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
library.dynam() # which packages have been "dynamically loaded"
}
\keyword{data}
\eof
\name{license}
\title{The R License Terms}
\alias{license}
\alias{licence}
\description{
  The license terms under which \R is distributed.
}
\usage{
license()
licence()
}
\details{
  \R is distributed under the terms of the GNU GENERAL PUBLIC LICENSE
  Version 2, June 1991.  A copy of this license is in
  \file{\$R\_HOME/COPYING}.

  A small number of files (the API header files and import library)
  are distributed under the LESSER GNU GENERAL PUBLIC LICENSE version
  2.1. A copy of this license is in \file{\$R\_HOME/COPYING.LIB}.
}
\keyword{misc}
\eof
\name{list}
\title{Lists -- Generic and Dotted Pairs}
\usage{
list(\dots)
pairlist(\dots)

as.list(x, \dots)
%as.list.default(x, \dots)
as.pairlist(x)
as.list.environment(x, all.names=FALSE, \dots)

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.list.environment}
\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.}
  \item{all.names}{a logical indicating whether to copy all values in as.list.environment}
}
\details{
  Most lists in \R internally are \emph{Generic
    Vectors}, whereas traditional \emph{dotted pair} lists (as in LISP)
  are still available.

  The arguments to \code{list} or \code{pairlist} are of the form
  \code{value} or \code{tag=value}.
  The functions return a list composed of its arguments
  with each value either tagged or untagged,
  depending on how the argument was specified.

  \code{alist} is like \code{list}, except in the handling of tagged
  arguments with no value. These are handled as if they described
  function arguments with no default (cf. \code{\link{formals}}), whereas
  \code{list} simply ignores them.

  \code{as.list} attempts to coerce its argument to list type.
  For functions, this returns the concatenation of the list of formals
  arguments and the function body. For expressions, the list of
  constituent calls is returned.

  \code{is.list} returns \code{TRUE} iff its argument
  is a \code{list} \emph{or} a \code{pairlist} of \code{length}\eqn{> 0},
  whereas \code{is.pairlist} only returns \code{TRUE} in the latter case.

  \code{is.list} and \code{is.pairlist} are generic: you can write
  methods to handle specific classes of objects, see \link{InternalMethods}.

  \code{as.list.environment} copies the named values from an environment to a list. The 
  user can request that all named objects are copied (normally names that begin with a dot 
  are not). The output is not sorted and no parent environments are searched.

  An empty pairlist, \code{pairlist()} is the same as \code{NULL}.  This
  is different from \code{list()}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
\code{\link{vector}(., mode="list")}, \code{\link{c}}, for concatenation;
\code{\link{formals}}.
}
\examples{
data(cars)
# create a plotting structure
pts <- list(x=cars[,1], y=cars[,2])
plot(pts)

# Argument lists
f <- function()x
# Note the specification of a "..." argument:
formals(f) <- al <- alist(x=, y=2, \dots=)
f
al

##environment->list coercion

e1 <- new.env()
e1$a <- 10
e1$b <- 20
as.list(e1)
}
\keyword{list}
\keyword{manip}
\eof
\name{list.files}
\alias{list.files}
\alias{dir}
\title{List the Files in a Directory/Folder}
\usage{
list.files(path = ".", pattern = NULL, all.files = FALSE,
           full.names = FALSE, recursive = FALSE)
       dir(path = ".", pattern = NULL, all.files = FALSE,
           full.names = FALSE, recursive = FALSE)
}
\arguments{
  \item{path}{a character vector of full path names; the default
    corresponds to the working directory \code{\link{getwd}()}.}
  \item{pattern}{an optional \link{regular expression}.  Only file names
    which match the regular expression will be returned.}
  \item{all.files}{a logical value. If \code{FALSE}, only the
    names of visible files are returned.  If \code{TRUE},
    all file names will be returned.}
  \item{full.names}{a logical value.  If \code{TRUE}, the directory
    path is prepended to the file names.  If \code{FALSE}, only
    the file names are returned.}
  \item{recursive}{logical. Should the listing recurse into directories?}
}
\description{
  This function produces a list containing the names of files
  in the named directory. \code{dir} is an alias.
}
\value{
  A character vector containing the names of the files in the
  specified directories, or \code{""} if there were no files. If a
  path does not exist or is not a directory or is unreadable it
  is skipped, with a warning.

  The files are sorted in alphabetical order, on the full path
  if \code{full.names = TRUE}.
}
\author{Ross Ihaka, Brian Ripley}
\note{
  File naming conventions are very platform dependent.

  \code{recursive = TRUE} is not supported on all platforms, and may be
  ignored, with a warning.
}
\seealso{\code{\link{file.info}}, \code{\link{file.access}}
  and \code{\link{files}} for many more file handling functions and 
  \code{\link{file.choose}} 
#ifdef windows
and \code{\link[utils]{choose.files}}
#endif
for interactive selection.}
\examples{
list.files(R.home())
## Only files starting with a-l or r (*including* uppercase):
dir("../..", pattern = "^[a-lr]",full.names=TRUE)
}
\keyword{file}
\eof
\name{load}
\alias{load}
\alias{loadURL}
\title{Reload Saved Datasets}
\description{
  Reload the datasets written to a file with the function \code{save}.
}
\usage{
load(file, envir = parent.frame())
loadURL(url, envir = parent.frame(), quiet = TRUE, \dots)
}
\arguments{
  \item{file}{a connection or a character string giving the name of the
    file to load.}
  \item{envir}{the environment where the data should be loaded.}
  \item{url}{a character string naming a URL.}
  \item{quiet, \dots}{additional arguments to
    \code{\link[utils]{download.file}}.}
}
\details{
  \code{load} can load \R objects saved in the current or any earlier
  format.  It can read a compressed file (see \code{\link{save}})
  directly from a file or from a suitable connection.

  \code{loadURL} is a convenience wrapper which downloads a file, loads
  it and deletes the downloaded copy.
}
\value{
  A character vector of the names of objects created, invisibly.
}
\seealso{
  \code{\link{save}}, \code{\link[utils]{download.file}}.
}
\examples{
## save all data
save(list = ls(), file= "all.Rdata")

## restore the saved values to the current environment
load("all.Rdata")

## restore the saved values to the user's workspace
load("all.Rdata", .GlobalEnv)

\dontrun{## This example may not still be available
## print the value to see what objects were created.
print(loadURL("http://hesweb1.med.virginia.edu/biostat/s/data/sav/kprats.sav"))}
}
\keyword{file}
\eof
\name{localeconv}
\alias{localeconv}
\alias{Sys.localeconv}
\title{Find Details of the Numerical Representations in the Current Locale}
\description{
  Get details of the numerical representations in the current locale.
}
\usage{
Sys.localeconv()
}
\value{
  A character vector with 18 named components. See your ISO C
  documentation for details of the meaning.

  It is possible to compile \R without support for locales, in which
  case the value will be \code{NULL}.
}
\seealso{
  \code{\link{Sys.setlocale}} for ways to set locales: by default \R uses the
  C clocal for \code{"LC_NUMERIC"} and \code{"LC_MONETARY"}.
}
\examples{
Sys.localeconv()
## The results in the default C locale are
##    decimal_point     thousands_sep          grouping   int_curr_symbol 
##              "."                ""                ""                "" 
##  currency_symbol mon_decimal_point mon_thousands_sep      mon_grouping 
##               ""                ""                ""                "" 
##    positive_sign     negative_sign   int_frac_digits       frac_digits 
##               ""                ""             "127"             "127" 
##    p_cs_precedes    p_sep_by_space     n_cs_precedes    n_sep_by_space 
##            "127"             "127"             "127"             "127" 
##      p_sign_posn       n_sign_posn 
##            "127"             "127"

## Now try your default locale (which might be "C").
\dontrun{old <- Sys.getlocale()
Sys.setlocale(locale = "")
Sys.localeconv()
Sys.setlocale(locale = old)}

\dontrun{read.table("foo", dec=Sys.localeconv()["decimal_point"])}
}
\keyword{utilities}
\eof
\name{locales}
\alias{locales}
\alias{Sys.getlocale}
\alias{Sys.setlocale}
\title{Query or Set Aspects of the Locale}
\description{
  Get details of or set aspects of the locale for the \R process.
}
\usage{
Sys.getlocale(category = "LC_ALL")
Sys.setlocale(category = "LC_ALL", locale = "")
}
\arguments{
  \item{category}{character string. Must be one of \code{"LC_ALL"},
    \code{"LC_COLLATE"}, \code{"LC_CTYPE"}, \code{"LC_MONETARY"},
    \code{"LC_NUMERIC"} or \code{"LC_TIME"}.}
  \item{locale}{character string. A valid locale name on the system in
    use. Normally \code{""} (the default) will pick up the default
    locale for the system.}
}
\details{
  The locale describes aspects of the internationalization of a program.
  Initially most aspects of the locale of \R are set to \code{"C"} (which
  is the default for the C language and reflects North-American usage).
  \R does set \code{"LC_CTYPE"} and \code{"LC_COLLATE"}, which allow the
  use of a different character set (typically ISO Latin 1) and alphabetic
  comparisons in that character set (including the use of
  \code{\link{sort}}) and \code{"LC_TIME"} may affect
  the behaviour of \code{\link{as.POSIXlt}} and \code{\link{strptime}}
  and functions which use them (but not \code{\link{date}}).

  \R can be built with no support for locales, but it is normally
  available on Unix and is available on Windows.

  Some systems will have other locale categories, but the six described
  here are those specified by POSIX.
}
\value{
  A character string of length one describing the locale in use (after
  setting for \code{Sys.setlocale}), or an empty character string if the
  locale is invalid (with a warning) or \code{NULL} if locale
  information is unavailable.

  For \code{category = "LC_ALL"} the details of the string are
  system-specific: it might be a single locale or a set of locales
  separated by \code{"/"} (Solaris) or \code{";"} (Windows).  For
  portability, it is best to query categories individually.  It is
  guaranteed that the result of \code{foo <- Sys.getlocale()} can be
  used in \code{Sys.setlocale("LC_ALL", locale = foo)} on the same
  machine.
}
\section{Warning}{
  Setting \code{"LC_NUMERIC"} can produce output that \R cannot then
  read by \code{scan} or \code{read.table} with their default arguments,
  which are not locale-specific.
}
\seealso{
  \code{\link{strptime}} for uses of \code{category = "LC_TIME"}.
  \code{\link{Sys.localeconv}} for details of numerical representations.
}
\examples{
Sys.getlocale()
Sys.getlocale("LC_TIME")
\dontrun{
Sys.setlocale("LC_TIME", "de")     # Solaris: details are OS-dependent
Sys.setlocale("LC_TIME", "German") # Windows}

Sys.setlocale("LC_COLLATE", "C")  # turn off locale-specific sorting
}
\keyword{utilities}
\eof
\name{logical}
\alias{logical}
\alias{as.logical}
\alias{as.logical.default}
\alias{is.logical}
\alias{TRUE}
\alias{FALSE}
\alias{T}
\alias{F}
\title{Logical Vectors}
\description{
  Create or test for objects of type \code{"logical"}, and the basic
  logical \dQuote{constants}.
}
\usage{
TRUE
FALSE
T; F

logical(length = 0)
as.logical(x, \dots)
is.logical(x)
}
\details{
  \code{TRUE} and \code{FALSE} are part of the \R language, where
  \code{T} and \code{F} are global variables set to these.
  All four are \code{logical(1)} vectors.

  \code{is.logical} is generic: you can write methods to handle
  specific classes of objects, see \link{InternalMethods}.
}
\arguments{
  \item{length}{desired length.}
  \item{x}{object to be coerced or tested.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\value{
  \code{logical} creates a logical vector of the specified length.
  Each element of the vector is equal to \code{FALSE}.

  \code{as.logical} attempts to coerce its argument to be of logical
  type.  For \code{\link{factor}}s, this uses the \code{\link{levels}}
  (labels) and not the \code{\link{codes}}.  Like
  \code{\link{as.vector}} it strips attributes including names.

  \code{is.logical} returns \code{TRUE} or \code{FALSE} depending on
  whether its argument is of logical type or not.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\keyword{classes}
\keyword{logic}
\eof
\name{longley}
\docType{data}
\alias{longley}
\title{Longley's Economic Regression Data}
\description{
  A macroeconomic data set which provides a well-known example for a
  highly collinear regression.
}
\usage{data(longley)}
\format{
  A data frame with 7 economical variables, observed yearly from 1947 to
  1962 (\eqn{n=16}).
  \describe{
    \item{GNP.deflator:}{GNP implicit price deflator (\eqn{1954=100})}
    \item{GNP:}{Gross National Product.}
    \item{Unemployed:}{number of unemployed.}
    \item{Armed.Forces:}{number of people in the armed forces.}
    \item{Population:}{\sQuote{noninstitutionalized} population
      \eqn{\ge} 14 years of age.}
    \item{Year:}{the year (time).}
    \item{Employed:}{number of people employed.}
  }

  The regression \code{lm(Employed ~ .)} is known to be highly
  collinear.
}
\source{
  J. W. Longley (1967)
  An appraisal of least-squares programs from the point of view of the
  user.
  \emph{Journal of the American Statistical Association}, \bold{62},
  819--841.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
## give the data set in the form it is used in S-PLUS:
data(longley)
longley.x <- data.matrix(longley[, 1:6])
longley.y <- longley[, "Employed"]
pairs(longley, main = "longley data")
summary(fm1 <- lm(Employed ~ ., data = longley))
opar <- par(mfrow = c(2, 2), oma = c(0, 0, 1.1, 0),
            mar = c(4.1, 4.1, 2.1, 1.1))
plot(fm1)
par(opar)
}
\keyword{datasets}
\eof
\name{lower.tri}
\alias{lower.tri}
\alias{upper.tri}
\title{Lower and Upper Triangular Part of a Matrix}
\description{
  Returns a matrix of logicals the same size of a given matrix with
  entries \code{TRUE} in the lower or upper triangle.
}
\usage{
lower.tri(x, diag = FALSE)
upper.tri(x, diag = FALSE)
}
\arguments{
  \item{x}{a matrix.}
  \item{diag}{logical. Should the diagonal be included?}
}
\seealso{
  \code{\link{diag}},
  \code{\link{matrix}}.
}
\examples{
(m2 <- matrix(1:20, 4, 5))
lower.tri(m2)
m2[lower.tri(m2)] <- NA
m2
}
\keyword{array}
\eof
\name{ls}
\alias{ls}
\alias{objects}
\title{List Objects}
\usage{
ls(name, pos = -1, envir = as.environment(pos),
   all.names = FALSE, pattern)
objects(name, pos= -1, envir = as.environment(pos),
        all.names = FALSE, pattern)
}
\arguments{
  \item{name}{which environment to use in listing the available objects.
    Defaults to the \emph{current}
    environment.  Although called \code{name} for back compatibility, in
    fact this argument can specify the environment in any form; see the
    details section.}
  \item{pos}{An alternative  argument to \code{name} for specifying the
    environment as a position in the search list.  Mostly there for
    back compatibility.}
  \item{envir}{an alternative  argument to \code{name} for specifying the
    environment evaluation environment. Mostly there for back compatibility.}
  \item{all.names}{a logical value.  If \code{TRUE}, all
    object names are returned.  If \code{FALSE}, names which begin with a
    \samp{.} are omitted.}
  \item{pattern}{an optional \link{regular expression}. Only names
    matching \code{pattern} are returned.}
}
\details{
  The \code{name} argument can specify the  environment from which
  object names are taken in one of several forms:
  as an integer (the position in the \code{\link{search}} list); as
  the character string name of an element in the search list; or as an
  explicit \code{\link{environment}} (including using
  \code{\link{sys.frame}} to access the currently active function calls).
  By default, the environment of the call to \code{ls} or \code{objects}
  is used. The \code{pos} and \code{envir} arguments are an alternative
  way to specify an environment, but are primarily there for back
  compatibility.
}  
 \description{
   \code{ls} and \code{objects} return a vector of character strings
   giving the names of the objects in the specified environment.
   When invoked with no argument at the top level prompt,
   \code{ls} shows what data sets and functions a user has defined.
   When invoked with no argument inside a function,
   \code{ls} returns the names of the functions local variables.
   This is useful in conjunction with \code{browser}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link[utils]{apropos}} (or \code{\link[utils]{find}})
  for finding objects in the whole search path;
  \code{\link{grep}} for more details on \dQuote{regular expressions};
  \code{\link[base]{class}},
  \code{\link[utils]{methods}}, etc., for
  object-oriented programming.
}
\examples{
.Ob <- 1
ls(pat="O")
ls(pat="O", all = TRUE)    # also shows ".[foo]"

# shows an empty list because inside myfunc no variables are defined
myfunc <- function() {ls()}
myfunc()

# define a local variable inside myfunc
myfunc <- function() {y <- 1; ls()}
myfunc()                # shows "y"
}
\keyword{environment}
\eof
\name{make.names}
\alias{make.names}
\title{Make Syntactically Valid Names}
\description{
  Make syntactically valid names out of character vectors.
}
\usage{
make.names(names, unique = FALSE)
}
\arguments{
 \item{names}{character vector to be coerced to syntactically valid
   names. This is coerced to character if necessary.}
 \item{unique}{logical; if \code{TRUE}, the resulting elements are
     unique.  This may be desired for, e.g., column names.}
}
\value{
  A character vector of same length as \code{names} with each changed to
  a syntactically valid name.
}
\details{
  A syntactically valid name consists of letters, numbers and the dot or
  underline characters and starts with a letter or the dot not followed
  by a number.  Names such as \code{".2way"} are not valid, and neither
  are the reserved words.

  The character \code{"X"} is prepended if necessary.
  All invalid characters are translated to \code{"."}.  A missing value
  is translated to \code{"NA"}.  Names which match \R keywords have a dot
  appended to them.  Duplicated values are altered by
  \code{\link{make.unique}}.
}
\seealso{
  \code{\link{make.unique}},
  \code{\link{names}},
  \code{\link{character}},
  \code{\link{data.frame}}.
}
\examples{
make.names(c("a and b", "a_and_b"), unique=TRUE)
# "a.and.b"  "a.and.b.1"

data(state)
state.name[make.names(state.name) != state.name] # those 10 with a space
}
\keyword{character}
\eof
\name{make.unique}
\alias{make.unique}
\title{Make Character Strings Unique}
\description{
  Makes the elements of a character vector unique by
  appending sequence numbers to duplicates.
}
\usage{
make.unique(names, sep = ".")
}
\arguments{
  \item{names}{a character vector}
  \item{sep}{a character string used to separate a duplicate name from
    its sequence number.}
}
\value{
  A character vector of same length as \code{names} with duplicates changed.
}
\details{
  The algorithm used by \code{make.unique} has the property that
  \code{make.unique(c(A, B)) == make.unique(c(make.unique(A), B))}.

  In other words, you can append one string at a time to a vector,
  making it unique each time, and get the same result as applying
  \code{make.unique} to all of the strings at once.
    
  If character vector \code{A} is already unique, then
  \code{make.unique(c(A, B))} preserves \code{A}.
}
\author{Thomas P Minka}
\seealso{
  \code{\link{make.names}}
}
\examples{
make.unique(c("a", "a", "a"))
make.unique(c(make.unique(c("a", "a")), "a"))

make.unique(c("a", "a", "a.2", "a"))
make.unique(c(make.unique(c("a", "a")), "a.2", "a"))

rbind(data.frame(x=1), data.frame(x=2), data.frame(x=3))
rbind(rbind(data.frame(x=1), data.frame(x=2)), data.frame(x=3))
}
\keyword{character}
\eof
\name{manglePackageName}
\alias{manglePackageName}
\title{Mangle the Package Name }
\description{
 This function takes the package name and the package version number and
 pastes them together with a separating underscore.
}
\usage{
manglePackageName(pkgName, pkgVersion)
}
\arguments{
  \item{pkgName}{The package name, as a character string. }
  \item{pkgVersion}{The package version, as a character string. }
}
\value{
  A character string with the two inputs pasted together.
}

\examples{
  manglePackageName("foo", "1.2.3")
}
\keyword{utilities }
\eof
\name{mapply}
\alias{mapply}
\title{Apply a function to multiple list or vector arguments }
\description{
  A multivariate version of \code{\link{sapply}}.
  \code{mapply} applies \code{FUN} to the first elements of each \dots
  argument, the second elements, the third elements, and so on.
  Arguments are recycled if necessary. 
}
\usage{
mapply(FUN, \dots, MoreArgs = NULL, SIMPLIFY = TRUE, USE.NAMES = TRUE)
}
\arguments{
  \item{FUN}{Function to apply }
  \item{\dots}{Arguments to vectorise over (list or vector) }
  \item{MoreArgs}{A list of other arguments to \code{FUN} }
  \item{SIMPLIFY}{Attempt to reduce the result to a vector or matrix? }
  \item{USE.NAMES}{If the first \dots argument is character and the
    result doesn't already have names, use it as the names}
}
\value{
  A list, vector, or matrix.
}

\seealso{\code{\link{sapply}}}, \code{\link{outer}} }
\examples{
 mapply(rep, 1:4, 4:1)

 mapply(rep, times=1:4, x=4:1)

 mapply(rep, times=1:4, MoreArgs=list(x=42))

}
\keyword{manip }
\keyword{utilities}
\eof
\name{margin.table}
\alias{margin.table}
\title{Compute table margin}
\description{
  For a contingency table in array form, compute the sum of table
  entries for a given index.
}
\usage{
margin.table(x, margin=NULL)
}
\arguments{
  \item{x}{an array}
  \item{margin}{index number (1 for rows, etc.) }
}
\details{
  This is really just \code{apply(x, margin, sum)} packaged up for
  newbies, except that if \code{margin} has length zero you get
  \code{sum(x)}.
}
\value{
  The relevant marginal table.  The class of \code{x} is copied to the
  output table, except in the summation case.
}
\author{Peter Dalgaard}
\examples{
m<-matrix(1:4,2)
margin.table(m,1)
margin.table(m,2)
}
\keyword{array}
\eof
\name{mat.or.vec}
\alias{mat.or.vec}
\title{Create a Matrix or a Vector}
\usage{
mat.or.vec(nr, nc)
}
\arguments{
  \item{nr, nc}{numbers of rows and columns.}
}
\description{
  \code{mat.or.vec} creates an \code{nr} by \code{nc} zero matrix if
  \code{nc} is greater than 1, and a zero vector of length \code{nr} if
  \code{nc} equals 1.
}
\examples{
mat.or.vec(3, 1)
mat.or.vec(3, 2)
}
\keyword{array}
\eof
\name{match}
\alias{match}
\alias{\%in\%}
\title{Value Matching}
\description{
  \code{match} returns a vector of the positions of (first) matches of
  its first argument in its second.

  \code{\%in\%} is a more intuitive interface as a binary operator,
  which returns a logical vector indicating if there is a match or not
  for its left operand.
}
\usage{
match(x, table, nomatch = NA, incomparables = FALSE)

x \%in\% table
}
\arguments{
  \item{x}{the values to be matched.}
  \item{table}{the values to be matched against.}
  \item{nomatch}{the value to be returned in the case when no match is
    found.  Note that it is coerced to \code{integer}.}
  \item{incomparables}{a vector of values that cannot be matched.  Any
    value in \code{x} matching a value in this vector is assigned the
    \code{nomatch} value.  Currently, \code{FALSE} is the only possible
    value, meaning that all values can be matched.}
}
\value{
  In both cases, a vector of the same length as \code{x}.

  \code{match}: An integer vector giving the position in \code{table} of
  the first match if there is a match, otherwise \code{nomatch}.

  If \code{x[i]} is found to equal \code{table[j]}
  then the value returned in the \code{i}-th position of the return value is
  \code{j}, for the smallest possible \code{j}.  If no match is found,
  the value is \code{nomatch}.

  \code{\%in\%}: A logical vector, indicating if a match was located for
  each element of \code{x}.
}
\details{
  \code{\%in\%} is currently defined as \cr
  \code{"\%in\%" <- function(x, table) match(x, table, nomatch = 0) > 0}

  Factors are converted to character vectors, and then \code{x} and
  \code{table} are coerced to a common type (the later of the two types
  in R's ordering, logical < integer < numeric < complex < character)
  before matching.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{pmatch}} and \code{\link{charmatch}} for (\emph{partial})
  string matching, \code{\link{match.arg}}, etc for function argument
  matching.

  \code{\link{is.element}} for an S-compatible equivalent of \code{\%in\%}.
}
\examples{
## The intersection of two sets :
intersect <- function(x, y) y[match(x, y, nomatch = 0)]
intersect(1:10,7:20)

1:10 \%in\% c(1,3,5,9)
sstr <- c("c","ab","B","bba","c","@","bla","a","Ba","\%")
sstr[sstr \%in\% c(letters,LETTERS)]

"\%w/o\%" <- function(x,y) x[!x \%in\% y] #--  x without y
(1:10) \%w/o\% c(3,7,12)
}
\keyword{manip}
\keyword{logic}
\eof
\name{match.arg}
\title{Argument Verification Using Partial Matching}
\usage{
match.arg(arg, choices)
}
\alias{match.arg}
\arguments{
  \item{arg}{a character string}
  \item{choices}{a character vector of candidate values}
}
\description{
  \code{match.arg} matches \code{arg} against a table of candidate
  values as specified by \code{choices}.
}
\details{
  In the one-argument form \code{match.arg(arg)}, the choices are
  obtained from a default setting for the formal argument \code{arg} of
  the function from which \code{match.arg} was called.

  Matching is done using \code{\link{pmatch}}, so \code{arg} may be
  abbreviated.
}
\value{
  The unabbreviated version of the unique partial match if there is one;
  otherwise, an error is signalled.
}
\seealso{
  \code{\link{pmatch}},
  \code{\link{match.fun}},
  \code{\link{match.call}}.
}
\examples{
require(stats)
## 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
try(center(x, "m"))  # Error
}
}
\keyword{programming}
\eof
\name{match.call}
\title{Argument Matching}
\usage{
match.call(definition = NULL, call = sys.call(sys.parent()),
           expand.dots = TRUE)
}
\alias{match.call}
\arguments{
  \item{definition}{a function, by default the function from which
    \code{match.call} is called.}
  \item{call}{an unevaluated call to the function specified by
    \code{definition}, as generated by \code{\link{call}}.}
  \item{expand.dots}{logical. Should arguments matching \code{\dots}
    in the call be included or left as a \code{\dots} argument?}
}
\description{
  \code{match.call} returns a call in which all of the arguments are
  specified by their names.  The most common use is to get the call of
  the current function, with all arguments named.
}
\value{
  An object of class \code{call}.
}
\references{
  Chambers, J. M. (1998)
  \emph{Programming with Data. A Guide to the S Language}.
  Springer.
}
\seealso{
  \code{\link{call}}, \code{\link{pmatch}}, \code{\link{match.arg}},
  \code{\link{match.fun}}.
}
\examples{
match.call(get, call("get", "abc", i = FALSE, p = 3))
## -> get(x = "abc", pos = 3, inherits = FALSE)
fun <- function(x, lower = 0, upper = 1) {
  structure((x - lower) / (upper - lower), CALL = match.call())
}
fun(4 * atan(1), u = pi)
}
\keyword{programming}
\eof
\name{match.fun}
\alias{match.fun}
\title{Function Verification for ``Function Variables''}
\description{
  When called inside functions that take a function as argument, extract
  the desired function object while avoiding undesired matching to
  objects of other types.
}
\usage{
match.fun(FUN, descend = TRUE)
}
\arguments{
 \item{FUN}{item to match as function.}
 \item{descend}{logical; control whether to search past non-function
     objects.}
}
\value{
  A function matching \code{FUN} or an error is generated.
}
\details{
  \code{match.fun} is not intended to be used at the top level since it
  will perform matching in the \emph{parent} of the caller.

  If \code{FUN} is a function, it is returned.  If it is a symbol or a
  character vector of length one, it will be looked up using \code{get}
  in the environment of the parent of the caller.  If it is of any other
  mode, it is attempted first to get the argument to the caller as a
  symbol (using \code{substitute} twice), and if that fails, an error is
  declared.

  If \code{descend = TRUE}, \code{match.fun} will look past non-function
  objects with the given name; otherwise if \code{FUN} points to a
  non-function object then an error is generated.

  This is now used in base functions such as \code{\link{apply}},
  \code{\link{lapply}}, \code{\link{outer}}, and \code{\link{sweep}}.
}
\author{
  Peter Dalgaard and Robert Gentleman, based on an earlier version
  by Jonathan Rougier.
}
\section{Bugs}{
  The \code{descend} argument is a bit of misnomer and probably not
  actually needed by anything.  It may go away in the future.

  It is impossible to fully foolproof this.  If one \code{attach}es a
  list or data frame containing a character object with the same name
  of a system function, it will be used.
}
\seealso{
  \code{\link{match.arg}}, \code{\link{get}}
}
\examples{
# Same as get("*"):
match.fun("*")
# Overwrite outer with a vector
outer <- 1:5
\dontrun{
match.fun(outer, descend = FALSE) #-> Error:  not a function
}
match.fun(outer) # finds it anyway
is.function(match.fun("outer")) # as well
}
\keyword{programming}
\eof
\name{matmult}
\alias{\%*\%}
\alias{matmult}
\title{Matrix Multiplication}
\description{
  Multiplies two matrices, if they are conformable.
  If one argument is a vector, it will be coerced to either a row or
  column matrix to make the two arguments conformable.
  If both are vectors it will return the inner product.
}
\usage{
a \%*\% b
}
\arguments{
  \item{a, b}{numeric or complex matrices or vectors.}
}
\value{
  The matrix product.  Use \code{\link{drop}} to get rid of dimensions
  which have only one level.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{matrix}},
  \code{\link{Arithmetic}},
  \code{\link{diag}}.
}
\examples{
x <- 1:4
(z <- x \%*\% x)    # scalar ("inner") product (1 x 1 matrix)
drop(z)             # as scalar

y <- diag(x)
z <- matrix(1:12, ncol = 3, nrow = 4)
y \%*\% z
y \%*\% x
x \%*\% z
}
\keyword{array}
\keyword{arith}
\eof
\name{matrix}
\alias{matrix}
\alias{as.matrix}
\alias{as.matrix.default}
\alias{as.matrix.data.frame}
\alias{is.matrix}
\title{Matrices}
\description{
  \code{matrix} creates a matrix from the given set of values.

  \code{as.matrix} attempts to turn its argument into a matrix.

  \code{is.matrix} tests if its argument is a (strict) matrix.
  It is generic: you can write methods to handle
  specific classes of objects, see \link{InternalMethods}.
}
\usage{
matrix(data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL)
as.matrix(x)
is.matrix(x)
}
\arguments{
  \item{data}{an optional data vector.}
  \item{nrow}{the desired number of rows}
  \item{ncol}{the desired number of columns}
  \item{byrow}{logical. If \code{FALSE}
    (the default) the matrix is filled by columns, otherwise the matrix is
    filled by rows.}
  \item{dimnames}{A \code{\link{dimnames}} attribute for the matrix: a
    \code{list} of length 2.}
  \item{x}{an \R object.}
}
\details{
  If either of \code{nrow} or \code{ncol} is not given, an attempt is
  made to infer it from the length of \code{data} and the other
  parameter.

  If there are too few elements in \code{data} to fill the array,
  then the elements in \code{data} are recycled.  If \code{data} has
  length zero, \code{NA} of an appropriate type is used for atomic
  vectors and \code{NULL} for lists.

  \code{is.matrix} returns \code{TRUE} if \code{x} is a matrix (i.e., it
  is \emph{not} a \code{\link{data.frame}} and has a \code{\link{dim}}
  attribute of length 2) and \code{FALSE} otherwise.

  \code{as.matrix} is a generic function. The method for data frames
  will convert any non-numeric/complex column into a character
  vector using \code{\link{format}} and so return a character matrix,
  except that all-logical data frames will be coerced to a logical matrix.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{data.matrix}}, which attempts to convert to a numeric matrix.
}
\examples{
is.matrix(as.matrix(1:10))
data(warpbreaks)
!is.matrix(warpbreaks)# data.frame, NOT matrix!
warpbreaks[1:10,]
as.matrix(warpbreaks[1:10,]) #using as.matrix.data.frame(.) method
}
\keyword{array}
\keyword{algebra}
\eof
\name{maxCol}
\alias{max.col}
\title{Find Maximum Position in Matrix}
\description{
  Find the maximum position for each row of a matrix, breaking ties at random.
}
\usage{
max.col(m)
}
\arguments{
  \item{m}{numerical matrix}
}
\value{index of a maximal value for each row, an integer vector of
  length \code{nrow(m)}.
}
\details{
  Ties are broken at random.  The determination of \dQuote{tie} assumes that
  the entries are probabilities: there is a relative tolerance of
  \eqn{10^{-5}}{1e-5}, relative to the largest entry in the row.
}
\references{
  Venables, W. N. and Ripley, B. D. (2002)
  \emph{Modern Applied Statistics with S.}
  New York: Springer (4th ed).
}
\seealso{\code{\link{which.max}} for vectors.}
\examples{
data(swiss)
table(mc <- max.col(swiss))# mostly "1" and "5", 5 x "2" and once "4"
swiss[unique(print(mr <- max.col(t(swiss)))) , ] # 3 33 45 45 33 6
}
\keyword{utilities}
\keyword{array}
\eof
\name{mean}
\title{Arithmetic Mean}
\usage{
mean(x, \dots)

\method{mean}{default}(x, trim = 0, na.rm = FALSE, \dots)
}
\alias{mean}
\alias{mean.default}
\alias{mean.data.frame}
\arguments{
  \item{x}{An \R object.  Currently there are methods for numeric data
    frames, numeric vectors and dates.  A complex vector is allowed for
    \code{trim = 0}, only.}
  \item{trim}{the fraction (0 to 0.5) of observations to be
    trimmed from each end of \code{x} before the mean is computed.}
  \item{na.rm}{a logical value indicating whether \code{NA}
    values should be stripped before the computation proceeds.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\description{
  Generic function for the (trimmed) arithmetic mean.
}
\value{
  For a data frame, a named vector with the appropriate method being
  applied column by column.
  
  If \code{trim} is zero (the default),
  the arithmetic mean of the values in \code{x} is computed.

  If \code{trim} is non-zero, a symmetrically trimmed mean is computed
  with a fraction of \code{trim} observations deleted from each end
  before the mean is computed.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link[stats]{weighted.mean}}, \code{\link{mean.POSIXct}}
}
\examples{
x <- c(0:10, 50)
xm <- mean(x)
c(xm, mean(x, trim = 0.10))

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

\eof
\name{memory.profile}
\alias{memory.profile}
\title{Profile the Usage of Cons Cells}
\description{
    Lists the usage of the cons cells by \code{SEXPREC} type.
}
\usage{
memory.profile()
}
\details{
    The current types and their uses are listed in the include file
    \file{Rinternals.h}. There will be blanks in the list corresponding
    to types that are no longer in use (types 11 and 12 at the time of
    writing). Also \code{FUNSXP} is not included.
}
\value{
  A vector of counts, named by the types.
}

\seealso{\code{\link{gc}} for the overall usage of cons cells.}

\examples{
memory.profile()
}
\keyword{utilities}
\eof
\name{merge}
\alias{merge}
\alias{merge.default}
\alias{merge.data.frame}
\title{Merge Two Data Frames}
\description{
  Merge two data frames by common columns or row names, or do other
  versions of database \dQuote{join} operations.
}
\usage{
merge(x, y, \dots)

\method{merge}{default}(x, y, \dots)

\method{merge}{data.frame}(x, y, by = intersect(names(x), names(y)),
      by.x = by, by.y = by, all = FALSE, all.x = all, all.y = all,
      sort = TRUE, suffixes = c(".x",".y"), \dots)
}
\arguments{
  \item{x, y}{data frames, or objects to be coerced to one}
  \item{by, by.x, by.y}{specifications of the common columns. See Details.}
  \item{all}{logical; \code{all=L} is shorthand for \code{all.x=L} and
    \code{all.y=L}.}
  \item{all.x}{logical; if \code{TRUE}, then extra rows will be added to
    the output, one for each row in \code{x} that has no matching row in
    \code{y}.  These rows will have \code{NA}s in those columns that are
    usually filled with values from \code{y}.  The default is
    \code{FALSE}, so that only rows with data from both \code{x} and
    \code{y} are included in the output.}
  \item{all.y}{logical; analogous to \code{all.x} above.}
  \item{sort}{logical.  Should the results be sorted on the \code{by}
    columns?}
  \item{suffixes}{character(2) specifying the suffixes to be used for
    making non-\code{by} \code{names()} unique.}
  \item{\dots}{arguments to be passed to or from methods.}
}
\details{
  By default the data frames are merged on the columns with names they
  both have, but separate specifications of the columns can be given by
  \code{by.x} and \code{by.y}.  Columns can be specified by name, number
  or by a logical vector: the name \code{"row.names"} or the number
  \code{0} specifies the row names.  The rows in the two data frames
  that match on the specified columns are extracted, and joined
  together.  If there is more than one match, all possible matches
  contribute one row each.\cr
  If the \code{by.*} vectors are of length 0, the result, \code{r}, is the
  \dQuote{Cartesian product} of \code{x} and \code{y}, i.e.,
  \code{dim(r) = c(nrow(x)*nrow, ncol(x) + ncol(y))}.

  If \code{all.x} is true, all the non matching cases of \code{x} are
  appended to the result as well, with \code{NA} filled in the
  corresponding columns of \code{y};  analogously for \code{all.y}.

  If the remaining columns in the data frames have any common names,
  these have \code{suffixes} (\code{".x"} and \code{".y"} by default)
  appended to make the names of the result unique.
}
\value{
  A data frame.  The rows are by default lexicographically sorted on the
  common columns, but are otherwise in the order in which they occurred
  in \code{y}.  The columns are the common columns followed by the
  remaining columns in \code{x} and then those in \code{y}.  If the
  matching involved row names, an extra column \code{Row.names} is added
  at the left, and in all cases the result has no special row names.
}
\seealso{
  \code{\link{data.frame}},
  \code{\link{by}},
  \code{\link{cbind}}
}

\examples{
authors <- data.frame(
    surname = c("Tukey", "Venables", "Tierney", "Ripley", "McNeil"),
    nationality = c("US", "Australia", "US", "UK", "Australia"),
    deceased = c("yes", rep("no", 4)))
books <- data.frame(
    name = c("Tukey", "Venables", "Tierney",
             "Ripley", "Ripley", "McNeil", "R Core"),
    title = c("Exploratory Data Analysis",
              "Modern Applied Statistics ...",
              "LISP-STAT",
              "Spatial Statistics", "Stochastic Simulation",
              "Interactive Data Analysis",
              "An Introduction to R"),
    other.author = c(NA, "Ripley", NA, NA, NA, NA,
                     "Venables & Smith"))

(m1 <- merge(authors, books, by.x = "surname", by.y = "name"))
(m2 <- merge(books, authors, by.x = "name", by.y = "surname"))
stopifnot(as.character(m1[,1]) == as.character(m2[,1]),
          all.equal(m1[, -1], m2[, -1][ names(m1)[-1] ]),
          dim(merge(m1, m2, by = integer(0))) == c(36, 10))

## "R core" is missing from authors and appears only here :
merge(authors, books, by.x = "surname", by.y = "name", all = TRUE)
}
\keyword{array}
\keyword{manip}
\eof
\name{missing}
\alias{missing}
\title{Does a Formal Argument have a Value?}
\usage{
missing(x)
}
\description{
\code{missing} can be used to test whether a value was specified
as an argument to a function.
}
\arguments{
  \item{x}{a formal argument.}
}
\details{
  \code{missing(x)} is only reliable if \code{x} has not been altered
  since entering the function: in particular it will \emph{always}
  be false after \code{x <- match.arg(x)}. 
  
  The example shows how a plotting function
  can be written to work with either a pair of vectors
  giving x and y coordinates of points to be plotted
  or a single vector giving y values to be plotted
  against their indexes.

  Currently \code{missing} can only be used in the immediate body of
  the function that defines the argument, not in the body of a nested
  function or a \code{local} call.  This may change in the future.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Chambers, J. M. (1998)
  \emph{Programming with Data. A Guide to the S Language}.
  Springer.
}
\seealso{
  \code{\link{substitute}} for argument expression;
  \code{\link{NA}} for \dQuote{missing values} in data.
}
\examples{
myplot <- function(x,y) {
                if(missing(y)) {
                        y <- x
                        x <- 1:length(y)
                }
                plot(x,y)
        }
}
\keyword{programming}
\eof
\name{mode}
\alias{mode}
\alias{mode<-}
\alias{storage.mode}
\alias{storage.mode<-}
\title{The (Storage) Mode of an Object}
\description{
  Get or set the type or storage mode of an object.
}
\usage{
mode(x)
mode(x) <- value
storage.mode(x)
storage.mode(x) <- value
}
\arguments{
  \item{x}{any \R object.}
  \item{value}{a character string giving the desired (storage) mode of
    the object.}
}
\details{
  Both \code{mode} and \code{storage.mode} return a character string
  giving the (storage) mode of the object --- often the same --- both
  relying on the output of \code{\link{typeof}(x)}, see the example
  below.

  The two assignment versions are currently identical.  Both
  \code{mode(x) <- newmode} and \code{storage.mode(x) <- newmode} change
  the \code{mode} or \code{storage.mode} of object \code{x} to
  \code{newmode}.

  As storage mode \code{"single"} is only a pseudo-mode in \R, it will
  not be reported by \code{mode} or \code{storage.mode}: use
  \code{attr(object, "Csingle")} to examine this. However, the
  assignment versions can be used to set the mode to \code{"single"},
  which sets the real mode to \code{"double"} and the \code{"Csingle"}
  attribute to \code{TRUE}. Setting any other mode will remove this
  attribute.

  Note (in the examples below) that some \code{\link{call}}s have mode
  \code{"("} which is S compatible.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{typeof}} for the R-internal \dQuote{mode},
  \code{\link{attributes}}.
}
\examples{
sapply(options(),mode)

cex3 <- c("NULL","1","1:1","1i","list(1)","data.frame(x=1)", "pairlist(pi)",
  "c", "lm", "formals(lm)[[1]]",  "formals(lm)[[2]]",
  "y~x","expression((1))[[1]]", "(y~x)[[1]]", "expression(x <- pi)[[1]][[1]]")
lex3 <- sapply(cex3, function(x) eval(parse(text=x)))
mex3 <- t(sapply(lex3, function(x) c(typeof(x), storage.mode(x), mode(x))))
dimnames(mex3) <- list(cex3, c("typeof(.)","storage.mode(.)","mode(.)"))
mex3

## This also makes a local copy of 'pi':
storage.mode(pi) <- "complex"
storage.mode(pi)
rm(pi)
}
\keyword{attribute}
\eof
\name{morley}
\docType{data}
\alias{morley}
\title{Michaelson-Morley Speed of Light Data}
\description{
  The classical data of Michaelson and Morley on the speed of light.
  The data consists of five experiments, each consisting of 20
  consecutive \sQuote{runs}.  The response is the speed of light
  measurement, suitably coded.
}
\usage{data(morley)}
\format{
  A data frame contains the following components:
  \describe{
    \item{\code{Expt}}{The experiment number, from 1 to 5.}
    \item{\code{Run}}{The run number within each experiment.}
    \item{\code{Speed}}{Speed-of-light measurement.}
  }
}
\details{
  The data is here viewed as a randomized block experiment with
  \sQuote{experiment} and \sQuote{run} as the factors.  \sQuote{run} may
  also be considered a quantitative variate to account for linear (or
  polynomial) changes in the measurement over the course of a single
  experiment.
}
\source{
  A. J. Weekes (1986)
  \emph{A Genstat Primer}.
  London: Edward Arnold.
}
\examples{
data(morley)
morley$Expt <- factor(morley$Expt)
morley$Run <- factor(morley$Run)
attach(morley)
plot(Expt, Speed, main = "Speed of Light Data", xlab = "Experiment No.")
fm <- aov(Speed ~ Run + Expt, data = morley)
summary(fm)
fm0 <- update(fm, . ~ . - Run)
anova(fm0, fm)
detach(morley)
}
\keyword{datasets}
\eof
\name{mtcars}
\docType{data}
\alias{mtcars}
\title{Motor Trend Car Road Tests}
\description{
  The data was extracted from the 1974 \emph{Motor Trend} US magazine,
  and comprises fuel consumption and 10 aspects of
  automobile design and performance for 32 automobiles (1973--74
  models).
}
\usage{data(mtcars)}
\format{
  A data frame with 32 observations on 11 variables.
  \tabular{rll}{
    [, 1] \tab mpg  \tab Miles/(US) gallon \cr
    [, 2] \tab cyl  \tab Number of cylinders \cr
    [, 3] \tab disp \tab Displacement (cu.in.) \cr
    [, 4] \tab hp   \tab Gross horsepower \cr
    [, 5] \tab drat \tab Rear axle ratio \cr
    [, 6] \tab wt   \tab Weight (lb/1000) \cr
    [, 7] \tab qsec \tab 1/4 mile time \cr
    [, 8] \tab vs   \tab V/S \cr
    [, 9] \tab am   \tab Transmission (0 = automatic, 1 = manual) \cr
    [,10] \tab gear \tab Number of forward gears \cr
    [,11] \tab carb \tab Number of carburetors
  }
}
\source{
  Henderson and Velleman (1981),
  Building multiple regression models interactively.
  \emph{Biometrics}, \bold{37}, 391--411.
}
\examples{
data(mtcars)
pairs(mtcars, main = "mtcars data")
coplot(mpg ~ disp | as.factor(cyl), data = mtcars,
       panel = panel.smooth, rows = 1)
}
\keyword{datasets}
\eof
\name{name}
\alias{name}
\alias{is.symbol}
\alias{as.symbol}
\alias{as.name}
\alias{is.name}
\title{Variable Names or Symbols, respectively}
\description{
  \code{as.symbol} coerces its argument to be a \emph{symbol}, or
  equivalently, a \emph{name}.  The argument must be of mode
  \code{"character"}.  \code{as.name} is an alias for \code{as.symbol}.

  \code{is.symbol} (and \code{is.name} equivalently) returns \code{TRUE}
  or \code{FALSE} depending on whether its argument is a symbol (i.e.,
  name) or not.
}
\usage{
as.symbol(x)
is.symbol(y)

as.name(x)
is.name(y)
}
\arguments{
  \item{x, y}{objects to be coerced or tested.} 
}
\note{
  The term \dQuote{symbol} is from the LISP background of \R, whereas
  \dQuote{name} has been the standard S term for this.
}
\details{
  \code{is.symbol} is generic: you can write methods to handle
  specific classes of objects, see \link{InternalMethods}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{call}}, \code{\link{is.language}}.
  For the internal object mode, \code{\link{typeof}}.
}
\examples{
an <- as.name("arrg")
is.name(an) # TRUE
mode(an)   # name
typeof(an) # symbol
}
\keyword{programming}
\keyword{attribute}
\eof
\name{names}
\alias{names}
\alias{names.default}
\alias{names<-}
\alias{names<-.default}
\title{The Names Attribute of an Object}
\description{
  Functions to get or set the names of an object.
}
\usage{
names(x)
names(x) <- value
}
\arguments{
  \item{x}{an \R object.}
  \item{value}{a character vector of up to the same length as \code{x}, or
    \code{NULL}.} 
}
\value{
  For \code{names}, \code{NULL} or a character vector of the same length
  as \code{x}.

  For \code{names<-}, the updated object.  (Note that the value of
  \code{names(x) <- value} is that of the assignment, \code{value}, not
  the return value from the left-hand side.)
}
\details{
  \code{names} is a generic accessor function, and \code{names<-} is a
  generic replacement function.  The default methods get and set
  the \code{"names"} attribute of a vector or list.

  If \code{value} is shorter than \code{x}, it is extended by character
  \code{NA}s to the length of \code{x}.
  
  It is possible to update just part of the names attribute via the
  general rules: see the examples.  This works because the expression
  there is evaluated as \code{z <- "names<-"(z, "[<-"(names(z), 3, "c2"))}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
data(islands)
# print the names attribute of the islands data set
names(islands)

# remove the names attribute
names(islands) <- NULL

z <- list(a=1, b="c", c=1:3)
names(z)
# change just the name of the third element.
names(z)[3] <- "c2"
z


z <- 1:3
names(z)
## assign just one name
names(z)[2] <- "b"
z
}
\keyword{attribute}
\eof
\name{nargs}
\title{The Number of Arguments to a Function}
\usage{nargs()}
\alias{nargs}
\description{
  When used inside a function body, \code{nargs} returns the number of
  arguments supplied to that function, \emph{including} positional
  arguments left blank. 
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{\code{\link{args}}, \code{\link{formals}} and \code{\link{sys.call}}.}
\examples{
tst <- function(a, b = 3, ...) {nargs()}
tst() # 0
tst(clicketyclack) # 1 (even non-existing)
tst(c1, a2, rr3) # 3

foo <- function(x, y, z, w) {
   cat("call was", deparse(match.call()), "\n")
   nargs()
}
foo()    # 0
foo(,,3) # 3
foo(z=3) # 1, even though this is the same call

nargs()# not really meaningful
}
\keyword{programming}
\eof
\name{nchar}
\title{Count the Number of Characters}
\usage{nchar(x)}
\alias{nchar}
\description{
  \code{nchar} takes a character vector as an argument and
  returns a vector whose elements contain the number of characters in
  the corresponding element of \code{x}.
}
\arguments{
  \item{x}{character vector, or a vector to be coerced to a character
    vector.} 
}
\details{
  The internal equivalent of \code{\link{as.character}} is performed on
  \code{x}. If you want to operate
  on non-vector objects passing them through \code{\link{deparse}} first
  will be required.
}
\value{
  The number of characters as the string will be printed (integer
  \code{2} for a missing string).
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link[graphics]{strwidth}} giving width of strings for plotting;
  \code{\link{paste}}, \code{\link{substr}}, \code{\link{strsplit}}
}
\examples{
x <- c("asfef","qwerty","yuiop[","b","stuff.blah.yech")
nchar(x)
# 5  6  6  1 15

nchar(deparse(mean))
# 23  1 16 45 11 64  2 17 50 43  2 17  1
}
\keyword{character}
\eof
\name{nextn}
\title{Highly Composite Numbers}
\usage{
nextn(n, factors=c(2,3,5))
}
\alias{nextn}
\arguments{
\item{n}{an integer.}
\item{factors}{a vector of positive integer factors.}
}
\description{
\code{nextn} returns the smallest integer,
greater than or equal to \code{n}, which can be obtained
as a product of powers of the values contained in \code{factors}.
\code{nextn} is intended to be used to find a suitable length
to zero-pad the argument of \code{fft} to
so that the transform is computed quickly.
The default value for \code{factors} ensures this.
}
\seealso{
\code{\link{convolve}}, \code{\link{fft}}.
}
\examples{
nextn(1001) # 1024
table(sapply(599:630, nextn))
}
\keyword{math}

\eof
\name{nlevels}
\title{The Number of Levels of a Factor}
\usage{
nlevels(x)
}
\alias{nlevels}
\description{
  Return the number of levels which its argument has.
}
\arguments{
  \item{x}{an object, usually a factor.} 
}
\details{
  If the argument is not a \code{\link{factor}}, \code{NA} is returned.

  The actual factor levels (if they exist) can be obtained
  with the \code{\link{levels}} function.
}
\examples{
nlevels(gl(3,7)) # = 3
}
\keyword{category}
\eof
\name{noquote}
\alias{noquote}
\alias{print.noquote}
\alias{as.matrix.noquote}
\alias{c.noquote}
\alias{[.noquote}
\title{Class for ``no quote'' Printing of Character Strings}
\description{
  Print character strings without quotes.
}
\usage{
noquote(obj)
\method{print}{noquote}(x, \dots)
\method{c}{noquote}(\dots, recursive = FALSE)
}
\arguments{
  \item{obj}{any \R object, typically a vector of
    \code{\link{character}} strings.}
  \item{x}{an object of class \code{"noquote"}.}
  \item{\dots}{further options passed to next methods, such as \code{\link{print}}.}
  \item{recursive}{for compatibility with the generic \code{\link{c}} function.}
}
\details{
  \code{noquote} returns its argument as an object of class
  \code{"noquote"}.  There is a method for \code{c()} and subscript
  method (\code{"[.noquote"}) which ensures that the class is not lost
  by subsetting.  The print method (\code{print.noquote}) prints
  character strings \emph{without} quotes (\code{"\dots"}).

  These functions exist both as utilities and as an example of using (S3)
  \code{\link[base]{class}} and object orientation.
}
\author{Martin Maechler \email{maechler@stat.math.ethz.ch}}
\seealso{
  \code{\link[utils]{methods}},
  \code{\link[base]{class}},
  \code{\link{print}}.
}
\examples{
letters
nql <- noquote(letters)
nql
nql[1:4] <- "oh"
nql[1:12]

cmp.logical <- function(log.v)
{
  ## Purpose: compact printing of logicals
  log.v <- as.logical(log.v)
  noquote(if(length(log.v)==0)"()" else c(".","|")[1+log.v])
}
cmp.logical(runif(20) > 0.8)
}
\keyword{print}
\keyword{methods}
\keyword{utilities}
\eof
\name{NotYet}
\title{Not Yet Implemented Functions and Unused Arguments}
\alias{NotYetImplemented}
\alias{.NotYetImplemented}
\alias{NotYetUsed}
\alias{.NotYetUsed}
\description{
  In order to pinpoint missing functionality, the \R core team uses
  these functions for missing \R functions and not yet used arguments of
  existing \R functions (which are typically there for compatibility
  purposes).

  You are very welcome to contribute your code \dots
}
\usage{
.NotYetImplemented()
.NotYetUsed(arg, error = TRUE)
}
\arguments{
  \item{arg}{an argument of a function that is not yet used.}
  \item{error}{a logical.  If \code{TRUE}, an error is signalled; if
    \code{FALSE}; only a warning is given.}
}
%------ PLEASE: put \alias{.} here for  EACH !
%done\alias{symbols}
%done\alias{plot.lm}
%NOT done, but in ./plot.lm.Rd on purpose:  \alias{plot.mlm}
\seealso{the contrary, \code{\link{Deprecated}} and
  \code{\link{Defunct}} for outdated code.}
\examples{
require(graphics)
require(stats)
plot.mlm         # to see how the "NotYetImplemented"
                 # reference is made automagically
try(plot.mlm())

barplot(1:5, inside = TRUE) # 'inside' is not yet used
}
\keyword{documentation}
\keyword{utilities}
\eof
\name{nrow}
\title{The Number of Rows/Columns of an Array}
\usage{
nrow(x)
ncol(x)
NCOL(x)
NROW(x)
}
\alias{nrow}
\alias{NROW}
\alias{ncol}
\alias{NCOL}
\arguments{
  \item{x}{a vector, array or data frame}
}
\description{
  \code{nrow} and \code{ncol} return the number of rows or columns
  present in \code{x}.
  \code{NCOL} and \code{NROW} do the same treating a vector as
  1-column matrix.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole (\code{ncol} and \code{nrow}.)
}
\seealso{
  \code{\link{dim}} which returns \emph{all} dimensions;
  \code{\link{array}}, \code{\link{matrix}}.
}
\value{an \code{\link{integer}} of length 1 or \code{\link{NULL}}.}
\examples{
ma <- matrix(1:12, 3, 4)
nrow(ma)   # 3
ncol(ma)   # 4

ncol(array(1:24, dim = 2:4)) # 3, the second dimension
NCOL(1:12) # 1
NROW(1:12) # 12
}
\keyword{array}
\eof
\name{ns-alt}
\title{Experimental Alternative Name Specification Support}
\alias{.Export}
\alias{.Import}
\alias{.ImportFrom}
\alias{.S3method}
\description{
  Alternative interface for specifying a name space within the code of a
  package.
}
\usage{
.Export(\dots)
.Import(\dots)
.ImportFrom(name, \dots)
.S3method(generic, class, method)
}
\arguments{
  \item{\dots}{name or literal character string arguments.}
  \item{name}{name or literal character string.}
  \item{generic}{name or literal character string.}
  \item{class}{name or literal character string.}
  \item{method}{optional character or function argument.}
}
\details{
  As an experimental alternative to using a \file{NAMESPACE} file it is
  possible to add a name space to a package by adding a
  \code{Namespace: <package_name>} entry to the \file{DESCRIPTION}
  file and placing directives to specify imports and exports directly in
  package code.  These directives should be viewed as declarations, not
  as function calls.   Except to the optional method argument to
  \code{.S3method} arguments are not evaluated.  These directives should
  only be used at top level of package code except as noted below.

  \code{.Export} is used to declare exports.  Its arguments should be
  literal names or character strings.  \code{.Export} should only be
  used at package top level.

  \code{.Import} is used to declare the import of entire name spaces.
  Its arguments should be literal names or character strings.
  \code{.ImportFrom} is used to declare the import of selected
  variables from a single name space.  The first argument is a literal
  name or character string identifying the source name space; the
  remaining arguments are literal names or character strings identifying
  the variables to import.  As an experimental feature both
  \code{.Import} and \code{.ImportFrom} can be used to import
  variables into a local environment.  The drawback of allowing this
  is that dependencies cannot be determined easily at package load
  time, and as a result this feature may need to be dropped.

  \code{.S3method} is used to declare a method for S3-style
  \code{UseMethod} dispatch.  This is needed since methods in packages
  that are imported but not on the search path might not be visible to
  the standard dispatch mechanism at a call site.  The first argument
  is the name of the generic, the second specifies the class.  The third
  argument is optional and defaults to the usual concatenation of
  generic and class separated by a period.  If supplied, the third
  argument should evaluate to a character string or a function.  If the
  third argument is omitted or a character string is supplied, then a
  function by that name must be defined.  If a function is supplied,
  it is used as the method.  When the method is specified as a name,
  explicitly or implicitly, the function lookup is handled lazily;
  this allows the definition to occur after the \code{.S3method}
  declaration and also integrates with possible data base storage of
  package code.
}
\examples{
\dontrun{
## code for package/name space 'foo'
x <- 1
f <- function(y) c(x,y)
print.foo <- function(x, ...) cat("<a foo>\n")
.Export(f)
S3method(print,foo)

## code for package/name space 'bar'
.Import(foo)
c <- function(...) sum(...)
g <- function(y) f(c(y, 7))
h <- function(y) y+9
.Export(g, h)
}
}
\keyword{internal}
\author{Luke Tierney}
\eof
\name{ns-dblcolon}
\title{Double Colon and Triple Colon Operators}
\alias{::}
\alias{:::}
\description{
  Accessing exported and internal variables in a name space.
}
\usage{
pkg::name
pkg:::name
}
\arguments{
  \item{pkg}{package name symbol or literal character string.}
  \item{name}{variable name symbol or literal character string.}
}
\details{
  The expression \code{pkg::name} returns the value of the exported
  variable \code{name} in package \code{pkg} if the package has a name
  space.  The expression \code{pkg:::name} returns the value of the
  internal variable \code{name} in package \code{pkg} if the package has
  a name space.  The package will be loaded if it was not loaded already
  before the call.  Assignment into name spaces is not supported.
}
\examples{
base::log
base::"+"
}
\keyword{programming}
\eof
\name{ns-hooks}
\alias{.onLoad}
\alias{.onUnload}
\alias{.onAttach}
\title{Hooks for Name Space events}
\description{
  Packages with name spaces can supply functions to be called when
  loaded, attached or unloaded.
}

\usage{
.onLoad(libname, pkgname)
.onAttach(libname, pkgname)
.onUnload(libpath)
}
\arguments{
  \item{libname}{a character string giving the library directory where
    the package defining the namespace was found.}
  \item{pkgname}{a character string giving the name of the name space.}
  \item{libpath}{a character string giving the complete path to the package.}
}
\details{
  These functions apply only to packages with name spaces.

  After loading, \code{\link{loadNamespace}} looks for a hook function named
  \code{.onLoad} and runs it before sealing the namespace and processing
  exports.

  If a name space is unloaded (via \code{\link{unloadNamespace}}),
  a hook function \code{.onUnload} is run before final unloading.
  
  Note that the code in \code{.onLoad} and \code{.onUnload} is run
  without the package being on the search path, but (unless circumvented)
  lexical scope will make objects in the namespace and its imports
  visible. (Do not use the double colon operator in \code{.onLoad} as
  exports have not been processed at the point it is run.)

  When the package is attached (via \code{\link{library}}), the hook
  function \code{.onAttach} is called after the exported functions are
  attached.  This is less likely to be useful than \code{.onLoad}, which
  should be seen as the analogue of \code{\link{.First.lib}} (which is only
  used for packages without a name space).

  \code{.onLoad}, \code{.onUnload} and \code{.onAttach} are looked for
  as internal variables in the name space and should not be exported.
  
  If a function \code{\link{.Last.lib}} is visible in the package, it
  will be called when the package is detached: this does need to be exported.

  Anything needed for the functioning of the name space should be
  handled at load/unload times by the \code{.onLoad} and
  \code{.onUnload} hooks.  For example, shared libraries can be loaded
  (unless done by a \code{useDynib} directive in the \code{NAMESPACE}
  file) and initialized in \code{.onLoad} and unloaded in
  \code{.onUnload}.  Use \code{.onAttach} only for actions that are
  needed only when the package becomes visible to the user, for example
  a start-up message.
}
\seealso{
  \code{\link{setHook}} shows how users can set hooks on the same events.
}
\keyword{utilities}
\eof
\name{ns-internals}
\title{Name Space Internals}

\alias{asNamespace}
\alias{getNamespaceInfo}
\alias{importIntoEnv}
\alias{isBaseNamespace}
\alias{isNamespace}
\alias{namespaceExport}
\alias{namespaceImport}
\alias{namespaceImportClasses}
\alias{namespaceImportFrom}
\alias{namespaceImportMethods}
\alias{packageHasNamespace}
\alias{parseNamespaceFile}
\alias{registerS3method}
\alias{setNamespaceInfo}
\alias{registerS3methods}
\alias{.__S3MethodsTable__.}
\alias{.mergeExportMethods}
\alias{.knownS3Generics}
\usage{
asNamespace(ns, base.OK = TRUE)
getNamespaceInfo(ns, which)
importIntoEnv(impenv, impnames, expenv, expnames)
isBaseNamespace(ns)
namespaceExport(ns, vars)
namespaceImport(self, \dots)
namespaceImportFrom(self, ns, vars)
namespaceImportClasses(self, ns, vars)
namespaceImportMethods(self, ns, vars)
packageHasNamespace(package, package.lib)
parseNamespaceFile(package, package.lib, mustExist = TRUE)
registerS3method(genname, class, method, envir = parent.frame())
registerS3methods(info, package, env)
setNamespaceInfo(ns, which, val)
.mergeExportMethods(new, ns)
.knownS3Generics
}

\arguments{
  \item{ns}{string or name space environment.}
  \item{base.OK}{logical.}
  \item{impenv}{environment.}
  \item{expenv}{name space environment.}
  \item{vars}{character vector.}
  \item{self}{name space environment.}
  \item{package}{string naming the package/name space to load.}
  \item{package.lib}{character vector specifying library.}
  \item{mustExist}{logical.}
  \item{genname}{character.}
  \item{class}{character.}
  \item{envir, env}{environment.}
  \item{info}{a 3-column character matrix.}
  \item{which}{character.}
  \item{val}{any object.}
  \item{\dots}{character arguments.}
}
\description{
  Internal name space support functions.  Not intended to be called directly.
}
\details{
  \code{packageHasNamespace} does not indicate if the package has a
  namespace, rather if it has a \file{NAMESPACE} file, which \code{base}
  does not.  But then you are not intended to be using it \dots.
}

\keyword{internal}
\author{Luke Tierney}
\eof
\name{ns-lowlev}
\title{Low Level Name Space Support Functions}

\alias{attachNamespace}
\alias{loadNamespace}
\alias{loadedNamespaces}
\alias{unloadNamespace}
\alias{loadingNamespaceInfo}
\alias{saveNamespaceImage}

\usage{
attachNamespace(ns, pos = 2)
loadNamespace(package, lib.loc = NULL,
              keep.source = getOption("keep.source.pkgs"),
              partial = FALSE, declarativeOnly = FALSE)
loadedNamespaces()
unloadNamespace(ns)
loadingNamespaceInfo()
saveNamespaceImage(package, rdafile, lib.loc = NULL,
                   keep.source = getOption("keep.source.pkgs"),
                   compress = TRUE)
}
\arguments{
  \item{ns}{string or namespace object.}
  \item{pos}{integer specifying position to attach.}
  \item{package}{string naming the package/name space to load.}
  \item{lib.loc}{character vector specifying library search path.}
  \item{keep.source}{logical specifying whether to retain source.}
  \item{partial}{logical; if true, stop just after loading code.}
  \item{declarativeOnly}{logical; disables \code{.Import}, etc, if true.}
  \item{compress}{option passed to \code{\link{save}}.}
}
\description{
  Low level name space support functions.
}
\details{
  The functions \code{loadNamespace} and \code{attachNamespace} are
  usually called implicitly when \code{library} is used to load a name
  space and any imports needed.  However it may be useful to call
  these functions directly at times.

  \code{loadNamespace} loads the specified name space and registers it in
  an internal data base.  A request to load a name space that is already
  loaded has no effect.  The arguments have the same meaning as the
  corresponding arguments to \code{library}.  After loading,
  \code{loadNamespace} looks for a hook function named
  \code{\link{.onLoad}} as an internal variable in the name space (it
  should not be exported). This function is called with the same arguments
  as \code{.First.lib}.  Partial loading is used to support installation with
  the \option{--save} option.

  \code{loadNamespace} does not attach the name space it loads to the
  search path.  \code{attachNamespace} can be used to attach a frame
  containing the exported values of a name space to the search path.
  The hook function \code{\link{.onAttach}} is run after the name space
  exports are attached.

  \code{loadedNamespaces} returns a character vector of the names of
  the loaded name spaces.

  \code{unloadNamespace} can be used to force
  a name space to be unloaded.  An error is signaled if the name space
  is imported by other loaded name spaces.  If defined, a hook
  function \code{\code{.onUnload}} is run
  before removing the name space from the internal registry.
  \code{unloadNamespace} will first \code{\link{detach}} a package of
  the same name if one is on the path, thereby running a
  \code{.Last.lib} function in the package if one is exported.

  \code{loadingNamespaceInfo} returns a list of the arguments that
  would be passed to \code{.onLoad} when a name space is being loaded.
  An error is signaled of a name space is not currently being loaded.

  \code{saveNamespaceImage} is used to save name space images for
  packages installed with \option{--save}.
}
\keyword{internal}
\author{Luke Tierney}
\eof
\name{ns-reflect.Rd}
\title{Name Space Reflection Support}

\alias{getExportedValue}
\alias{getNamespace}
\alias{getNamespaceExports}
\alias{getNamespaceImports}
\alias{getNamespaceName}
\alias{getNamespaceUsers}
\alias{getNamespaceVersion}

\usage{
getExportedValue(ns, name)
getNamespace(name)
getNamespaceExports(ns)
getNamespaceImports(ns)
getNamespaceName(ns)
getNamespaceUsers(ns)
getNamespaceVersion(ns)
}
\arguments{
  \item{ns}{string or name space object.}
  \item{name}{string or name.}
}
\description{
  Functions to support reflection on name space objects.
}
\details{
  \code{getExportedValue} returns the value of the exported variable
  \code{name} in name space \code{ns}.

  \code{getNamespace} returns the environment representing the name
  space \code{name}.  The name space is loaded if necessary.

  \code{getNamespaceExports} returns a character vector of the names
  exported by \code{ns}.

  \code{getNamespaceImports} returns a representation of the imports
  used by name space \code{ns}.  This representation is experimental
  and subject to change.

  \code{getNamespaceName} and \code{getNamespaceVersion} return the name
  and version of the name space \code{ns}.

  \code{getNamespaceUsers} returns a character vector of the names of
  the name spaces that import name space \code{ns}.
}
\keyword{internal}
\author{Luke Tierney}
\eof
\name{ns-topenv}
\title{Top Level Environment}
\alias{topenv}
\description{
  Finding the top level environment.
}
\usage{
topenv(envir = parent.frame(), matchThisEnv = getOption("topLevelEnvironment"))
}
\arguments{
  \item{envir}{environment.}

  \item{matchThisEnv}{return this environment, if it matches before
      any other criterion is satisfied.  The default, the option
      \dQuote{topLevelEnvironment}, is set by \code{\link{sys.source}},
      which treats a specific environment as the top level environment.
      Supplying the argument as \code{NULL} means it will never match.}
}
\details{
  \code{topenv} returns the first top level environment found when
  searching \code{envir} and its parent environments.  An environment is
  considered top level if it is the internal environment of a name space,
  a package environment in the search path, or \code{.GlobalEnv}.
}
\examples{
topenv(.GlobalEnv)
topenv(new.env())
}
\keyword{programming}
\eof
\name{numeric}
\title{Numeric Vectors}
\alias{numeric}
\alias{as.numeric}
\alias{is.numeric}
\usage{
numeric(length = 0)
as.numeric(x, \dots)
is.numeric(x)
}
\arguments{
  \item{length}{desired length.}
  \item{x}{object to be coerced or tested.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\description{
  \code{numeric} creates a real vector of the specified length.  The
  elements of the vector are all equal to \code{0}.

  \code{as.numeric} attempts to coerce its argument to numeric type
  (either integer or real).

  \code{is.numeric} returns \code{TRUE} if its argument is of type real
  or type integer and \code{FALSE} otherwise.
}
\details{
  \code{is.numeric} is  generic: you can write methods to handle
  specific classes of objects, see \link{InternalMethods}.

  Note that factors are false for \code{is.numeric} but true for
  \code{\link{is.integer}}.
}

\note{
  \emph{\R has no single precision data type.  All real numbers are
    stored in double precision format}. While \code{as.numeric} is a
  generic function, user methods must be written for \code{as.double},
  which it calls

  \code{as.numeric} for factors yields the codes underlying the factor
    levels, not the numeric representation of the labels.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
as.numeric(c("-.1"," 2.7 ","B")) # (-0.1, 2.7, NA)  +  warning
as.numeric(factor(5:10))
}
\keyword{classes}
\keyword{attribute}
\eof
\name{octmode}
\alias{format.octmode}
\alias{print.octmode}
\alias{as.character.octmode}
\title{Display Numbers in Octal}
\description{
  Convert or print integers in octal format, with as many digits as are
  needed to display the largest, using leading zeroes as necessary.
}
\usage{
\method{as.character}{octmode}(x, \dots)
\method{format}{octmode}(x, \dots)
\method{print}{octmode}(x, \dots)
}
\arguments{
  \item{x}{An object inheriting from class \code{"octmode"}.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\details{
  Class \code{"octmode"} consists of integer vectors with that class
  attribute, used merely to ensure that they are printed in octal
  notation, specifically for Unix-like file permissions such as
  \code{755}.
}
\seealso{
  These are auxiliary functions for \code{\link{file.info}}
}
\keyword{print}
\eof
\name{on.exit}
\alias{on.exit}
\title{Function Exit Code}
\description{
  \code{on.exit} records the expression given as its argument as needing
  to be executed when the current function exits (either naturally or as
  the result of an error).  This is useful for resetting graphical
  parameters or performing other cleanup actions.

  If no expression is provided, i.e., the call is \code{on.exit()}, then
  the current \code{on.exit} code is removed.
}
\usage{
on.exit(expr, add = FALSE)
}
\arguments{
  \item{expr}{an expression to be executed.}
  \item{add}{if TRUE, add \code{expr} to be executed after any previously
    set expressions.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{sys.on.exit}} to see the current expression.
}
\examples{
opar <- par(mai = c(1,1,1,1))
on.exit(par(opar))
\dontshow{par(opar)}
}
\keyword{programming}
\eof
\name{options}
\alias{options}
\alias{.Options}
\alias{getOption}
\title{Options Settings}
\description{
  Allow the user to set and examine a variety of global \dQuote{options}
  which affect the way in which \R computes and displays its results.
}
\usage{
options(\dots)
getOption(x)
.Options
}
%%-- NOTE : Keep the list up-to-date,
%%-- ====   Consider also the leading comments in ../../../main/options.c
\arguments{
  \item{\dots}{any options can be defined, using \code{name = value}.

    However, only the ones below are used in \dQuote{base \R}.

    Further, \code{options('name') == options()['name']}, see the example.
  }
  \item{x}{a character string holding an option name.}
}
\details{
  Invoking \code{options()} with no arguments returns a list with the
  current values of the options.  Note that not all options listed below
  are set initially.  To access the value of a single option, one should
  use \code{getOption("width")}, e.g., rather than
  \code{options("width")} which is a \emph{list} of length one.

  \code{.Options} also always contains the \code{options()} list, for
  S compatibility.  You must use it \dQuote{read only} however.
}
\value{
  For \code{options}, a list (in any case) with the previous values of
  the options changed, or all options when no arguments were given.
}
\section{Options used in base \R}{
  \describe{
    \item{\code{prompt}:}{a string, used for \R's prompt; should usually
      end in a blank (\code{" "}).}

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

    \item{\code{width}:}{controls the number of characters on a line.
      You may want to change this if you re-size the window that \R is
      running in.  Valid values are 10\dots10000 with default normally
      80.  (The valid values are in file \file{Print.h} and can be
      changed by re-compiling \R.)}

    \item{\code{digits}:}{controls the number of digits to print when
      printing numeric values.  It is a suggestion only.  Valid values
      are 1\dots22 with default 7.  See \code{\link{print.default}}.}

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

    \item{\code{pager}:}{the (stand-alone) program used for displaying
      ASCII files on \R's console, also used by \code{\link{file.show}} and
      sometimes \code{\link[utils]{help}}.
#ifdef unix
      Defaults to \file{\$R\_HOME/bin/pager}.
#endif
#ifdef windows
      Defaults to \code{"internal"}, which uses a pager similar to the
      GUI console.  Another possibility is \code{"console"} to use the
      console itself.
#endif
    }

    \item{\code{browser}:}{default HTML browser used by
      \code{\link[utils]{help.start}()} on UNIX, or a non-default browser on
      Windows.}

#ifdef unix
    \item{\code{pdfviewer}:}{default PDF viewer.  Set from the
      environment variable \env{R\_PDFVIEWER}.}
#endif

    \item{\code{mailer}:}{default mailer used by
      \code{\link[utils]{bug.report}()}.  Can be \code{"none"}.}

    \item{\code{contrasts}:}{the default \code{\link[utils]{contrasts}} used in
      model fitting such as with \code{\link[utils]{aov}} or \code{\link[utils]{lm}}.
      A character vector of length two, the first giving the function to
      be used with unordered factors and the second the function to be
      used with ordered factors.}

    \item{\code{defaultPackages}:}{the packages that are attached by
      default when \R starts up.  Initially set from value of the
      environment variables \env{R\_DefaultPackages}, or if that is unset
      %%  default is set in ../../profile/Common.R :
      to \code{c("utils", "stats", "graphics", "methods")}.  (Set
      \env{R\_DEFAULT\_PACKAGES} to \code{NULL} or a comma-separated list
      of package names.)  A call to \code{options} should be in your
      \file{.Rprofile} file to ensure that the change takes effect
      before the base package is initialized (see \code{\link{Startup}}).}

    \item{\code{expressions}:}{sets a limit on the number of nested
      expressions that will be evaluated.
      Valid values are 25\dots100000 with default 500.}

    \item{\code{keep.source}:}{When \code{TRUE}, the source code for
      functions (newly defined or loaded) is stored in their
      \code{"source"} attribute (see \code{\link{attr}}) allowing
      comments to be kept in the right places.

      The default is \code{\link{interactive}()}, i.e., \code{TRUE} for
      interactive use.}

    \item{\code{keep.source.pkgs}:}{As for \code{keep.source}, for
      functions in packages loaded by \code{\link{library}} or
      \code{\link{require}}.  Defaults to \code{FALSE} unless the
      environment variable \env{R\_KEEP\_PKG\_SOURCE} is set to
      \code{yes}.}

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

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

    \item{\code{printcmd}:}{the command used by \code{\link[graphics]{postscript}}
      for printing; set by environment variable \env{R\_PRINTCMD} when
      \R is started.  This should be a command that expects either input
      to be piped to \file{stdin} or to be given a single filename
      argument.
#ifdef windows
      See \code{\link[graphics]{postscript}} for ways to set this up.
#endif
    }

#ifdef unix
    \item{\code{latexcmd, dvipscmd}:}{character strings giving commands
      to be used in off-line printing of help pages.}
#endif

    \item{\code{show.signif.stars, show.coef.Pvalues}:}{logical,
      affecting P value printing, see \code{\link[stats]{printCoefmat}}.}

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

    \item{\code{error}:}{either a function or an expression governing
      the handling of non-catastrophic errors such as those generated by
      \code{\link{stop}} as well as by signals and internally detected
      errors.  If the option is a function, a call to that function,
      with no arguments, is generated as the expression.  The default
      value is \code{NULL}: see \code{\link{stop}} for the behaviour in
      that case.  The function \code{\link[utils]{dump.frames}} provides one
      alternative that allows post-mortem debugging.}

    \item{\code{show.error.messages}:}{a logical.  Should error messages
      be printed?  Intended for use with \code{\link{try}} or a
      user-installed error handler.}

    \item{\code{warn}:}{sets the handling of warning messages.  If
      \code{warn} is negative all warnings are ignored.  If \code{warn}
      is zero (the default) warnings are stored until the top--level
      function returns.  If fewer than 10 warnings were signalled they
      will be printed otherwise a message saying how many (max 50) were
      signalled.  A top--level variable called \code{last.warning} is
      created and can be viewed through the function
      \code{\link{warnings}}.  If \code{warn} is one, warnings are
      printed as they occur.  If \code{warn} is two or larger all
      warnings are turned into errors.}

    \item{\code{warning.length}:}{sets the truncation limit for error
      and warning messages.  A non-negative integer, with allowed values
      100--8192, default 1000.}

    \item{\code{warning.expression}:}{an \R code expression to be called
      if a warning is generated, replacing the standard message.  If
      non-null is called irrespective of the value of option
      \code{warn}.}
#ifdef windows

	\item{\code{warn.FPU}:}{logical, by default undefined.  If true,
	  a \link{warning} is produced whenever \link{dyn.load} repairs the
	  control word damaged by a buggy DLL.}
#endif

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

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

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

    \item{\code{device}:}{a character string giving the default device
      for that session.  This defaults to the normal screen device
      (e.g., \code{x11}, \code{windows} or \code{gtk}) for an
      interactive session, and \code{postscript} in batch use or if a
      screen is not available.}

#ifdef unix
    \item{\code{X11colortype}:}{The default colour type for
      \code{\link[graphics]{X11}} devices.}
#endif

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

    \item{\code{repositories}:}{A function that when evaluated returns a
      named vector of URLs which can be used to specify the set and
      order of any online repositories the user would like used in
      functions such as \code{\link[tools]{packageDepends}}.  The default
      return value for the function is a vector with two components, one the 
      value of \code{contrib.url(getOption("CRAN"))} and the second
      \code{contrib.url(getOption("BIOC"))}.}
    
    \item{\code{download.file.method}:}{Method to be used for
      \code{download.file}.  Currently download methods
      \code{"internal"}, \code{"wget"} and \code{"lynx"} are available.
      There is no default for this option, when \code{method = "auto"}
      is chosen: see \code{\link[utils]{download.file}}.}

    \item{\code{unzip}:}{the command used for unzipping help files.
#ifdef unix
      Defaults to the value of \env{R\_UNZIPCMD}, which is set in
      \file{etc/Renviron} if an \code{unzip} command was found during
      configuration.}
#endif
#ifdef windows
      Defaults to \code{"internal"} when the internal unzip code is
      used.}
#endif

    \item{\code{de.cellwidth}:}{integer: the cell widths (number of
      characters) to be used in the data editor \code{\link[utils]{dataentry}}.
      If this is unset, 0, negative or \code{NA}, variable cell widths
      are used.}

    \item{\code{encoding}:}{An integer vector of length 256 holding an
      input encoding.  Defaults to \code{native.enc} (= \code{0:255}).
      See \code{\link{connections}}.}

    \item{\code{timeout}:}{integer.  The timeout for some Internet
      operations, in seconds.  Default 60 seconds.
      See \code{\link[utils]{download.file}} and \code{\link{connections}}.}

    \item{\code{internet.info}:}{The minimum level of information to be
      printed on URL downloads etc.  Default is 2, for failure causes.
      Set to 1 or 0 to get more information.}

    \item{\code{scipen}:}{integer.  A penalty to be applied
      when deciding to print numeric values in fixed or exponential
      notation.  Positive values bias towards fixed and negative towards
      scientific notation: fixed notation will be preferred unless it is
      more than \code{scipen} digits wider.}

    \item{\code{locatorBell}:}{logical.  Should selection in \code{locator}
      and \code{identify} be confirmed by a bell.  Default \code{TRUE}.
      Honoured at least on \code{X11} and \code{windows} devices.}
#ifdef unix
    \item{\code{X11fonts}:}{character vector of length 2.
      See \code{\link[graphics]{X11}}.}
#endif
  }

  The default settings of some of these options are
  \tabular{llll}{
    \code{prompt} \tab \code{"> "} \tab
    \code{continue} \tab \code{"+ "}\cr
    \code{width}  \tab \code{80} \tab
    \code{digits} \tab \code{7}\cr
    \code{expressions} \tab \code{500} \tab
    \code{keep.source} \tab \code{TRUE}\cr
    \code{show.signif.stars} \tab \code{TRUE} \tab
    \code{show.coef.Pvalues} \tab \code{TRUE}\cr
    \code{na.action} \tab \code{na.omit} \tab
    \code{ts.eps} \tab \code{1e-5}\cr
    \code{error} \tab \code{NULL} \tab
    \code{show.error.messages} \tab \code{TRUE} \cr
    \code{warn} \tab \code{0}\tab
    \code{warning.length} \tab \code{1000}\cr
    \code{echo} \tab \code{TRUE} \tab
    \code{verbose} \tab \code{FALSE} \cr
    \code{scipen} \tab \code{0} \tab \code{locatorBell} \tab \code{TRUE}
  }
  Others are set from environment variables or are platform-dependent.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
options() # printing all current options
op <- options(); str(op) # nicer printing

# .Options is the same:
all(sapply(1:length(op), function(i) if(is.atomic(op[[i]]))
                         {all(.Options[[i]] == op[[i]])} else TRUE))

options('width')[[1]] == options()$width # the latter needs more memory
options(digits=20)
pi

# set the editor, and save previous value
old.o <- options(editor="nedit")
old.o

options(check.bounds = TRUE)
x <- NULL; x[4] <- "yes" # gives a warning

options(digits=5)
print(1e5)
options(scipen=3); print(1e5)

options(op)     # reset (all) initial options
options('digits')

\dontrun{## set contrast handling to be like S
options(contrasts=c("contr.helmert", "contr.poly"))
}
\dontrun{## on error, terminate the R session with error status 66
options(error=quote(q("no", status=66, runLast=FALSE)))
stop("test it")
}
\dontrun{## set an error action for debugging: see ?debugger.
options(error=dump.frames)
## A possible setting for non-interactive sessions
options(error=quote({dump.frames(to.file=TRUE); q()}))
}}
\keyword{environment}
\keyword{error}
\keyword{print}
\eof
\name{order}
\title{Ordering Permutation}
\alias{order}
\alias{sort.list}
\description{
  \code{order} returns a permutation which rearranges its first
  argument into ascending or descending order, breaking ties by further
  arguments. \code{sort.list} is the same, using only one argument.
}
\usage{
order(\dots, na.last = TRUE, decreasing = FALSE)

sort.list(x, partial = NULL, na.last = TRUE, decreasing = FALSE,
          method = c("shell", "quick", "radix"))
}
\arguments{
  \item{\dots}{a sequence of vectors, all of the same length.}
  \item{x}{a vector.}
  \item{partial}{vector of indices for partial sorting.}
  \item{decreasing}{logical. Should the sort order be increasing or
    decreasing?}
  \item{na.last}{for controlling the treatment of \code{NA}s.
    If \code{TRUE}, missing values in the data are put last; if
    \code{FALSE}, they are put first; if \code{NA}, they are removed.
  }
  \item{method}{the method to be used: partial matches are allowed.}
}
\details{
  In the case of ties in the first vector, values in the second are used
  to break the ties.  If the values are still tied, values in the later
  arguments are used to break the tie (see the first example).
  The sort used is \emph{stable} (except for \code{method = "quick"}),
  so any unresolved ties will be left in their original ordering.

  The default method for \code{sort.list} is a good compromise.
  Method \code{"quick"} is only supported for numeric \code{x} with
  \code{na.last=NA}, and is not stable, but will be faster for long vectors.
  Method \code{"radix"} is only implemented for integer \code{x} with
  a range of less than 100,000.  For such \code{x} it is very
  fast (and stable), and hence is ideal for sorting factors.

  \code{partial} is supplied for compatibility with other
  implementations of S, but no other values are accepted and ordering is
  always complete.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{\code{\link{sort}} and \code{\link{rank}}.}
\examples{
(ii <- order(x <- c(1,1,3:1,1:4,3), y <- c(9,9:1), z <-c(2,1:9)))
## 6  5  2  1  7  4 10  8  3  9
rbind(x,y,z)[,ii] # shows the reordering (ties via 2nd & 3rd arg)

## Suppose we wanted descending order on y. A simple solution is
rbind(x,y,z)[, order(x, -y, z)]
## For character vectors we can make use of rank:
cy <- as.character(y)
rbind(x,y,z)[, order(x, -rank(y), z)]

## rearrange matched vectors so that the first is in ascending order
x <- c(5:1, 6:8, 12:9)
y <- (x - 5)^2
o <- order(x)
rbind(x[o], y[o])

## tests of na.last
a <- c(4, 3, 2, NA, 1)
b <- c(4, NA, 2, 7, 1)
z <- cbind(a, b)
(o <- order(a, b)); z[o, ]
(o <- order(a, b, na.last = FALSE)); z[o, ]
(o <- order(a, b, na.last = NA)); z[o, ]

\dontrun{
##  speed examples for long vectors: timings are immediately after gc()
x <- factor(sample(letters, 1e6, replace=TRUE))
system.time(o <- sort.list(x)) ## 4 secs
stopifnot(!is.unsorted(x[o]))
system.time(o <- sort.list(x, method="quick", na.last=NA)) # 0.4 sec
stopifnot(!is.unsorted(x[o]))
system.time(o <- sort.list(x, method="radix")) # 0.04 sec
stopifnot(!is.unsorted(x[o]))
xx <- sample(1:26, 1e7, replace=TRUE)
system.time(o <- sort.list(xx, method="radix")) # 0.4 sec
xx <- sample(1:100000, 1e7, replace=TRUE)
system.time(o <- sort.list(xx, method="radix")) # 4 sec
}}
\keyword{univar}
\keyword{manip}
\eof
\name{outer}
\alias{outer}
\alias{\%o\%}
\title{Outer Product of Arrays}
\description{
  The outer product of the arrays \code{X} and \code{Y} is the array
  \code{A} with dimension \code{c(dim(X), dim(Y))} where element
  \code{A[c(arrayindex.x, arrayindex.y)]
    = FUN(X[arrayindex.x], Y[arrayindex.y], \dots)}.
}
\usage{
outer(X, Y, FUN="*", \dots)
X \%o\% Y
}

\arguments{
  \item{X}{A vector or array.}
  \item{Y}{A vector or array.}
  \item{FUN}{a function to use on the outer products, it may be a quoted
    string.}
  \item{\dots}{optional arguments to be passed to \code{FUN}.}
}
\details{
  \code{FUN} must be a function (or the name of it) which expects at
  least two arguments and which operates elementwise on arrays.
    
  Where they exist, the [dim]names of \code{X} and \code{Y} will be
  preserved.
    
  \code{\%o\%} is an alias for \code{outer} (where \code{FUN}
  cannot be changed from \code{"*"}).
}
\author{Jonathan Rougier}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{\%*\%}} for usual (\emph{inner}) matrix vector
  multiplication;
  \code{\link{kronecker}} which is based on \code{outer}.
}
\examples{
x <- 1:9; names(x) <- x
# Multiplication & Power Tables
x \%o\% x
y <- 2:8; names(y) <- paste(y,":",sep="")
outer(y, x, "^")

outer(month.abb, 1999:2003, FUN = "paste")

## three way multiplication table:
x \%o\% x \%o\% y[1:3]
}
\keyword{array}
\eof
\name{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, depLevel=c("Depends", "Suggests"))
}
\arguments{
    \item{x}{A matrix of package descriptions as returned by
	\code{\link[utils]{CRAN.packages}}.}
    \item{check}{If \code{TRUE}, return logical vector of check results.
	If \code{FALSE}, return parsed list of dependencies.}
    \item{depLevel}{Whether to look for \code{Depends} or
      \code{Suggests} level 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[utils]{update.packages}}}
\keyword{utilities}
\eof
\name{packageDescription}
\alias{packageDescription}
\alias{print.packageDescription}
\title{Package Description}
\description{
  Parses and returns the \file{DESCRIPTION} file of a package.
}
\usage{
packageDescription(pkg, lib.loc = NULL, fields = NULL, drop=TRUE)
}
\arguments{
  \item{pkg}{a character string with the package name.}
  \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{fields}{a character vector giving the tags of fields to return
    (if other fields occur in the file they are ignored).}
  \item{drop}{If \code{TRUE} and the length of \code{fields} is 1, then
    a single character string with the value of the respective field is
    returned instead of an object of class \code{"packageDescription"}.}
}
\value{
  If a \file{DESCRIPTION} for the given package is found and can
  successfully be read, \code{packageDescription} returns an object of
  class \code{"packageDescription"}, which is a named list
  with the values of the (given) fields as elements and
  the tags as names, unless \code{drop = TRUE}.

  If parsing the \file{DESCRIPTION} file was not
  successful, it returns a named list 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}}, \code{\link[utils]{package.contents}}}
\examples{
packageDescription("stats")
packageDescription("stats", fields = c("Package", "Version"))

packageDescription("stats", fields = "Version")
packageDescription("stats", fields = "Version", drop = FALSE)
}
\keyword{utilities}
\eof
\name{parse}
\alias{parse}
\title{Parse Expressions}
\description{
  \code{parse} returns the parsed but unevaluated expressions in a
  list.  Each element of the list is of mode \code{expression}.
}
\usage{
parse(file = "", n = NULL, text = NULL, prompt = "?")
}
\arguments{
  \item{file}{a connection, or a character string giving the name of a
    file or a URL to read the expressions from.
    If \code{file} is \code{""} and \code{text} is missing or \code{NULL}
    then input is taken from the console.}
  \item{n}{the number of statements to parse.  If \code{n} is negative
    the file is parsed in its entirety.}
  \item{text}{character vector. The text to parse. Elements are treated
    as if they were lines of a file.}
  \item{prompt}{the prompt to print when parsing from the keyboard.
    \code{NULL} means to use \R's prompt, \code{getOption("prompt")}.}
    \code{NULL} means to use \R's prompt, \code{getOption("prompt")}.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{scan}}, \code{\link{source}}, \code{\link{eval}},
  \code{\link{deparse}}.
}
\details{
  All versions of \R accept input from a connection with end of line
  marked by LF (as used on Unix), CRLF (as used on DOS/Windows)
  or CR (as used on classic MacOS).  The final line can be incomplete,
  that is missing the final EOL marker.

  See \code{\link{source}} for the limits on the size of functions
  that can be parsed (by default).
}
\examples{
cat("x <- c(1,4)\n  x ^ 3 -10 ; outer(1:7,5:9)\n", file="xyz.Rdmped")
# parse 3 statements from the file "xyz.Rdmped"
parse(file = "xyz.Rdmped", n = 3)
unlink("xyz.Rdmped")
}
\keyword{file}
\keyword{programming}
\keyword{connection}
\eof
\name{paste}
\title{Concatenate Strings}
\usage{
paste(\dots, sep = " ", collapse = NULL)
}
\alias{paste}
\arguments{
  \item{\dots}{one or more \R objects, to be coerced to character vectors.}
  \item{sep}{a character string to separate the terms.}
  \item{collapse}{an optional character string to separate the results.}
}
\description{
  Concatenate vectors after converting to character.
}
\details{
  \code{paste} converts its arguments to character strings, and
  concatenates them (separating them by the string given by \code{sep}).
  If the arguments are vectors, they are concatenated term-by-term to
  give a character vector result.

  If a value is specified for \code{collapse}, the values in the result
  are then concatenated into a single string, with the elements being
  separated by the value of \code{collapse}.
}
\value{
  A character vector of the concatenated values.  This will be of length
  zero if all the objects are, unless \code{collapse} is non-NULL, in
  which case it is a single empty string.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  String manipulation with
  \code{\link{as.character}}, \code{\link{substr}}, \code{\link{nchar}},
  \code{\link{strsplit}}; further, \code{\link{cat}} which concatenates and
  writes to a file, and \code{\link{sprintf}} for C like string
  construction.
}
\examples{
paste(1:12) # same as as.character(1:12)
paste("A", 1:6, sep = "")
paste("Today is", date())
}
\keyword{character}
\eof
\name{path.expand}
\alias{path.expand}
\title{Expand File Paths}
\description{
  Expand a path name, for example by replacing a leading tilde by the
  user's home directory (if defined on that platform).
}
\usage{
path.expand(path)
}
\arguments{
  \item{path}{character vector containing one or more path names.}
}
#ifdef unix
\details{
  On \emph{some Unix} versions, a leading \code{~user} will expand to
  the home directory of \code{user}, but not on Unix versions without
  \code{readline} installed.
}
#endif
\seealso{
  \code{\link{basename}}
}
\examples{
path.expand("~/foo")
}
\keyword{file}
\eof
\name{phones}
\docType{data}
\alias{phones}
\title{The World's Telephones}
\description{
  The number of telephones in various regions of the world (in
  thousands).
}
\usage{data(phones)}
\format{
  A matrix with 7 rows and 8 columns.  The columns of the matrix give
  the figures for a given region, and the rows the figures for a year.

  The regions are: North America, Europe, Asia, South America, Oceania,
  Africa, Central America.
  
  The years are: 1951, 1956, 1957, 1958, 1959, 1960, 1961.
}
\source{
  AT&T (1961) \emph{The World's Telephones}.
}
\references{
  McNeil, D. R. (1977)
  \emph{Interactive Data Analysis}.
  New York: Wiley.
}
\examples{
data(phones)
matplot(rownames(phones), phones, type = "b", log = "y",
        xlab = "Year", ylab = "Number of telephones (1000's)")
legend(1951.5, 80000, colnames(phones), col = 1:6, lty = 1:5, pch = rep(21, 7))
title(main = "phones data: log scale for response")
}
\keyword{datasets}
\eof
\name{pmatch}
\title{Partial String Matching}
\usage{
pmatch(x, table, nomatch = NA, duplicates.ok = FALSE)
}
\alias{pmatch}
\arguments{
  \item{x}{the values to be matched.}
  \item{table}{the values to be matched against.}
  \item{nomatch}{the value returned at non-matching or multiply
    partially matching positions.}
  \item{duplicates.ok}{should elements be in \code{table} be used more
    than once?}
}
\description{
  \code{pmatch} seeks matches for the elements of its first argument
  among those of its second.
}
\details{
  The behaviour differs by the value of \code{duplicates.ok}. Consider
  first the case if this is true.  First exact matches are considered,
  and the positions of the first exact matches are recorded. Then unique
  partial matches are considered, and if found recorded. (A partial
  match occurs if the whole of the element of \code{x} matches the
  beginning of the element of \code{table}.)  Finally,
  all remaining elements of \code{x} are regarded as unmatched.
  In addition, an empty string can match nothing, not even an exact
  match to an empty string.  This is the appropriate behaviour for
  partial matching of character indices, for example.

  If \code{duplicates.ok} is \code{FALSE}, values of \code{table} once
  matched are excluded from the search for subsequent matches.  This
  behaviour is equivalent to the \R algorithm for argument
  matching, except for the consideration of empty strings (which in
  argument matching are matched after exact and partial matching to any
  remaining arguments).

  \code{\link{charmatch}} is similar to \code{pmatch} with
  \code{duplicates.ok} true, the differences being that it
  differentiates between no match and an ambiguous partial match,  it
  does match empty strings, and it does not allow multiple exact matches.
}
\value{
  A numeric vector of integers (including \code{NA} if \code{nomatch =
    NA}) of the same length as \code{x}, giving the indices of the
  elements in \code{table} which matched, or \code{nomatch}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Chambers, J. M. (1998)
  \emph{Programming with Data. A Guide to the S Language}.
  Springer.
}
\seealso{
  \code{\link{match}}, \code{\link{charmatch}} and
  \code{\link{match.arg}}, \code{\link{match.fun}},
  \code{\link{match.call}}, for function argument matching etc.,
  \code{\link{grep}} etc for more general (regexp) matching of strings.
}
\examples{
pmatch("", "")                             # returns NA
pmatch("m",   c("mean", "median", "mode")) # returns NA
pmatch("med", c("mean", "median", "mode")) # returns 2

pmatch(c("", "ab", "ab"), c("abc", "ab"), dup=FALSE)
pmatch(c("", "ab", "ab"), c("abc", "ab"), dup=TRUE)
## compare
charmatch(c("", "ab", "ab"), c("abc", "ab"))
}
\keyword{character}
\eof
\name{polyroot}
\title{Find Zeros of a Real or Complex Polynomial}
\usage{
polyroot(z)
}
\alias{polyroot}
\arguments{
  \item{z}{the vector of polynomial coefficients in increasing order.}
}
\description{
  Find zeros of a real or complex polynomial.
}
\details{
  A polynomial of degree \eqn{n - 1},
  \deqn{
    p(x) = z_1 + z_2 x + \cdots + z_n x^{n-1}}{
    p(x) = z1 + z2 * x + \ldots + z[n] * x^(n-1)}
  is given by its coefficient vector \code{z[1:n]}.
  \code{polyroot} returns the \eqn{n-1} complex zeros of \eqn{p(x)}
  using the Jenkins-Traub algorithm.

  If the coefficient vector \code{z} has zeroes for the highest powers,
  these are discarded.
}
\value{
  A complex vector of length \eqn{n - 1}, where \eqn{n} is the position
  of the largest non-zero element of \code{z}. 
}
\references{
  Jenkins and Traub (1972)
  TOMS Algorithm 419.
  \emph{Comm. ACM}, \bold{15}, 97--99.
}
\seealso{
  \code{\link[stats]{uniroot}} for numerical root finding of arbitrary
  functions;
  \code{\link{complex}} and the \code{zero} example in the demos
  directory.
}
\examples{
polyroot(c(1, 2, 1))
round(polyroot(choose(8, 0:8)), 11) # guess what!
for (n1 in 1:4) print(polyroot(1:n1), digits = 4)
polyroot(c(1, 2, 1, 0, 0)) # same as the first
}
\keyword{math}
\eof
\name{pos.to.env}
\alias{pos.to.env}
\title{Convert Positions in the Search Path to Environments}
\description{
  Returns the environment at a specified position in the search path.
}
\usage{pos.to.env(x)}
\arguments{
  \item{x}{an integer between 1 and \code{length(search())}, the length
    of the search path.}
}
\details{
  Several \R functions for manipulating objects in environments (such as
  \code{\link{get}} and \code{\link{ls}}) allow specifying environments
  via corresponding positions in the search path.  \code{pos.to.env} is
  a convenience function for programmers which converts these positions
  to corresponding environments; users will typically have no need for
  it.
}
\examples{
pos.to.env(1) # R_GlobalEnv
# the next returns NULL, which is how package:base is represented.
pos.to.env(length(search()))
}
\keyword{utilities}
\eof
\name{precip}
\docType{data}
\alias{precip}
\title{Annual Precipitation in US Cities}
\description{
  The average amount of precipitation (rainfall) in inches for each of
  70 United States (and Puerto Rico) cities.
}
\usage{data(precip)}
\format{
  A named vector of length 70.
}
\source{
  Statistical Abstracts of the United States, 1975.
}
\references{
  McNeil, D. R. (1977)
  \emph{Interactive Data Analysis}.
  New York: Wiley.
}
\examples{
require(graphics)
data(precip)
dotchart(precip[order(precip)], main = "precip data")
title(sub = "Average annual precipitation (in.)")
}
\keyword{datasets}
\eof
\name{pressure}
\docType{data}
\alias{pressure}
\title{Vapor Pressure of Mercury as a Function of Temperature}
\description{
  Data on the relation between temperature in degrees Celsius and vapor
  pressure of mercury in millimeters (of mercury).
}
\usage{data(pressure)}
\format{
  A data frame with 19 observations on 2 variables.
  \tabular{rlll}{
    [, 1] \tab temperature \tab numeric \tab temperature (deg C)\cr
    [, 2] \tab pressure    \tab numeric \tab pressure (mm)
  }
}
\source{
  Weast, R. C., ed. (1973)
  \emph{Handbook of Chemistry and Physics}.
  CRC Press.
}
\references{
  McNeil, D. R. (1977)
  \emph{Interactive Data Analysis}.
  New York: Wiley.
}
\examples{
data(pressure)
plot(pressure, xlab = "Temperature (deg C)",
     ylab = "Pressure (mm of Hg)",
     main = "pressure data: Vapor Pressure of Mercury")
plot(pressure, xlab = "Temperature (deg C)",  log = "y",
     ylab = "Pressure (mm of Hg)",
     main = "pressure data: Vapor Pressure of Mercury")
}
\keyword{datasets}
\eof
\name{pretty}
\title{Pretty Breakpoints}
\usage{
pretty(x, n = 5, min.n = n \%/\% 3,  shrink.sml = 0.75,
       high.u.bias = 1.5, u5.bias = .5 + 1.5*high.u.bias,
       eps.correct = 0)
}
\alias{pretty}
\arguments{
\item{x}{numeric vector}
\item{n}{integer giving the \emph{desired} number of
  intervals.  Non-integer values are rounded down.}
\item{min.n}{nonnegative integer giving the \emph{minimal} number of
    intervals.  If \code{min.n == 0}, \code{pretty(.)} may return a
    single value.}
\item{shrink.sml}{positive numeric
  by a which a default scale is shrunk in the case when
  \code{range(x)} is \dQuote{very small} (usually 0).}
\item{high.u.bias}{non-negative numeric, typically \eqn{> 1}.
    The interval unit is determined as \{1,2,5,10\} times \code{b}, a
    power of 10.  Larger \code{high.u.bias} values favor larger units.
}
\item{u5.bias}{non-negative numeric
    multiplier favoring factor 5 over 2.  Default and \dQuote{optimal}:
    \code{u5.bias = .5 + 1.5*high.u.bias}.}
\item{eps.correct}{integer code, one of \{0,1,2\}. If non-0, an
    \dQuote{\emph{epsilon correction}} is made at the boundaries such that
    the result boundaries will be outside \code{range(x)}; in the
    \emph{small} case, the correction is only done if \code{eps.correct >=2}.}
}
\description{
    Compute a  sequence of about \code{n+1} equally spaced nice values which
    cover the range of the values in \code{x}.
    The values are chosen so that they are 1, 2 or 5 times a power of 10.
}
\details{
    Let \code{d <- max(x) - min(x)} \eqn{\ge 0}{>= 0}.
    If \code{d} is not (very close) to 0, we let \code{c <- d/n},
    otherwise more or less \code{c <- max(abs(range(x)))*shrink.sml / min.n}.
    Then, the \emph{10 base} \code{b} is
    \eqn{10^{\lfloor{\log_{10}(c)}\rfloor}}{10^(floor(log10(c)))} such
    that \eqn{b \le c < 10b}.

    Now determine the basic \emph{unit} \eqn{u} as one of
    \eqn{\{1,2,5,10\} b}, depending on \eqn{c/b \in [1,10)} and the two
    \dQuote{\emph{bias}} coefficients, \eqn{h =}\code{high.u.bias} and
    \eqn{f =}\code{u5.bias}.

    \dots\dots\dots
%%-- fixme: give even more details
%%-- fixme: give even more details

}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
pretty(1:15)     # 0  2  4  6  8 10 12 14 16
pretty(1:15, h=2)# 0  5 10 15
pretty(1:15, n=4)# 0  5 10 15
pretty(1:15 * 2) # 0  5 10 15 20 25 30
pretty(1:20)      # 0  5 10 15 20
pretty(1:20, n=2) # 0 10 20
pretty(1:20, n=10)# 0  2  4 ... 20

for(k in 5:11) {
  cat("k=",k,": "); print(diff(range(pretty(100 + c(0, pi*10^-k)))))}

##-- more bizarre, when  min(x) == max(x):
pretty(pi)

add.names <- function(v) { names(v) <- paste(v); v}
str(lapply(add.names(-10:20), pretty))
str(lapply(add.names(0:20),   pretty, min = 0))
sapply(    add.names(0:20),   pretty, min = 4)

pretty(1.234e100)
pretty(1001.1001)
pretty(1001.1001, shrink = .2)
for(k in -7:3)
  cat("shrink=",formatC(2^k,wid=9),":",
      formatC(pretty(1001.1001, shrink = 2^k), wid=6),"\n")
}
\keyword{dplot}
\eof
\name{print}
\title{Print Values}
\usage{
print(x, \dots)

\method{print}{factor}(x, quote = FALSE, max.levels = NULL,
     width = getOption("width"), \dots)

\method{print}{table}(x, digits = getOption("digits"), quote = FALSE,
          na.print = "", zero.print = "0", justify = "none", \dots)
}
\alias{print}
\alias{print.factor}
\alias{print.htest}
\alias{print.listof}
\alias{print.simple.list}
\alias{print.table}
\description{
  \code{print} prints its argument and returns it \emph{invisibly} (via
  \code{\link{invisible}(x)}).  It is a generic function which means that
  new printing methods can be easily added for new
  \code{\link[base]{class}}es.
}
\arguments{
  \item{x}{an object used to select a method.}
  \item{\dots}{further arguments passed to or from other methods.}
  \item{quote}{logical, indicating whether or not strings should be
    printed with surrounding quotes.}
  \item{max.levels}{integer, indicating how many levels should be
    printed for a factor; if \code{0}, no extra "Levels" line will be
    printed.  The default, \code{NULL}, entails choosing \code{max.levels}
    such that the levels print on one line of width \code{width}.}
  \item{width}{only used when \code{max.levels} is NULL, see above.}
  \item{digits}{minimal number of \emph{significant} digits, see
    \code{\link{print.default}}.}
  \item{na.print}{character string (or \code{NULL}) indicating
    \code{\link{NA}} values in printed output, see
    \code{\link{print.default}}.}
  \item{zero.print}{character specifying how zeros (\code{0}) should be
    printed; for sparse tables, using \code{"."} can produce stronger results.}
  \item{justify}{character indicating if strings should left- or
    right-justified or left alone, passed to \code{\link{format}}.}
}
\details{
  The default method, \code{\link{print.default}} has its own help page.
  Use \code{\link[utils]{methods}("print")} to get all the methods for the
  \code{print} generic.

  \code{print.factor} allows some customization and is used for printing
  \code{\link{ordered}} factors as well.

  \code{print.table} for printing \code{\link{table}}s allows other
  customization.

  See \code{\link{noquote}} as an example of a class whose main
  purpose is a specific \code{print} method.
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S.}
  Wadsworth \& Brooks/Cole.
}
\seealso{
  The default method \code{\link{print.default}}, and help for the
  methods above; further \code{\link{options}}, \code{\link{noquote}}.

  For more customizable (but cumbersome) printing, see
  \code{\link{cat}}, \code{\link{format}} or also \code{\link{write}}.
}
\examples{
ts(1:20)#-- print is the "Default function" --> print.ts(.) is called
rr <- for(i in 1:3) print(1:i)
rr

## Printing of factors
data(attenu)
attenu$station ## 117 levels -> `max.levels' depending on width

data(esoph) ## ordered : levels  "l1 < l2 < .."
esoph$agegp[1:12]
esoph$alcgp[1:12]

## Printing of sparse (contingency) tables
set.seed(521)
t1 <- round(abs(rt(200, df=1.8)))
t2 <- round(abs(rt(200, df=1.4)))
table(t1,t2) # simple
print(table(t1,t2), zero.print = ".")# nicer to read
}
\keyword{print}
\eof
\name{print.data.frame}
\title{Printing Data Frames}
\alias{print.data.frame}
\description{
  Print a data frame.
}
\usage{
\method{print}{data.frame}(x, \dots, digits = NULL, quote = FALSE, right = TRUE)
}
\arguments{
  \item{x}{object of class \code{data.frame}.}
  \item{\dots}{optional arguments to \code{print} or \code{plot} methods.}
  \item{digits}{the minimum number of significant digits to be used.}
  \item{quote}{logical, indicating whether or not entries should be
    printed with surrounding quotes.}
  \item{right}{logical, indicating whether or not strings should be
    right-aligned. The default is left-alignment.}
}
\details{
  This calls \code{\link{format}} which formats the data frame
  column-by-column, then converts to a character matrix and dispatches
  to the \code{print} method for matrices.

  When \code{quote = TRUE} only the entries are quoted not the row names
  nor the column names.
}
\seealso{
  \code{\link{data.frame}}.
}
\keyword{print}
\eof
\name{print.default}
\alias{print.default}
\alias{print.matrix}
\description{
  \code{print.default} is the \emph{default} method of the generic
  \code{\link{print}} function which prints its argument.
  \code{print.matrix} is currently identical, but was not prior to
  \code{1.7.0}.
}
\title{Default Printing}
\usage{
\method{print}{default}(x, digits = NULL, quote = TRUE, na.print = NULL,
      print.gap = NULL, right = FALSE, \dots)
}
\arguments{
  \item{x}{the object to be printed.}
  \item{digits}{a non-null value for \code{digits} specifies the minimum
    number of significant digits to be printed in values.  If
    \code{digits} is \code{NULL}, the value of \code{digits} set by
    \code{options} is used.}
  \item{quote}{logical, indicating whether or not strings
    (\code{\link{character}}s) should be printed with surrounding quotes.}
  \item{na.print}{a character string which is used to indicate
    \code{\link{NA}} values in printed output, or \code{NULL} (see Details)}
  \item{print.gap}{an integer, giving the spacing between adjacent columns
    in printed matrices and arrays, or \code{NULL} meaning 1.}
  \item{right}{logical, indicating whether or not strings should be
    right-aligned. The default is left-alignment.}
  \item{\dots}{further arguments to be passed to or from other
    methods. They are ignored in these functions.}
}
\details{
  Prior to \R 1.7.0, \code{print.matrix} did not
  print attributes and did not have a \code{digits} argument.
  
  The default for printing \code{NA}s is to print \code{NA} (without
  quotes) unless this is a character \code{NA} \emph{and} \code{quote =
    FALSE}, when \code{<NA>} is printed.

  The same number of decimal places is used throughout a vector,  This
  means that \code{digits} specifies the minimum number of significant
  digits to be used, and that at least one entry will be printed with
  that minimum number.

  As from \R 1.7.0 attributes are printed respecting their class(es),
  using the values of \code{digits} to \code{print.default}, but using the
  default values (for the methods called) of the other arguments.

  When the \pkg{methods} package is attached, \code{print} will call
  \code{\link[methods]{show}} for methods with formal classes if called
  with no optional arguments.
}
\seealso{The generic \code{\link{print}}, \code{\link{options}}.
  The \code{"\link{noquote}"} class and print method.
}
\examples{
pi
print(pi, digits = 16)
LETTERS[1:16]
print(LETTERS, quote = FALSE)
}
\keyword{print}
\eof
\name{prmatrix}
\alias{prmatrix}
\title{Print Matrices, Old-style}
\usage{
prmatrix(x, rowlab =, collab =,
         quote = TRUE, right = FALSE, na.print = NULL, \dots)
}
\arguments{
  \item{x}{numeric or character matrix.}
  \item{rowlab,collab}{(optional) character vectors giving row or column
    names respectively.  By default, these are taken from
    \code{\link{dimnames}(x)}.}
  \item{quote}{logical; if \code{TRUE} and \code{x} is of mode
    \code{"character"}, \emph{quotes} (\code{"}) are used.} %"
  \item{right}{ if \code{TRUE} and \code{x} is of mode
    \code{"character"}, the output columns are \emph{right}-justified.}
  \item{na.print}{how \code{NA}s are printed.  If this is non-null, its
    value is used to represent \code{NA}.}
  \item{\dots}{arguments for \code{print} methods.}
}
\description{
  An earlier method for printing matrices, provided for S compatibility.
}
\details{
  \code{prmatrix} is an earlier form of \code{print.matrix}, and
  is very similar to the S function of the same name.
}
\value{
  Invisibly returns its argument, \code{x}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{print.default}}, and other \code{\link{print}} methods.
}
\examples{
prmatrix(m6 <- diag(6), row = rep("",6), coll=rep("",6))

chm <- matrix(scan(system.file("help", "AnIndex", package = "splines"),
                   what = ""), , 2, byrow = TRUE)
chm  # uses print.matrix()
prmatrix(chm, collab = paste("Column",1:3), right=TRUE, quote=FALSE)
}
\keyword{print}
\eof
\name{proc.time}
\alias{proc.time}
\title{Running Time of R}
\description{
  \code{proc.time} determines how much time (in seconds) the currently
  running \R process already consumed.
}
\usage{
proc.time()
}
\value{
  A numeric vector of length 5, containing the user, system, and total
  elapsed times for the currently running \R process, and the cumulative
  sum of user and system times of any child processes spawned by it.

  The resolution of the times will be system-specific; it is common for
  them to be recorded to of the order of 1/100 second, and elapsed
  time is rounded to the nearest 1/100.

  It is most useful for \dQuote{timing} the evaluation of \R expressions,
  which can be done conveniently with \code{\link{system.time}}.
}
\note{
#ifdef unix
  It is possible to compile \R without support for \code{proc.time},
  when the function will not exist.
#endif
#ifdef windows
  CPU times will be returned as \code{NA} on Windows 9x/ME systems, but
  are genuine times on NT4/2000/XP systems. Times of child processes are
  not available and will always be given as \code{NA}.
#endif
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{system.time}} for timing a valid \R expression,
  \code{\link{gc.time}} for how much of the time was spent in garbage
  collection.
}
\examples{\dontrun{
## a way to time an R expression: system.time is preferred
ptm <- proc.time()
for (i in 1:50) mad(runif(500))
proc.time() - ptm
}}
\keyword{utilities}
\eof
\name{prod}
\title{Product of Vector Elements}
\usage{
prod(\dots, na.rm = FALSE)
}
\alias{prod}
\description{
  \code{prod} returns the product of all the values
  present in its arguments.
}
\arguments{
  \item{\dots}{numeric vectors.}
  \item{na.rm}{logical. Should missing values be removed?}
}
\details{
  If \code{na.rm} is \code{FALSE} an \code{NA}
  value in any of the arguments will cause
  a value of \code{NA} to be returned, otherwise
  \code{NA} values are ignored.

  This is a generic function: methods can be defined for it
  directly or via the \code{\link{Summary}} group generic.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
\code{\link{sum}},
\code{\link{cumprod}},
\code{\link{cumsum}}.
}
\examples{
print(prod(1:7)) == print(gamma(8))
}
\keyword{arith}
\eof
\name{prop.table}
\title{Express table entries as fraction of marginal table}
\usage{
prop.table(x, margin=NULL)
}
\alias{prop.table}
\arguments{
 \item{x}{ table }
 \item{margin}{ index, or vector of indices to generate margin for}
}

\description{ This is really \code{sweep(x, margin, margin.table(x,
margin), "/")} for newbies, except that if \code{margin} has length
zero, then one gets \code{x/sum(x)}.  }

\value{
  Table like \code{x} expressed relative to \code{margin} 
}
\author{ Peter Dalgaard }

\seealso{\code{\link{margin.table}}}

\examples{
m<-matrix(1:4,2)
m
prop.table(m,1)
}
\keyword{ array }
\eof
\name{pushBack}
\alias{pushBack}
\alias{pushBackLength}
\title{Push Text Back on to a Connection}
\description{
  Functions to push back text lines onto a connection, and to enquire
  how many lines are currently pushed back.
}
\usage{
pushBack(data, connection, newLine = TRUE)
pushBackLength(connection)
}
\arguments{
  \item{data}{a character vector.}
  \item{connection}{A connection.}
  \item{newLine}{logical. If true, a newline is appended to each string
    pushed back.}
}
\details{
  Several character strings can be pushed back on one or more occasions.
  The occasions form a stack, so the first line to be retrieved will be
  the first string from the last call to \code{pushBack}.  Lines which
  are pushed back are read prior to the normal input from the
  connection, by the normal text-reading functions such as
  \code{\link{readLines}} and \code{\link{scan}}.

  Pushback is only allowed for readable connections.

  Not all uses of connections respect pushbacks, in particular the input
  connection is still wired directly, so for example parsing
  commands from the console and \code{\link{scan}("")} ignore pushbacks on
  \code{\link{stdin}}.
}
\value{
  \code{pushBack} returns nothing.

  \code{pushBackLength} returns number of lines currently pushed back.
}
\seealso{\code{\link{connections}}, \code{\link{readLines}}.}

\examples{
zz <- textConnection(LETTERS)
readLines(zz, 2)
pushBack(c("aa", "bb"), zz)
pushBackLength(zz)
readLines(zz, 1)
pushBackLength(zz)
readLines(zz, 1)
readLines(zz, 1)
close(zz)
}
\keyword{connection}
\eof
\name{Sys.putenv}
\title{Set Environment Variables}
\usage{
Sys.putenv(\dots)
}
\alias{Sys.putenv}
\arguments{
  \item{\dots}{arguments in \code{name=value} form, with \code{value}
    coercible to a character string.}
}
\description{
  \code{putenv} sets environment variables (for other processes called
  from within \R or future calls to \code{\link{Sys.getenv}} from this
  \R process).
}
\value{
  A logical vector of the same length as \code{x}, with elements being
  true if setting the corresponding variable succeeded.
}
\details{
  Non-standard \R names must be quoted: see the Examples section.
}
\note{
  Not all systems need support \code{Sys.putenv}.
}
\seealso{
  \code{\link{Sys.getenv}},
  \code{\link{setwd}} for the working directory.
}
\examples{
print(Sys.putenv("R_TEST"="testit", ABC=123))
Sys.getenv("R_TEST")
}
\keyword{environment}
\keyword{utilities}
\eof
\name{qr}
\alias{qr}
\alias{qr.coef}
\alias{qr.qy}
\alias{qr.qty}
\alias{qr.resid}
\alias{qr.fitted}
\alias{qr.solve}
\alias{is.qr}
\alias{as.qr}
\alias{solve.qr}
\title{The QR Decomposition of a Matrix}
\usage{
qr(x, tol = 1e-07 , LAPACK = FALSE)
qr.coef(qr, y)
qr.qy(qr, y)
qr.qty(qr, y)
qr.resid(qr, y)
qr.fitted(qr, y, k = qr$rank)
qr.solve(a, b, tol = 1e-7)
\method{solve}{qr}(a, b, \dots)

is.qr(x)
as.qr(x)
}
\arguments{
  \item{x}{a matrix whose QR decomposition is to be computed.}
  \item{tol}{the tolerance for detecting linear dependencies in the
    columns of \code{x}. Only used if \code{LAPACK} is false and
    \code{x} is real.}
  \item{qr}{a QR decomposition of the type computed by \code{qr}.}
  \item{y, b}{a vector or matrix of right-hand sides of equations.}
  \item{a}{A QR decomposition or (\code{qr.solve} only) a rectangular matrix.}
  \item{k}{effective rank.}
  \item{LAPACK}{logical. For real \code{x}, if true use LAPACK
    otherwise use LINPACK.}
  \item{\dots}{further arguments passed to or from other methods}
}
\description{
  \code{qr} computes the QR decomposition of a matrix.  It provides an
  interface to the techniques used in the LINPACK routine DQRDC 
  or the LAPACK routines DGEQP3 and (for complex matrices) ZGEQP3.
}
\details{
  The QR decomposition plays an important role in many
  statistical techniques.  In particular it can be used to solve the
  equation \eqn{\bold{Ax} = \bold{b}} for given matrix \eqn{\bold{A}},
  and vector \eqn{\bold{b}}.  It is useful for computing regression
  coefficients and in applying the Newton-Raphson algorithm.

  The functions \code{qr.coef}, \code{qr.resid}, and \code{qr.fitted}
  return the coefficients, residuals and fitted values obtained when
  fitting \code{y} to the matrix with QR decomposition \code{qr}.
  \code{qr.qy} and \code{qr.qty} return \code{Q \%*\% y} and
  \code{t(Q) \%*\% y}, where \code{Q} is the \eqn{\bold{Q}} matrix.

  All the above functions keep \code{dimnames} (and \code{names}) of
  \code{x} and \code{y} if there are.

  \code{solve.qr} is the method for \code{solve} for \code{qr} objects.
  \code{qr.solve} solves systems of equations via the QR decomposition:
  if \code{a} is a QR decomposition it is the same as \code{solve.qr},
  but if \code{a} is a rectangular matrix the QR decomposition is
  computed first.  Either will handle over- and under-determined
  systems, providing a minimal-length solution or a least-squares fit
  if appropriate.

  \code{is.qr} returns \code{TRUE} if \code{x} is a \code{\link{list}}
  with components named \code{qr}, \code{rank} and \code{qraux} and
  \code{FALSE} otherwise.

  It is not possible to coerce objects to mode \code{"qr"}.  Objects
  either are QR decompositions or they are not.
}
\value{
  The QR decomposition of the matrix as computed by LINPACK or LAPACK.
  The components in the returned value correspond directly
  to the values returned by DQRDC/DGEQP3/ZGEQP3.
  \item{qr}{a matrix with the same dimensions as \code{x}.
    The upper triangle contains the \eqn{\bold{R}} of the decomposition
    and the lower triangle contains information on the \eqn{\bold{Q}} of
    the decomposition (stored in compact form).  Note that the storage
    used by DQRDC and DGEQP3 differs.}
  \item{qraux}{a vector of length \code{ncol(x)} which contains
    additional information on \eqn{\bold{Q}}.}
  \item{rank}{the rank of \code{x} as computed by the decomposition:
    always full rank in the LAPACK case.}
  \item{pivot}{information on the pivoting strategy used during
    the decomposition.}

  Non-complex QR objects computed by LAPACK have the attribute
  \code{"useLAPACK"} with value \code{TRUE}.
}
\note{
  To compute the determinant of a matrix (do you \emph{really} need it?),
  the QR decomposition is much more efficient than using Eigen values
  (\code{\link{eigen}}).  See \code{\link{det}}.

  Using LAPACK (including in the complex case) uses column pivoting and
  does not attempt to detect rank-deficient matrices.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

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

  Anderson. E. and ten others (1999)
  \emph{LAPACK Users' Guide}. Third Edition. SIAM.\cr
  Available on-line at
  \url{http://www.netlib.org/lapack/lug/lapack_lug.html}.
}
\seealso{
  \code{\link{qr.Q}},  \code{\link{qr.R}},  \code{\link{qr.X}} for
  reconstruction of the matrices.
  \code{\link{solve.qr}},  \code{\link[stats]{lsfit}},
  \code{\link{eigen}}, \code{\link{svd}}.

  \code{\link{det}} (using \code{qr}) to compute the determinant of a matrix.
}
\examples{
hilbert <- function(n) { i <- 1:n; 1 / outer(i - 1, i, "+") }
h9 <- hilbert(9); h9
qr(h9)$rank           #--> only 7
qrh9 <- qr(h9, tol = 1e-10)
qrh9$rank             #--> 9
##-- Solve linear equation system  H \%*\% x = y :
y <- 1:9/10
x <- qr.solve(h9, y, tol = 1e-10) # or equivalently :
x <- qr.coef(qrh9, y) #-- is == but much better than
                      #-- solve(h9) \%*\% y
h9 \%*\% x              # = y
}
\keyword{algebra}
\keyword{array}
\keyword{regression}
\eof
\name{QR.Auxiliaries}
\title{Reconstruct the Q, R, or X Matrices from a QR Object}
\usage{
qr.X(qr, complete = FALSE, ncol =)
qr.Q(qr, complete = FALSE, Dvec =)
qr.R(qr, complete = FALSE)
}
\alias{qr.X}
\alias{qr.Q}
\alias{qr.R}
\arguments{
  \item{qr}{object representing a QR decomposition.  This will
    typically have come from a previous call to \code{\link{qr}} or
    \code{\link[stats]{lsfit}}.}
  \item{complete}{logical expression of length 1.  Indicates whether an
    arbitrary  orthogonal completion of the \eqn{\bold{Q}} or
    \eqn{\bold{X}} matrices is to be made, or whether the \eqn{\bold{R}}
    matrix is to be completed  by binding zero-value rows beneath the
    square upper triangle.}
  \item{ncol}{integer in the range \code{1:nrow(qr$qr)}.  The number
    of columns to be in the reconstructed \eqn{\bold{X}}.  The default
    when \code{complete} is \code{FALSE} is the first
    \code{min(ncol(X), nrow(X))} columns of the original \eqn{\bold{X}}
    from which the qr object was constructed.  The default when
    \code{complete} is \code{TRUE} is a square matrix with the original
    \eqn{\bold{X}} in the first \code{ncol(X)} columns and an arbitrary
    orthogonal completion (unitary completion in the complex case) in
    the remaining columns.}
  \item{Dvec}{vector (not matrix) of diagonal values.  Each column of
    the returned \eqn{\bold{Q}} will be multiplied by the corresponding
    diagonal value.  Defaults to all \code{1}s.}
}
\description{
  Returns the original matrix from which the object was constructed or
  the components of the decomposition.
}
\value{
  \code{qr.X} returns \eqn{\bold{X}}, the original matrix from
  which the qr object was constructed, provided \code{ncol(X) <= nrow(X)}.
  If \code{complete} is \code{TRUE} or the argument \code{ncol} is greater than
  \code{ncol(X)}, additional columns from an arbitrary orthogonal
  (unitary) completion of \code{X} are returned.

  \code{qr.Q} returns \bold{Q}, the order-nrow(X) orthogonal (unitary)
  transformation represented by \code{qr}.  If \code{complete} is
  \code{TRUE}, \bold{Q} has \code{nrow(X)} columns.  If \code{complete}
  is \code{FALSE}, \bold{Q} has \code{ncol(X)} columns.  When
  \code{Dvec} is specified, each column of \bold{Q} is multiplied by the
  corresponding value in \code{Dvec}.

  \code{qr.R} returns \bold{R}, the upper triangular matrix such that
  \code{X == Q \%*\% R}.  The number of rows of \bold{R} is
  \code{nrow(X)} or \code{ncol(X)}, depending on whether \code{complete}
  is \code{TRUE} or \code{FALSE}.
}
\seealso{
  \code{\link{qr}},
  \code{\link{qr.qy}}.
}
\examples{
data(LifeCycleSavings)
p <- ncol(x <- LifeCycleSavings[,-1]) # not the 'sr'
qrstr <- qr(x)   # dim(x) == c(n,p)
qrstr $ rank # = 4 = p
Q <- qr.Q(qrstr) # dim(Q) == dim(x)
R <- qr.R(qrstr) # dim(R) == ncol(x)
X <- qr.X(qrstr) # X == x
range(X - as.matrix(x))# ~ < 6e-12
## X == Q \%*\% R :
Q \%*\% R
}
\keyword{algebra}
\keyword{array}
\eof
\name{quakes}
\docType{data}
\alias{quakes}
\title{Locations of Earthquakes off Fiji}
\description{
  The data set give the locations of 1000 seismic events of MB > 4.0.
  The events occurred in a cube near Fiji since 1964.
}
\usage{data(quakes)}
\format{
  A data frame with 1000 observations on 5 variables.
  \tabular{rlll}{
    [,1] \tab lat      \tab numeric \tab Latitude of event\cr
    [,2] \tab long     \tab numeric \tab Longitude\cr
    [,3] \tab depth    \tab numeric \tab Depth (km)\cr
    [,4] \tab mag      \tab numeric \tab Richter Magnitude\cr
    [,5] \tab stations \tab numeric \tab Number of stations reporting
  }
}
\source{
  This is one of the Harvard PRIM-H project data sets.  They in turn
  obtained it from Dr. John Woodhouse, Dept. of Geophysics, Harvard
  University.
}
\details{
  There are two clear planes of seismic activity.  One is a major plate
  junction; the other is the Tonga trench off New Zealand.  These data
  constitute a subsample from a larger dataset of containing 5000
  observations.
}
\examples{
data(quakes)
pairs(quakes, main = "Fiji Earthquakes, N = 1000", cex.main=1.2, pch=".")
}
\keyword{datasets}
\eof
\name{quit}
\alias{quit}
\alias{q}
\alias{.Last}
\title{Terminate an R Session}
\usage{
quit(save = "default", status = 0, runLast = TRUE)
   q(save = "default", status = 0, runLast = TRUE)
.Last <- function(x) { \dots\dots }
}
\arguments{
    \item{save}{a character string indicating whether the environment
        (workspace) should be saved, one of \code{"no"}, \code{"yes"},
        \code{"ask"} or \code{"default"}.}
    \item{status}{the (numerical) error status to be returned to the
        operating system, where relevant. Conventionally \code{0}
        indicates successful completion.}
    \item{runLast}{should \code{.Last()} be executed?}
}
\description{
    The function \code{quit} or its alias \code{q} terminate the current
    \R session.
}
\details{
    \code{save} must be one of \code{"no"}, \code{"yes"},
    \code{"ask"} or \code{"default"}.  In the first case the workspace
    is not saved, in the second it is saved and in the third the user is
    prompted and can also decide \emph{not} to quit.  The default is to
    ask in interactive use but may be overridden by command-line
    arguments (which must be supplied in non-interactive use).

    Immediately \emph{before} terminating, the function \code{.Last()}
    is executed if it exists and \code{runLast} is true. If in
    interactive use there are errors in
    the \code{.Last} function, control will be returned to the command
    prompt, so do test the function thoroughly.

    Some error statuses are used by \R itself.  The default error
    handler for non-interactive effectively calls \code{q("no", 1,
      FALSE)} and returns error code 1.  Error status 2 is used for \R
    \sQuote{suicide}, that is a catastrophic failure, and other small
    numbers are used by specific ports for initialization failures.  It
    is recommended that users choose statuses of 10 or more.

    Valid values of \code{status} are system-dependent, but \code{0:255}
    are normally valid.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{\code{\link{.First}} for setting things on startup.
}
\examples{
\dontrun{## Unix-flavour example
.Last <- function() {
  cat("Now sending PostScript graphics to the printer:\n")
  system("lpr Rplots.ps")
  cat("bye bye...\n")
}
quit("yes")}
}
\keyword{environment}
\eof
\name{r2dtable}
\alias{r2dtable}
\title{Random 2-way Tables with Given Marginals}
\description{
  Generate random 2-way tables with given marginals using Patefield's
  algorithm.
}
\usage{
r2dtable(n, r, c)
}
\arguments{
  \item{n}{a non-negative numeric giving the number of tables to be
    drawn.}
  \item{r}{a non-negative vector of length at least 2 giving the row
    totals, to be coerced to \code{integer}.  Must sum to the same as
    \code{c}.}
  \item{c}{a non-negative vector of length at least 2 giving the column
    totals, to be coerced to \code{integer}.}
}
\value{
  A list of length \code{n} containing the generated tables as its
  components.
}
\references{
  Patefield, W. M. (1981)
  Algorithm AS159.  An efficient method of generating r x c tables
  with given row and column totals.
  \emph{Applied Statistics} \bold{30}, 91--97.
} 
\examples{
## Fisher's Tea Drinker data.
TeaTasting <-
matrix(c(3, 1, 1, 3),
       nr = 2,
       dimnames = list(Guess = c("Milk", "Tea"),
                       Truth = c("Milk", "Tea")))
## Simulate permutation test for independence based on the maximum
## Pearson residuals (rather than their sum).
rowTotals <- rowSums(TeaTasting)
colTotals <- colSums(TeaTasting)
nOfCases <- sum(rowTotals)
expected <- outer(rowTotals, colTotals, "*") / nOfCases
maxSqResid <- function(x) max((x - expected) ^ 2 / expected)
simMaxSqResid <-
    sapply(r2dtable(1000, rowTotals, colTotals), maxSqResid)
sum(simMaxSqResid >= maxSqResid(TeaTasting)) / 1000
## Fisher's exact test gives p = 0.4857 ...
}
\keyword{distribution}
\eof
\name{randu}
\docType{data}
\alias{randu}
\title{Random Numbers from Congruential Generator RANDU}
\description{
  400 triples of successive random numbers were taken from the VAX
  FORTRAN function RANDU running under VMS 1.5.
}
\usage{data(randu)}
\details{
  In three dimensional displays it is evident that the triples fall on
  15 parallel planes in 3-space. This can be shown theoretically to be
  true for all triples from the RANDU generator.

  These particular 400 triples start 5 apart in the sequence, that is
  they are ((U[5i+1], U[5i+2], U[5i+3]), i= 0, \dots, 399), and they
  are rounded to 6 decimal places.

  Under VMS versions 2.0 and higher, this problem has been fixed.
}
\format{
  A data frame with 400 observations on 3 variables named \code{x},
  \code{y} and \code{z} which give the first, second and third random
  number in the triple.
}
\source{
  David Donoho
}
\examples{
\dontrun{## We could re-generate the dataset by the following R code
seed <- as.double(1)
RANDU <- function() {
    seed <<- ((2^16 + 3) * seed) \%\% (2^31)
    seed/(2^31)
}
for(i in 1:400) {
    U <- c(RANDU(), RANDU(), RANDU(), RANDU(), RANDU())
    print(round(U[1:3], 6))
}}
}
\keyword{datasets}
\eof
\name{range}
\alias{range}
\alias{range.default}
\title{Range of Values}
\usage{
range(\dots, na.rm = FALSE)

\method{range}{default}(\dots, na.rm = FALSE, finite = FALSE)
}
\arguments{
  \item{\dots}{any \code{\link{numeric}} objects.}
  \item{na.rm}{logical, indicating if \code{\link{NA}}'s should be
    omitted.}
  \item{finite}{logical, indicating if all non-finite elements should
    be omitted.}
}
\description{
  \code{range} returns a vector containing the minimum and maximum of
  all the given arguments.
}
\details{
  \code{range} is a generic function: methods can be defined for it
  directly or via the \code{\link{Summary}} group generic.

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

  If \code{finite} is \code{TRUE}, the minimum
  and maximum of all finite values is computed, i.e.,
  \code{finite=TRUE} \emph{includes} \code{na.rm=TRUE}.

  A special situation occurs when there is no (after omission
  of \code{NA}s) nonempty argument left, see \code{\link{min}}.% Extremes.Rd
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{min}},
  \code{\link{max}},
  \code{\link[base]{Methods}}.
}
\examples{
(r.x <- range(rnorm(100)))
diff(r.x) # the SAMPLE range

x <- c(NA, 1:3, -1:1/0); x
range(x)
range(x, na.rm = TRUE)
range(x, finite = TRUE)
}
\keyword{univar}
\keyword{arith}
\eof
\name{rank}
\alias{rank}
\title{Sample Ranks}
\description{
  Returns the sample ranks of the values in a numeric vector.
  Ties, i.e., equal values, result in ranks being averaged, by default.
}
\usage{
rank(x, na.last = TRUE, ties.method = c("average", "first", "random"))
}
\arguments{
  \item{x}{a numeric vector.}
  \item{na.last}{for controlling the treatment of \code{\link{NA}}s.
    If \code{TRUE}, missing values in the data are put last; if
    \code{FALSE}, they are put first; if \code{NA}, they are removed; if
    \code{"keep"} they are kept.}
  \item{ties.method}{a character string specifying how ties are treated,
    see below; can be abbreviated.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\details{
  If all components are different, the ranks are well defined, with
  values in \code{1:n} where \code{n <- length(x)} and we assume no
  \code{NA}s for the moment.  Otherwise, with some values equal, called
  \sQuote{ties}, the argument \code{ties.method} determines
  the result at the corresponding indices.  The \code{"first"} method
  results in a permutation with increasing values at each index set of
  ties.  The \code{"random"} method puts these in random order whereas the
  default, \code{"average"}, replaces them by their mean.
}
\seealso{\code{\link{order}} and \code{\link{sort}}.}
\examples{
(r1 <- rank(x1 <- c(3, 1, 4, 15, 92)))
x2 <- c(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5)
names(x2) <- letters[1:11]
(r2 <- rank(x2)) # ties are averaged

## rank() is "idempotent": rank(rank(x)) == rank(x) :
stopifnot(rank(r1) == r1, rank(r2) == r2)

## ranks without averaging
rank(x2, ties.method= "first")  # first occurrence wins
rank(x2, ties.method= "random") # ties broken at random
rank(x2, ties.method= "random") # and again
}
\keyword{univar}
\eof
\name{read.00Index}
\alias{read.00Index}
\title{Read 00Index-style Files}
\description{
  Read item/description information from 00Index-style files.  Such
  files are description lists rendered in tabular form, and currently
  used for the object, data and demo indices and \file{TITLE} files of
  add-on packages.
}
\usage{
read.00Index(file)
}
\arguments{
  \item{file}{the name of a file to read data values from.  If the
    specified file is \code{""}, then input is taken from the keyboard
    (in this case input can be terminated by a blank line).
    Alternatively, \code{file} can be a \code{\link{connection}}, which
    will be opened if necessary, and if so closed at the end of the
    function call.}
}
\value{
  a character matrix with 2 columns named \code{"Item"} and
  \code{"Description"} which hold the items and descriptions.
}
\seealso{
  \code{\link{formatDL}} for the inverse operation of creating a
  00Index-style file from items and their descriptions.
}
\keyword{file}
\keyword{connection}
\eof
\name{read.table}
\alias{read.table}
\alias{read.csv}
\alias{read.csv2}
\alias{read.delim}
\alias{read.delim2}
\title{Data Input}
\description{
  Reads a file in table format and creates a data frame from it, with
  cases corresponding to lines and variables to fields in the file.
}
\usage{
read.table(file, header = FALSE, sep = "", quote = "\"'", dec = ".",
           row.names, col.names, as.is = FALSE, na.strings = "NA",
           colClasses = NA, nrows = -1,
           skip = 0, check.names = TRUE, fill = !blank.lines.skip,
           strip.white = FALSE, blank.lines.skip = TRUE,
           comment.char = "#")

read.csv(file, header = TRUE, sep = ",", quote="\"", dec=".",
         fill = TRUE, \dots)

read.csv2(file, header = TRUE, sep = ";", quote="\"", dec=",",
         fill = TRUE, \dots)

read.delim(file, header = TRUE, sep = "\t", quote="\"", dec=".",
         fill = TRUE, \dots)

read.delim2(file, header = TRUE, sep = "\t", quote="\"", dec=",",
         fill = TRUE, \dots)
}
\arguments{
  \item{file}{the name of the file which the data are to be read from.
    Each row of the table appears as one line of the file.  If it does
    not contain an \emph{absolute} path, the file name is
    \emph{relative} to the current working directory,
    \code{\link{getwd}()}. Tilde-expansion is performed where supported.

    Alternatively, \code{file} can be a \code{\link{connection}}, which
    will be opened if necessary, and if so closed at the end of the
    function call.  (If \code{stdin()} is used, the prompts for lines
    may be somewhat confusing.  Terminate input with an EOF
    signal, \code{Ctrl-D} on Unix and \code{Ctrl-Z} on Windows.)

    \code{file} can also be a complete URL.
  }

  \item{header}{a logical value indicating whether the file contains the
    names of the variables as its first line.  If missing, the value is
    determined from the file format: \code{header} is set to \code{TRUE}
    if and only if the first row contains one fewer field than the
    number of columns.}

  \item{sep}{the field separator character.  Values on each line of the
    file are separated by this character.  If \code{sep = ""} (the
    default for \code{read.table}) the separator is \dQuote{white space},
    that is one or more spaces, tabs or newlines.}

  \item{quote}{the set of quoting characters. To disable quoting
    altogether, use \code{quote=""}.  See \code{\link{scan}} for the
    behaviour on quotes embedded in quotes.}

  \item{dec}{the character used in the file for decimal points.}

  \item{row.names}{a vector of row names.  This can be a vector giving
    the actual row names, or a single number giving the column of the
    table which contains the row names, or character string giving the
    name of the table column containing the row names.

    If there is a header and the first row contains one fewer field than
    the number of columns, the first column in the input is used for the
    row names.  Otherwise if \code{row.names} is missing, the rows are
    numbered.

    Using \code{row.names = NULL} forces row numbering.
  }

  \item{col.names}{a vector of optional names for the variables.
    The default is to use \code{"V"} followed by the column number.}

  \item{as.is}{the default behavior of \code{read.table} is to convert
    character variables (which are not converted to logical, numeric or
    complex) to factors.  The variable \code{as.is}
    controls this conversion.  Its value is either a vector of logicals
    (values are recycled if necessary), or a vector of numeric or
    character indices which specify which columns should not be
    converted to factors.

    Note: to suppress all conversions including those of numeric
    columns, set \code{colClasses = "character"}.
  }

  \item{na.strings}{a vector of strings which are to be interpreted as
    \code{\link{NA}} values.  Blank fields are also considered to be
    missing values.}

  \item{colClasses}{character.  A vector of classes to be assumed for
    the columns.  Recycled as necessary.  If this is not one of the
    atomic vector classes (logical, integer, numeric, complex and
    character), there needs to be an \code{as} method for
    conversion from \code{"character"} to the specified class, or
    \code{NA} when \code{\link{type.convert}} is used.  NB: \code{as} is
    in package \pkg{methods}.}

  \item{nrows}{the maximum number of rows to read in.  Negative values
    are ignored.}

  \item{skip}{the number of lines of the data file to skip before
    beginning to read data.}

  \item{check.names}{logical.  If \code{TRUE} then the names of the
    variables in the data frame are checked to ensure that they are
    syntactically valid variable names.  If necessary they are adjusted
    (by \code{\link{make.names}}) so that they are, and also to ensure
    that there are no duplicates.}

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

  \item{strip.white}{logical. Used only when \code{sep} has
    been specified, and allows the stripping of leading and trailing
    white space from \code{character} fields (\code{numeric} fields
    are always stripped).  See \code{\link{scan}} for further details,
    remembering that the columns may include the row names.}

  \item{blank.lines.skip}{logical: if \code{TRUE} blank lines in the
    input are ignored.}
  
  \item{comment.char}{character: a character vector of length one
    containing a single character or an empty string.  Use \code{""} to
    turn off the interpretation of comments altogether.}

  \item{\dots}{Further arguments to \code{read.table}.}
}
\value{
  A data frame (\code{\link{data.frame}}) containing a representation of
  the data in the file.  Empty input is an error unless \code{col.names}
  is specified, when a 0-row data frame is returned: similarly giving
  just a header line if \code{header = TRUE} results in a 0-row data frame.

  This function is the principal means of reading tabular data into \R.
}
\details{
  If \code{row.names} is not specified and the header line has one less
  entry than the number of columns, the first column is taken to be the
  row names.  This allows data frames to be read in from the format in
  which they are printed.  If \code{row.names} is specified and does
  not refer to the first column, that column is discarded from such files.

  The number of data columns is determined by looking at the first five lines
  of input (or the whole file if it has less than five lines), or from
  the length of \code{col.names} if it is specified and
  is longer.  This could conceivably be wrong if \code{fill} or
  \code{blank.lines.skip} are true, so specify \code{col.names} if necessary.
  
  \code{read.csv} and \code{read.csv2} are identical to
  \code{read.table} except for the defaults.  They are intended for
  reading \dQuote{comma separated value} files (\file{.csv}) or the variant
  used in countries that use a comma as decimal point and a semicolon
  as field separator.  Similarly, \code{read.delim} and
  \code{read.delim2} are for reading delimited files, defaulting to the
  TAB character for the delimiter.  Notice that \code{header = TRUE} and
  \code{fill = TRUE} in these variants.

  The rest of the line after a comment character is skipped; quotes
  are not processed in comments.  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.

  As from \R 1.9.0 quoted fields with embedded newlines are supported
  except after a comment character.
}
\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[utils]{read.fwf}} for reading \emph{f}ixed \emph{w}idth
  \emph{f}ormatted input;
  \code{\link{write.table}};
  \code{\link{data.frame}}.

  \code{\link{count.fields}} can be useful to determine problems with
  reading files which result in reports of incorrect record lengths.
}
\references{
  Chambers, J. M. (1992)
  \emph{Data for models.}
  Chapter 3 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\keyword{file}
\keyword{connection}
\eof
\name{readBin}
\alias{readBin}
\alias{writeBin}
\alias{readChar}
\alias{writeChar}
\title{Transfer Binary Data To and From Connections}
\description{
  Read binary data from a connection, or write binary data to a connection.
}
\usage{
readBin(con, what, n = 1, size = NA, signed = TRUE,
        endian = .Platform$endian)
writeBin(object, con, size = NA, endian = .Platform$endian)

readChar(con, nchars)
writeChar(object, con, nchars = nchar(object), eos = "")
}
\arguments{
  \item{con}{A connection object or a character string.}
  \item{what}{Either an object whose mode will give the mode of the
    vector to be read, or a character vector of length one describing
    the mode: one of \code{"numeric", "double", "integer", "int",
      "logical", "complex", "character"}.}
  \item{n}{integer.  The (maximal) number of records to be
    read. You can use an over-estimate here, but not too large as
    storage is reserved for \code{n} items.}
  \item{size}{integer.  The number of bytes per element in the byte
    stream.  The default, \code{NA}, uses the natural size.  Size changing
    is not supported for complex vectors.}
  \item{signed}{logical. Only used for integers of sizes 1 and 2,
    when it determines if the quantity on file
    should be regarded as a signed or unsigned integer.}
  \item{endian}{The endian-ness (\code{"big"} or \code{"little"} of the
    target system for the file.  Using \code{"swap"} will force swapping
    endian-ness.}
  \item{object}{An \R object to be written to the connection.}
  \item{nchars}{integer, giving the lengths of (unterminated) character
    strings to be read or written.}
  \item{eos}{character. The terminator to be written after each string,
    followed by an ASCII \code{nul}; use \code{NULL} for no terminator
    at all.}
}
\details{
  If the \code{con} is a character string, the functions call
  \code{\link{file}} to obtain an file connection which is opened for
  the duration of the function call.

  If the connection is open it is read/written from its current position.
  If it is not open, it is opened for the duration of the call and then
  closed again.

  If \code{size} is specified and not the natural size of the object,
  each element of the vector is coerced to an appropriate type before
  being written or as it is read.  Possible sizes are 1, 2, 4 and
  possibly 8 for integer or logical vectors, and 4, 8 and possibly 12/16
  for numeric vectors.  (Note that coercion occurs as signed types
  except if \code{signed = FALSE} when reading integers of sizes 1 and 2.)
  Changing sizes is unlikely to preserve \code{NA}s, and the extended
  precision sizes are unlikely to be portable across platforms.

  \code{readBin} and \code{writeBin} read and write C-style
  zero-terminated character strings. Input strings are limited to 10000
  characters.  \code{readChar} and \code{writeChar} allow more
  flexibility, and can also be used on text-mode connections.

  Handling \R's missing and special (\code{Inf}, \code{-Inf} and
  \code{NaN}) values is discussed in the \emph{R Data Import/Export} manual.
}

\note{
  Integer read/writes of size 8 will be available if either C type
  \code{long} is of size 8 bytes or C type \code{long long} exists and
  is of size 8 bytes.

  Real read/writes of size \code{sizeof(long double)} (usually 12 or 16
  bytes) will be available only if that type is available and different
  from \code{double}.

  Note that as \R character strings cannot contain ASCII \code{nul},
  strings read by \code{readChar} which contain such characters will
  appear to be shorter than requested, but the additional bytes are read
  from the file.

  If the character length requested for \code{readChar} is longer than
  the data available on the connection, what is available is returned.
  For \code{writeChar} if too many characters are requested the output
  is zero-padded, with a warning.

  If \code{readBin(what=character())} is used incorrectly on a file which
  does not contain C-style character strings, warnings (usually
  many) are  given as from version 1.6.2.  The input will be broken into
  pieces of length 10000 with any final part being discarded.
}

\value{
  For \code{readBin}, a vector of appropriate mode and length the number of
  items read (which might be less than \code{n}).

  For \code{readChar}, a character vector of length the number of
  items read (which might be less than \code{length(nchars)}).

  For \code{writeBin} and \code{writeChar}, none.
}
\seealso{
  The \emph{R Data Import/Export} manual.

  \code{\link{connections}}, \code{\link{readLines}},
  \code{\link{writeLines}}.

  \code{\link{.Machine}} for the sizes of \code{long}, \code{long long}
  and \code{long double}.
}
\examples{
zz <- file("testbin", "wb")
writeBin(1:10, zz)
writeBin(pi, zz, endian="swap")
writeBin(pi, zz, size=4)
writeBin(pi^2, zz, size=4, endian="swap")
writeBin(pi+3i, zz)
writeBin("A test of a connection", zz)
z <- paste("A very long string", 1:100, collapse=" + ")
writeBin(z, zz)
if(.Machine$sizeof.long == 8 || .Machine$sizeof.longlong == 8)
    writeBin(as.integer(5^(1:10)), zz, size = 8)
if((s <-.Machine$sizeof.longdouble) > 8) writeBin((pi/3)^(1:10), zz, size = s)
close(zz)

zz <- file("testbin", "rb")
readBin(zz, integer(), 4)
readBin(zz, integer(), 6)
readBin(zz, numeric(), 1, endian="swap")
readBin(zz, numeric(), size=4)
readBin(zz, numeric(), size=4, endian="swap")
readBin(zz, complex(), 1)
readBin(zz, character(), 1)
z2 <- readBin(zz, character(), 1)
if(.Machine$sizeof.long == 8 || .Machine$sizeof.longlong == 8)
    readBin(zz, integer(), 10,  size = 8)
if((s <-.Machine$sizeof.longdouble) > 8) readBin(zz, numeric(), 10, size = s)
close(zz)
unlink("testbin")
stopifnot(z2 == z)

## test fixed-length strings
zz <- file("testbin", "wb")
x <- c("a", "this will be truncated", "abc")
nc <- c(3, 10, 3)
writeChar(x, zz, nc, eos=NULL)
writeChar(x, zz, eos="\r\n")
close(zz)

zz <- file("testbin", "rb")
readChar(zz, nc)
readChar(zz, nchar(x)+3) # need to read the terminator explicitly
close(zz)
unlink("testbin")

## signed vs unsigned ints
zz <- file("testbin", "wb")
x <- as.integer(seq(0, 255, 32))
writeBin(x, zz, size=1)
writeBin(x, zz, size=1)
x <- as.integer(seq(0, 60000, 10000))
writeBin(x, zz, size=2)
writeBin(x, zz, size=2)
close(zz)
zz <- file("testbin", "rb")
readBin(zz, integer(), 8, size=1)
readBin(zz, integer(), 8, size=1, signed=FALSE)
readBin(zz, integer(), 7, size=2)
readBin(zz, integer(), 7, size=2, signed=FALSE)
close(zz)
unlink("testbin")
}
\keyword{file}
\keyword{connection}
\eof
\name{readLines}
\alias{readLines}
\title{Read Text Lines from a Connection}
\description{
  Read text lines from a connection.
}
\usage{
readLines(con = stdin(), n = -1, ok = TRUE)
}
\arguments{
  \item{con}{A connection object or a character string.}
  \item{n}{integer.  The (maximal) number of lines to
    read. Negative values indicate that one should read up to the end of
    the connection.}
  \item{ok}{logical. Is it OK to reach the end of the connection before
    \code{n > 0} lines are read? If not, an error will be generated.}
}
\details{
  If the \code{con} is a character string, the functions call
  \code{\link{file}} to obtain an file connection which is opened for
  the duration of the function call.

  If the connection is open it is read from its current position.
  If it is not open, it is opened for the duration of the call and then
  closed again.

  If the final line is incomplete (no final EOL marker) the behaviour
  depends on whether the connection is blocking or not. For a blocking
  text-mode connection (or a non-text-mode connection) the line
  will be accepted, with a warning.  For a non-blocking text-mode
  connection the incomplete line is pushed back, silently.

  Whatever mode the connection is opened in, any of LF, CRLF or CR will
  be accepted as the EOL marker for a line.
}
\value{
  A character vector of length the number of lines read.
}
\seealso{
  \code{\link{connections}}, \code{\link{writeLines}}, \code{\link{readBin}},
  \code{\link{scan}}}

\examples{
cat("TITLE extra line", "2 3 5 7", "", "11 13 17", file="ex.data",
    sep="\n")
readLines("ex.data", n=-1)
unlink("ex.data") # tidy up

## difference in blocking
cat("123\nabc", file = "test1")
readLines("test1") # line with a warning

con <- file("test1", "r", blocking = FALSE)
readLines(con) # empty
cat(" def\n", file = "test1", append = TRUE)
readLines(con) # gets both
close(con)

unlink("test1") # tidy up
}
\keyword{file}
\keyword{connection}
\eof
\name{readline}
\title{Read a Line from the Terminal}
\usage{
readline(prompt = "")
}
\alias{readline}
\arguments{
  \item{prompt}{the string printed when prompting the user for input.
  Should usually end with a space \code{" "}.}
}
\description{
  \code{readline} reads a line from the terminal
}
\details{
  The prompt string will be truncated to a maximum allowed length,
  normally 256 chars (but can be changed in the source code).
}
\value{
  A character vector of length one.
}
\examples{
fun <- function() {
  ANSWER <- readline("Are you a satisfied R user? ")
  if (substr(ANSWER, 1, 1) == "n")
    cat("This is impossible.  YOU LIED!\n")
  else
    cat("I knew it.\n")
}
fun()
}
\keyword{utilities}
\eof
\name{real}
\title{Real Vectors}
\alias{real}
\alias{as.real}
\alias{is.real}
\usage{
real(length = 0)
as.real(x, \dots)
is.real(x)
}
\description{
  \code{real} creates a double precision vector of the specified
  length. Each element of the vector is equal to \code{0}.

  \code{as.real} attempts to coerce its argument to be of real type.

  \code{is.real} returns \code{TRUE} or \code{FALSE} depending on
  whether its argument is of real type or not.
}
\arguments{
  \item{length}{desired length.}
  \item{x}{object to be coerced or tested.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\note{
  \emph{\R has no single precision data type.
    All real numbers are stored in double precision format}.
}
\keyword{classes}
\eof
\name{reg.finalizer}
\alias{reg.finalizer}
\title{Finalization of objects}
\description{
  Registers an \R function to be called upon garbage collection of
  object.
}
\usage{
  reg.finalizer(e, f)
}
\arguments{
  \item{e}{Object to finalize. Must be environment or external pointer.}
  \item{f}{Function to call on finalization. Must accept a single argument, 
    which will be the object to finalize.}
}
\value{
  \code{NULL}.
}
\note{
  The purpose of this function is mainly to allow objects that refer to
  external items (a temporary file, say) to perform cleanup actions when
  they are no longer referenced from within \R.  This only makes sense
  for objects that are never copied on assignment, hence the restriction
  to environments and external pointers.
}
\examples{
f <- function(e) print("cleaning....")
g <- function(x){e<-environment(); reg.finalizer(e,f)}
g() 
invisible(gc()) # trigger cleanup
}
\keyword{programming}
\eof
\name{regex}
\alias{regex}
\alias{regexp}
\alias{regular expression}
\concept{regular expression}
\title{Regular Expressions as used in R}
\description{
  This help page documents the regular expression patterns supported by
  \code{\link{grep}} and related functions \code{regexpr}, \code{sub}
  and \code{gsub}, as well as by \code{\link{strsplit}}.
}
\details{
  A \sQuote{regular expression} is a pattern that describes a set of
  strings.  Three types of regular expressions are used in \R,
  \emph{extended} regular expressions, used by
  \code{grep(extended = TRUE)} (its default), \emph{basic} regular
  expressions, as used by \code{grep(extended = FALSE)}, and
  \emph{Perl-like} regular expressions used by \code{grep(perl = TRUE)}.

  Other functions which use regular expressions (often via the use of
  \code{grep}) include \code{apropos}, \code{browseEnv},
  \code{help.search}, \code{list.files}, \code{ls} and \code{strsplit}.
  These will all use \emph{extended} regular expressions, unless
  \code{strsplit} is called with argument \code{extended = FALSE} or
  \code{perl = TRUE}.

  Patterns are described here as they would be printed by \code{cat}: do
  remember that backslashes need to be doubled in entering \R character
  strings from the keyboard.
}
\section{Extended Regular Expressions}{
  This section covers the regular expressions allowed
  if \code{extended = TRUE} in \code{grep}, \code{regexpr}, \code{sub},
  \code{gsub} and \code{strsplit}.  They use the GNU implementation of
  the POSIX 1003.2 standard.

  Regular expressions are constructed analogously to arithmetic
  expressions, by using various operators to combine smaller expressions.

  The fundamental building blocks are the regular expressions that match
  a single character.  Most characters, including all letters and
  digits, are regular expressions that match themselves.  Any
  metacharacter with special meaning may be quoted by preceding it with
  a backslash.  The metacharacters are \code{. \\ | ( ) [ \{ ^ $ * + ?}.

  A \emph{character class} is a list of characters enclosed by \code{[}
  and \code{]} matches any single character in that list; if the first
  character of the list is the caret \code{^}, then it matches any
  character \emph{not} in the list.  For example, the regular expression
  \code{[0123456789]} matches any single digit, and \code{[^abc]} matches
  anything except the characters \code{a}, \code{b} or \code{c}.  A range
  of characters may be specified by giving the first and last characters,
  separated by a hyphen.  (Character ranges are interpreted in the
  collation order of the current locale.)

  Certain named classes of characters are predefined.  Their
  interpretation depends on the \emph{locale} (see \link{locales}); the
  interpretation below is that of the POSIX locale.

  \describe{
    \item{\code{[:alnum:]}}{Alphanumeric characters: \code{[:alpha:]}
      and \code{[:digit:]}.}

    \item{\code{[:alpha:]}}{Alphabetic characters: \code{[:lower:]} and
      \code{[:upper:]}.}

    \item{\code{[:blank:]}}{Blank characters: space and tab.}

    \item{\code{[:cntrl:]}}{
      Control characters.  In ASCII, these characters have octal codes
      000 through 037, and 177 (\code{DEL}).  In another character set,
      these are the equivalent characters, if any.}

    \item{\code{[:digit:]}}{Digits: \code{0 1 2 3 4 5 6 7 8 9}.}

    \item{\code{[:graph:]}}{Graphical characters: \code{[:alnum:]} and
      \code{[:punct:]}.}

    \item{\code{[:lower:]}}{Lower-case letters in the current locale.}

    \item{\code{[:print:]}}{
      Printable characters: \code{[:alnum:]}, \code{[:punct:]} and space.}

    \item{\code{[:punct:]}}{Punctuation characters:
      \code{! " # $ \% & ' ( ) * + , - . / : ; < = > ? @ [ \\ ] ^ _ ` \{ | \} ~}.}
%'"`  keep Emacs Rd mode happy

    \item{\code{[:space:]}}{
      Space characters: tab, newline, vertical tab, form feed, carriage
      return, and space.}

    \item{\code{[:upper:]}}{Upper-case letters in the current locale.}

    \item{\code{[:xdigit:]}}{Hexadecimal digits:
      \code{0 1 2 3 4 5 6 7 8 9 A B C D E F a b c d e f}.}
  }

  For example, \code{[[:alnum:]]} means \code{[0-9A-Za-z]}, except the
  latter depends upon the locale and the character encoding, whereas
  the former is independent of locale and character set.  (Note that the
  brackets in these class names are part of the symbolic names, and must
  be included in addition to the brackets delimiting the bracket list.)
  Most metacharacters lose their special meaning inside lists.  To
  include a literal \code{]}, place it first in the list.  Similarly, to
  include a literal \code{^}, place it anywhere but first.  Finally, to
  include a literal \code{-}, place it first or last. (Only these and
  \code{\\} remain special inside character classes.)

  The period \code{.} matches any single character.  The symbol
  \code{\\w} is documented to be synonym for \code{[[:alnum:]]} and
  \code{\\W} is its negation.  However, \code{\\w} also
  matches underscore in the GNU grep code used in \R.

  The caret \code{^} and the dollar sign \code{$} are metacharacters
  that respectively match the empty string at the beginning and end of a
  line.  The symbols \code{\\<} and \code{\\>} respectively match the
  empty string at the beginning and end of a word.  The symbol \code{\\b}
  matches the empty string at the edge of a word, and \code{\\B} matches
  the empty string provided it is not at the edge of a word.

  A regular expression may be followed by one of several repetition
  quantifiers:
  \describe{
    \item{\code{?}}{The preceding item is optional and will be matched
      at most once.}

    \item{\code{*}}{The preceding item will be matched zero or more
      times.}

    \item{\code{+}}{The preceding item will be matched one or more
      times.}

    \item{\code{{n}}}{The preceding item is matched exactly \code{n}
      times.}

    \item{\code{{n,}}}{The preceding item is matched \code{n} or more
      times.}

    \item{\code{{n,m}}}{The preceding item is matched at least \code{n}
      times, but not more than \code{m} times.}
  }
  Repetition is greedy, so the maximal possible number of repeats is used.

  Two regular expressions may be concatenated; the resulting regular
  expression matches any string formed by concatenating two substrings
  that respectively match the concatenated subexpressions.

  Two regular expressions may be joined by the infix operator \code{|};
  the resulting regular expression matches any string matching either
  subexpression.   For example, \code{abba|cde} matches either the
  string \code{abba} or the string \code{cde}.  Note that alternation
  does not work inside character classes, where \code{|} has its literal
  meaning.

  Repetition takes precedence over concatenation, which in turn takes
  precedence over alternation.  A whole subexpression may be enclosed in
  parentheses to override these precedence rules.

  The backreference \code{\\N}, where N is a single digit, matches the
  substring previously matched by the Nth parenthesized subexpression of
  the regular expression.

  The current code attempts to support traditional usage by assuming
  that \code{\{} is not special if it would be the start of an invalid
  interval specification.  (POSIX allows this behaviour as an extension but
  we advise users not to rely on it.)
}
\section{Basic Regular Expressions}{
  This section covers the regular expressions allowed if
  \code{extended = FALSE} in \code{grep}, \code{regexpr}, \code{sub},
  \code{gsub} and \code{strsplit}.

  In basic regular expressions the metacharacters \code{?}, \code{+},
  \code{\{}, \code{|}, \code{(}, and \code{)} lose their special meaning;
  instead use the backslashed versions \code{\\?}, \code{\\+},
  \code{\\ \{}, \code{\\|}, \code{\\(}, and \code{\\)}.  Thus the
  metacharacters are \code{. \\ [ ^ $ *}.
}
\section{Perl Regular Expressions}{
  The \code{perl = TRUE} argument to \code{grep}, \code{regexpr}, \code{sub},
  \code{gsub} and \code{strsplit} switches to the PCRE library that
  \sQuote{implements regular expression pattern matching using the same
    syntax and semantics as Perl 5.6 or later, with just a few differences}.

  For complete details please consult the man pages for PCRE, especially
  \code{man pcrepattern} and \code{man pcreapi}) on your system or from
  the sources at
  \url{ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/}. If PCRE
  support was compiled from the sources within \R, the PCRE version is 4.5
  as described here (version \eqn{\ge}{>=} 4.0 is required even if \R is
  configured to use the system's PCRE library).

  All the regular expressions described for extended regular expressions
  are accepted except \code{\\<} and \code{\\>}: in Perl all backslashed
  metacharacters are alphanumeric and backslashed symbols always are
  interpreted as a literal character. \code{\{} is not special if it would
  be the start of an invalid interval specification.  There can be more than
  9 backreferences.

  The construct \code{(?...)} is used for Perl extensions in a variety
  of ways depending on what immediately follows the \code{?}.

  Perl-like matching can work in several modes, set by the options
  \code{(?i)} (caseless, equivalent to Perl's \code{/i}), \code{(?m)}
  (multiline, equivalent to Perl's \code{/m}), \code{(?s)} (single line,
  so a dot matches all characters, even new lines: equivalent to Perl's
  \code{/s}) and \code{(?x)} (extended, whitespace data characters are
  ignored unless escaped and comments are allowed: equivalent to Perl's
  \code{/x}).  These can be concatenated, so for example, \code{(?im)}
  sets caseless multiline matching.  It is also possible to unset these
  options by preceding the letter with a hyphen, and to combine setting
  and unsetting such as \code{(?im-sx)}.  These settings can be applied
  within patterns, and then apply to the remainder of the pattern.
  Additional options not in Perl include \code{(?U)} to set
  \sQuote{ungreedy} mode (so matching is minimal unless \code{?} is used,
  when it is greedy).  Initially none of these options are set.

  If you want to remove the special meaning from a sequence of
  characters, you can do so by putting them between \code{\\Q} and
  \code{\\E}. This is different from Perl in that \code{$} and \code{@} are
  handled as literals in \code{\\Q...\\E} sequences in PCRE, whereas in
  Perl, \code{$} and \code{@} cause variable interpolation.

  The escape sequences \code{\\d}, \code{\\s} and \code{\\w} represent any
  decimal digit, space character and \sQuote{word} character
  (letter, digit or underscore in the current locale) respectively, and
  their upper-case versions represent their negation.
  Unlike POSIX and earlier versions of Perl and PCRE, vertical tab is
  not regarded as a whitespace character.

  Escape sequence \code{\\a} is \code{BEL}, \code{\\e} is \code{ESC},
  \code{\\f} is \code{FF}, \code{\\n} is \code{LF}, \code{\\r} is
  \code{CR} and \code{\\t} is \code{TAB}.  In addition \code{\\cx} is
  \code{cntrl-x} for any \code{x}, \code{\\ddd} is the octal character
  \code{ddd} (for up to three digits unless interpretable as a
  backreference), and \code{\\xhh} specifies a character in hex.

  Outside a character class, \code{\\b} matches a word boundary,
  \code{\\B} is its negation, \code{\\A} matches at start of a subject (even
  in multiline mode, unlike \code{^}), \code{\\Z} matches at end of a
  subject or before newline at end, \code{\\z} matches at end of a
  subject. and \code{\\G} matches at first matching position in a
  subject. \code{\\C} matches a single byte. including a newline.

  The same repetition quantifiers as extended POSIX are supported.
  However, if a quantifier is followed by \code{?}, the match is
  \sQuote{ungreedy}, that is as short as possible rather than as long as
  possible (unless the meanings are reversed by the \code{(?U)} option.)

  The sequence \code{(?#} marks the start of a comment which continues
  up to the next closing parenthesis.  Nested parentheses are not
  permitted.  The characters that make up a comment play no part at all in
  the pattern matching.

  If the extended option is set, an unescaped \code{#} character outside
  a character class introduces a comment that continues up to the next
  newline character in the pattern.

  The pattern \code{(?:...)} groups characters just as parentheses do
  but does not make a backreference.

  Patterns \code{(?=...)} and \code{(?!...)} are zero-width positive and
  negative lookahead \emph{assertions}: they match if an attempt to
  match the \code{\dots} forward from the current position would succeed
  (or not), but use up no characters in the string being processed.
  Patterns \code{(?<=...)} and \code{(?<!...)} are the lookbehind
  equivalents: they do not allow repetition quantifiers nor \code{\\C}
  in \code{\dots}.

  Named subpatterns, atomic grouping, possessive qualifiers and conditional
  and recursive patterns are not covered here.
}
\author{
  This help page is based on the documentation of GNU grep 2.4.2, from
  which the C code used by \R has been taken, the \code{pcre} man
  page from PCRE 3.9 and the \code{pcrepattern} man page from PCRE 4.4.
}
\seealso{
  \code{\link{grep}}, \code{\link[utils]{apropos}}, \code{\link[utils]{browseEnv}},
  \code{\link[utils]{help.search}}, \code{\link{list.files}},
  \code{\link{ls}} and \code{\link{strsplit}}.
}
\keyword{character}
\eof
\name{rep}
\alias{rep}
\alias{rep.default}
\alias{rep.int}
\alias{rep.POSIXct}
\alias{rep.POSIXlt}
\alias{rep.Date}
\title{Replicate Elements of Vectors and Lists}
\description{
  \code{rep} replicates the values in \code{x}. It is a generic
  function, and the default method is described here.

  \code{rep.int} is a faster simplified version for the commonest case.
}
\usage{
rep(x, times, \dots)

\method{rep}{default}(x, times, length.out, each, \dots)

rep.int(x, times)
}
\arguments{
  \item{x}{a vector (of any mode including a list) or a pairlist or a
    \code{POSIXct} or \code{POSIXlt} or \code{date} object.}
  \item{times}{optional non-negative integer.  A vector giving the number of
    times to repeat each element if of length \code{length(x)}, or to
    repeat the whole vector if of length 1.}
  \item{length.out}{optional integer. The desired length of the
    output vector.}
  \item{each}{optional integer. Each element of \code{x} is
    repeated \code{each} times.}
  \item{\dots}{further arguments to be passed to or from other methods.}
}

\details{
  A least one of \code{times}, \code{length.out} and \code{each} must be
  specified, and normally exactly one is.  If \code{length.out} is
  given, \code{times} is ignored. If \code{each} is specified with
  either of the other two, its replication is performed first, and then
  that implied by \code{times} or \code{length.out}.
  
  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.

  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.

  If \code{x} has length zero and \code{length.out} is supplied and is
  positive, the values are filled in using the extraction rules, that is
  by an \code{NA} of the appropriate class for an atomic vector and
  \code{NULL} for a list.  
}
\value{
  A vector of the same class as \code{x}.
}
\note{
  If the original vector has names, these are also replicated and so
  will almost always contain duplicates.  (In contrast, S strips the names.)
%
%  If \code{length.out} is used to extend the vector, the behaviour is
%  different from that of S-PLUS, which recycles the existing vector.

  Function \code{rep.int} is a simple case handled by internal code, and
  provided as a separate function purely for S compatibility.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{seq}}, \code{\link{sequence}}.
}
\examples{
rep(1:4, 2)
rep(1:4, each = 2)       # not the same.
rep(1:4, c(2,2,2,2))     # same as second.
rep(1:4, c(2,1,2,1))
rep(1:4, each = 2, len = 4)    # first 4 only.
rep(1:4, each = 2, len = 10)   # 8 integers plus two recycled 1's.
rep(1:4, each = 2, times = 3)  # length 24, 3 complete replications

rep(1, 40*(1-.8)) # length 7 on most platforms
rep(1, 40*(1-.8)+1e-7) # better

## replicate a list
fred <- list(happy = 1:10, name = "squash")
rep(fred, 5)

# date-time objects
x <- .leap.seconds[1:3]
rep(x, 2)
rep(as.POSIXlt(x), rep(2, 3))
}
\keyword{manip}
\keyword{chron}
\eof
\name{replace}
\title{Replace Values in a Vector}
\usage{
replace(x, list, values)
}
\alias{replace}
\description{
\code{replace} replaces the values in \code{x}
with indexes given in \code{list} by those given in \code{values}.
If necessary, the values in \code{values} are recycled.
}
\arguments{
  \item{x}{vector}
  \item{list}{an index vector}
  \item{values}{replacement values}
}
\value{
  A vector with the values replaced.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\note{
  \code{x} is unchanged: remember to assign the result.
}
\keyword{manip}
\eof
\name{rev}
\alias{rev}
\alias{rev.default}
\title{Reverse Elements}
\usage{
rev(x)
\method{rev}{default}(x)
}
\arguments{
  \item{x}{a vector or another object for which reversion is defined.}
}
\description{
  \code{rev} provides a reversed version of its argument.  It is generic
  function with a default method for vectors and one for
  \code{\link[stats]{dendrogram}}s.

  Note that this is no longer needed (nor efficient) for obtaining
  vectors sorted into descending order, since that is now rather more
  directly achievable by \code{\link{sort}(x, decreasing=TRUE)}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{\code{\link{seq}}, \code{\link{sort}}.}
\examples{
x <- c(1:5,5:3)
## sort into descending order; first more efficiently:
stopifnot(sort(x, decreasing = TRUE) == rev(sort(x)))
stopifnot(rev(1:7) == 7:1)#- don't need 'rev' here
}
\keyword{manip}
\eof
\name{rivers}
\docType{data}
\alias{rivers}
\title{Lengths of Major North American Rivers}
\description{
  This data set gives the lengths (in miles) of 141 \dQuote{major}
  rivers in North America, as compiled by the US Geological Survey.
}
\usage{data(rivers)}
\format{A vector containing 141 observations.}
\source{World Almanac and Book of Facts, 1975, page 406.}
\references{
  McNeil, D. R. (1977) \emph{Interactive Data Analysis}.
  New York: Wiley.
}
\keyword{datasets}
\eof
\name{rle}
\title{Run Length Encoding}
\alias{rle}
\alias{inverse.rle}
\alias{print.rle}
\description{
  Compute the lengths and values of runs of equal values in a vector
  -- or the reverse operation.
}
\usage{
rle(x)
inverse.rle(x, \dots)
}
\arguments{
  \item{x}{a simple vector for \code{rle()} or an object of class
    \code{"rle"} for \code{inverse.rle()}.}
  \item{\dots}{further arguments which are ignored in \R.}
}
\value{
  \code{rle()} returns an object of class \code{"rle"} which is a list
  with components
  \item{lengths}{an integer vector containing the length of each run.}
  \item{values}{a vector of the same length as \code{lengths} with the
    corresponding values.}

  \code{inverse.rle()} is the inverse function of \code{rle()}.
}
\examples{
x <- rev(rep(6:10, 1:5))
rle(x)
## lengths [1:5]  5 4 3 2 1
## values  [1:5] 10 9 8 7 6

z <- c(TRUE,TRUE,FALSE,FALSE,TRUE,FALSE,TRUE,TRUE,TRUE)
rle(z)
rle(as.character(z))

stopifnot(x == inverse.rle(rle(x)),
          z == inverse.rle(rle(z)))
}
\keyword{manip}
\eof
\name{remove}
\title{Remove Objects from a Specified Environment}
\usage{
remove(\dots, list = character(0), pos = -1, envir = as.environment(pos),
       inherits = FALSE)
rm    (\dots, list = character(0), pos = -1, envir = as.environment(pos),
       inherits = FALSE)
}
\alias{rm}
\alias{remove}
\arguments{
  \item{\dots}{the objects to be removed, supplied individually and/or as a
    character vector}
  \item{list}{a character vector naming objects to be removed.}
  \item{pos}{where to do the removal.  By default, uses the
    current environment.  See the details for other possibilities.}
  \item{envir}{the \code{\link{environment}} to use. See the details section.}
  \item{inherits}{should the enclosing frames of the environment be
    inspected?}
}
\description{
  \code{remove} and \code{rm} can be used to remove objects.  These can
  be specified successively as character strings, or in the character
  vector \code{list}, or through a combination of both.  All objects
  thus specified will be removed.

  If \code{envir} is NULL then the currently active environment is
  searched first.

  If \code{inherits} is \code{TRUE} then parents of the supplied
  directory are searched until a variable with the given name is
  encountered.  A warning is printed for each variable that is not
  found.
}
\details{
  The \code{pos} argument can specify the  environment from which to remove
  the objects in any of several ways:
  as an integer (the position in the \code{\link{search}} list); as
  the character string name of an element in the search list; or as an
  \code{\link{environment}} (including using \code{\link{sys.frame}} to
  access the currently active function calls).
  The \code{envir} argument is an alternative way to specify an
  environment, but is primarily there for back compatibility.
   }
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{ls}}, \code{\link{objects}}
}
\examples{
tmp <- 1:4
## work with tmp  and cleanup
rm(tmp)

\dontrun{
## remove (almost) everything in the working environment.
## You will get no warning, so don't do this unless you are really sure.
rm(list = ls())
}}
\keyword{environment}
\eof
\name{round.POSIXt}
\alias{round.POSIXt}
\alias{trunc.POSIXt}
\alias{round.Date}
\alias{trunc.Date}
\title{Round / Truncate Data-Time Objects}
\description{
  Round or truncate date-time objects.
}
\usage{
\method{round}{POSIXt}(x, units=c("secs", "mins", "hours", "days"))
\method{trunc}{POSIXt}(x, units=c("secs", "mins", "hours", "days"))

\method{round}{Date}(x, \dots)
\method{trunc}{Date}(x)
}
\arguments{
  \item{x}{an object inheriting from \code{"POSIXt"} or \code{"Date"}.}
  \item{units}{one of the units listed.  Can be abbreviated.}
  \item{\dots}{arguments to be passed to or from other methods, notably
    \code{digits}.}
}
\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.

  The methods for class \code{"Date"} are of little use except to remove
  fractional days.
}
\value{
  An object of class \code{"POSIXlt"}.
}
\seealso{
  \code{\link{round}} for the generic function and default methods.
  
  \code{\link{DateTimeClasses}}, \code{\link{Date}}
}

\examples{
round(.leap.seconds + 1000, "hour")
trunc(Sys.time(), "day")
}
\keyword{chron}
\eof
\name{row}
\alias{row}
\title{Row Indexes}
\description{
  Returns a matrix of integers indicating their row number in the
  matrix.
}
\usage{
row(x, as.factor = FALSE)
}
\arguments{
  \item{x}{a matrix.}
  \item{as.factor}{a logical value indicating whether the value should
    be returned as a factor rather than as numeric.}
}
\value{
  An integer matrix with the same dimensions as \code{x} and whose
  \code{ij}-th element is equal to \code{i}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{col}} to get columns.
}
\examples{
x <- matrix(1:12, 3, 4)
# extract the diagonal of a matrix
dx <- x[row(x) == col(x)]
dx

# create an identity 5-by-5 matrix
x <- matrix(0, nr = 5, nc = 5)
x[row(x) == col(x)] <- 1
x
}
\keyword{array}
\eof
\name{row.names}
\title{Get and Set Row Names for Data Frames}
\alias{row.names}
\alias{row.names.data.frame}
\alias{row.names.default}
\alias{row.names<-}
\alias{row.names<-.data.frame}
\alias{row.names<-.default}
\description{
  All data frames have a row names attribute, a character vector of
  length the number of rows with no duplicates nor missing values.

  For convenience, these are generic functions for which users can write
  other methods, and there are default methods for arrays.  The
  description here is for the \code{data.frame} method.
}
\usage{
row.names(x)
row.names(x) <- value
}
\arguments{
  \item{x}{object of class \code{"data.frame"}, or any other class for
    which a method has been defined.}
  \item{value}{a vector with the same length as the number of rows of
    \code{x}, to be coerced to character.  Duplicated or missing values
    are not allowed.}
}
\value{
  \code{row.names} returns a character vector.

  \code{row.names<-} returns a data frame with the row names changed.
}
\note{
  \code{row.names} is similar to \code{\link{rownames}} for arrays, and
  it has a method that calls \code{rownames} for an array argument.
}
\references{
  Chambers, J. M. (1992)
  \emph{Data for models.}
  Chapter 3 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{data.frame}}, \code{\link{rownames}}.
}
\keyword{classes}
\keyword{methods}
\eof
\name{rowsum}
\alias{rowsum}
\alias{rowsum.default}
\alias{rowsum.data.frame}
\title{
Give row sums of a matrix or data frame, based on a grouping variable
}
\description{
  Compute sums across rows of a matrix-like object for each level of a grouping
  variable. \code{rowsum} is generic, with methods for matrices and data
  frames.
}
\usage{
rowsum(x, group, reorder = TRUE, \dots)
}
\arguments{
  \item{x}{a matrix, data frame or vector of numeric data.  Missing
  values are    allowed.}
  \item{group}{a vector giving the grouping, with one element per row of
    \code{x}.  Missing values will be treated as another group and a
    warning will be given}
  \item{reorder}{if \code{TRUE}, then the result will be in order of
    \code{sort(unique(group))}, if \code{FALSE}, it will be in the order
    that rows were encountered. }
  \item{\dots}{other arguments for future methods}
}
\value{
  a matrix or data frame containing the sums.  There will be one row per
  unique value  of \code{group}.
}

\details{
  The default is to reorder the rows to agree with \code{tapply} as in
  the example below. Reordering should not add noticeably to the time
  except when there are very many distinct values of \code{group} and
  \code{x} has few columns.

  The original function was written by Terry Therneau, but this is a
  new implementation using hashing that is much faster for large matrices.

  To add all the rows of a matrix (ie, a single \code{group}) use
  \code{\link{rowSums}}, which should be even faster.
}

\seealso{
  \code{\link{tapply}}, \code{\link[stats]{aggregate}}, \code{\link{rowSums}}
}
\examples{
x <- matrix(runif(100), ncol=5)
group <- sample(1:8, 20, TRUE)
xsum <- rowsum(x, group)
## Slower versions
xsum2 <- tapply(x, list(group[row(x)], col(x)), sum)
xsum3<- aggregate(x,list(group),sum)

}
\keyword{manip}

\eof
\name{sQuote}
\alias{sQuote}
\alias{dQuote}
\title{Quote Text}
\description{
  Single or double quote text by combining with appropriate single or
  double left and right quotation marks.
}
\usage{
sQuote(x)
dQuote(x)
}
\arguments{
  \item{x}{an \R object, to be coerced to a character vector.}
}
\details{
  The purpose of the functions is to provide a simple means of markup
  for quoting text to be used in the R output, e.g., in warnings or
  error messages.

  The choice of the appropriate quotation marks depends on both the
  locale and the available character sets.  Older Unix/X11 fonts
  displayed the grave accent (0x60) and the apostrophe (0x27) in a way
  that they could also be used as matching open and close single
  quotation marks.  Using modern fonts, or non-Unix systems, these
  characters no longer produce matching glyphs.  Unicode provides left
  and right single quotation mark characters (U+2018 and U+2019); if
  Unicode cannot be assumed, it seems reasonable to use the apostrophe
  as an undirectional single quotation mark.

  Similarly, Unicode has left and right double quotation mark characters
  (U+201C and U+201D); if only ASCII's typewriter characteristics can be
  employed, than the ASCII quotation mark (0x22) should be used as both
  the left and right double quotation mark.

  \code{sQuote} and \code{dQuote} currently only provide undirectional
  ASCII quotation style, but may be enhanced in the future.
}
\references{
  Markus Kuhn, \dQuote{ASCII and Unicode quotation marks}.
  \url{http://www.cl.cam.ac.uk/~mgk25/ucs/quotes.html}
}
\examples{
paste("argument", sQuote("x"), "must be non-zero")
}
\keyword{character}
\eof
\name{sample}
\alias{sample}
\title{Random Samples and Permutations}
\description{
  \code{sample} takes a sample of the specified size from the elements
  of \code{x} using either with or without replacement.
}
\usage{
sample(x, size, replace = FALSE, prob = NULL)
}
\arguments{
  \item{x}{Either a (numeric, complex, character or logical) vector of
    more than one element from which to choose, or a positive integer.}
  \item{size}{non-negative integer giving the number of items to choose.}
  \item{replace}{Should sampling be with replacement?}
  \item{prob}{A vector of probability weights for obtaining the elements
    of the vector being sampled.}
}
\details{
  If \code{x} has length 1, sampling takes place from
  \code{1:x}.  \emph{Note} that this convenience feature may lead to
  undesired behaviour when \code{x} is of varying length
  \code{sample(x)}.  See the \code{resample()} example below.

  By default \code{size} is equal to \code{length(x)}
  so that \code{sample(x)} generates a random permutation
  of the elements of \code{x} (or \code{1:x}).

  The optional \code{prob} argument can be used to give a vector
  of weights for obtaining the elements of the vector being
  sampled. They need not sum to one, but they should be nonnegative
  and not all zero.
  If \code{replace} is false, these probabilities are applied
  sequentially, that is the probability of choosing the next item is
  proportional to the probabilities amongst the remaining items. The number
  of nonzero weights must be at least \code{size} in this case.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
x <- 1:12
# a random permutation
sample(x)
# bootstrap sampling -- only if length(x) > 1 !
sample(x,replace=TRUE)

# 100 Bernoulli trials
sample(c(0,1), 100, replace = TRUE)

## More careful bootstrapping --  Consider this when using sample()
## programmatically (i.e., in your function or simulation)!

# sample()'s surprise -- example
x <- 1:10
    sample(x[x >  8]) # length 2
    sample(x[x >  9]) # oops -- length 10!
try(sample(x[x > 10]))# error!

## This is safer:
resample <- function(x, size, ...)
  if(length(x) <= 1) { if(!missing(size) && size == 0) x[FALSE] else x
  } else sample(x, size, ...)

resample(x[x >  8])# length 2
resample(x[x >  9])# length 1
resample(x[x > 10])# length 0
}
\keyword{distribution}
\eof
\name{save}
\alias{save}
\alias{save.image}
\alias{sys.save.image}
\alias{sys.load.image}
\title{Save R Objects}
\description{
  \code{save} writes an external representation of \R objects to the
  specified file.  The objects can be read back from the file at a later
  date by using the function \code{load} (or \code{data} in some cases).

  \code{save.image()} is just a short-cut for \dQuote{save my current
    environment},
  i.e., \code{save(list = ls(all=TRUE), file = ".RData")}.  It is what
  also happens with \code{\link{q}("yes")}.
}
\usage{
save(\dots, list = character(0), file = stop("'file' must be specified"),
     ascii = FALSE, version = NULL, envir = parent.frame(), 
     compress = FALSE)
save.image(file = ".RData", version = NULL, ascii = FALSE,
           compress = FALSE, safe = TRUE)

sys.load.image(name, quiet)
sys.save.image(name)
}
\arguments{
  \item{\dots}{the names of the objects to be saved.}
  \item{list}{A character vector containing the names of objects to be
    saved.}
  \item{file}{a connection or the name of the file where the data will be
    saved.  Must be a file name for workspace format version 1.}
  \item{ascii}{if \code{TRUE}, an ASCII representation of the data is
    written.  This is useful for transporting data between machines of
    different types.  The default value of \code{ascii} is \code{FALSE}
    which leads to a more compact binary file being written.}
  \item{version}{the workspace format version to use.  \code{NULL}
    specifies the current default format.  The version used from \R
    0.99.0 to \R 1.3.1 was version 1.  The default format as from \R
    1.4.0 is version 2.}
  \item{envir}{environment to search for objects to be saved.}
  \item{compress}{logical specifying whether saving to a named file is to
    use compression. Ignored when \code{file} is a connection and for
    workspace format version 1.}
  \item{safe}{logical.  If \code{TRUE}, a temporary file is used for
    creating the saved workspace.  The temporary file is renamed to
    \code{file} if the save succeeds.  This preserves an existing
    workspace \code{file} if the save fails, but at the cost of using
    extra disk space during the save.}
  \item{name}{name of image file to save or load.}
  \item{quiet}{logical specifying whether a message should be printed.}
  }
}
\details{
  All \R platforms use the XDR representation of binary objects in
  binary save-d files, and these are portable across all \R platforms.

  Default values for the \code{ascii}, \code{compress}, \code{safe} and
  \code{version} arguments can be modified with
  the \code{save.defaults} option (used both by \code{save} and
  \code{save.image}). If a \code{save.image.defaults}
  option is set it overrides \code{save.defaults} for function
  \code{save.image} (which allows to have different defaults). This
  mechanism is experimental and subject to change.

  \code{sys.save.image} is a system function that is called by \code{q()}
  and its GUI analogs; \code{sys.load.image} is called by the startup code.
  These functions should not be called directly and are subject to change.

  \code{sys.save.image} closes all connections first, to ensure that it
  is able to open a connection to save the image.  This is appropriate
  when called from \code{q()} and allies, but reinforces the warning
  that it should not be called directly.
}
\section{Warning}{
  The \code{\dots} arguments only give the \emph{names} of the objects
  to be saved: they are searched for in the environment given by the
  \code{envir} argument, and the actual objects given as arguments need
  not be those found.  
}
\seealso{
  \code{\link{dput}}, \code{\link{dump}}, \code{\link{load}},
  \code{\link{data}}.
}
\examples{
x <- runif(20)
y <- list(a = 1, b = TRUE, c = "oops")
save(x, y, file = "xy.Rdata")
save.image()
unlink("xy.Rdata")
unlink(".RData")

# set save defaults using option:
options(save.defaults=list(ascii=TRUE, safe=FALSE))
save.image()
unlink(".RData")
}
\keyword{file}
\eof
\name{scale}
\alias{scale}
\alias{scale.default}
\title{Scaling and Centering of Matrix-like Objects}
\description{
  \code{scale} is generic function whose default method centers and/or
  scales the columns of a numeric matrix.
}
\usage{
scale(x, center = TRUE, scale = TRUE)
}
\arguments{
  \item{x}{a numeric matrix(like object).}
  \item{center}{either a logical value or a numeric vector of length
    equal to the number of columns of \code{x}.}
  \item{scale}{either a logical value or a numeric vector of length
    equal to the number of columns of \code{x}.}
}
\value{
  For \code{scale.default}, the centered, scaled matrix. The numeric
  centering and scalings used (if any) are returned as attributes
  \code{"scaled:center"} and \code{"scaled:scale"}
}
\details{
  The value of \code{center} determines how column centering is
  performed.
  If \code{center} is a numeric vector with length equal to the number
  of columns of \code{x}, then each column of \code{x} has the
  corresponding value from \code{center} subtracted from it.
  If \code{center} is \code{TRUE} then centering is done by subtracting
  the column means (omitting \code{NA}s) of \code{x} from their
  corresponding columns, and if \code{center} is \code{FALSE},
  no centering is done.

  The value of \code{scale} determines how column scaling is performed
  (after centering).
  If \code{scale} is a numeric vector with length equal to the number of
  columns of \code{x}, then each column of \code{x} is divided by the
  corresponding value from \code{scale}.
  If \code{scale} is \code{TRUE} then scaling is done by dividing the
  (centered) columns of \code{x} by their root-mean-square, and if
  \code{scale} is \code{FALSE}, no scaling is done.

  The root-mean-square for a column is obtained by computing the
  square-root of the sum-of-squares of the non-missing values in the
  column divided by the number of non-missing values minus one.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{sweep}} which allows centering (and scaling) with
  arbitrary statistics.

  For working with the scale of a plot, see \code{\link[graphics]{par}}.
}
\examples{
require(stats)
x <- matrix(1:10, nc=2)
(centered.x <- scale(x, scale=FALSE))
cov(centered.scaled.x <- scale(x))# all 1
}
\keyword{array}
\eof
\name{scan}
\title{Read Data Values}
\alias{scan}
\description{
  Read data into a vector or list from the console or file.
}
\usage{
scan(file = "", what = double(0), nmax = -1, n = -1, sep = "",
     quote = if (sep=="\n") "" else "'\"", dec = ".",
     skip = 0, nlines = 0, na.strings = "NA",
     flush = FALSE, fill = FALSE, strip.white = FALSE, quiet = FALSE,
     blank.lines.skip = TRUE, multi.line = TRUE, comment.char = "")
}
\arguments{
  \item{file}{the name of a file to read data values from.  If the
    specified file is \code{""}, then input is taken from the keyboard
    (or \code{stdin} if input is redirected).
    (In this case input can be terminated by a blank line or an EOF
    signal, \code{Ctrl-D} on Unix and \code{Ctrl-Z} on Windows.)

    Otherwise, the file name is interpreted \emph{relative} to the
    current working directory (given by \code{\link{getwd}()}),
    unless it specifies an \emph{absolute} path.
    Tilde-expansion is performed where supported.

    Alternatively, \code{file} can be a \code{\link{connection}},
    which will be opened if necessary, and if so closed at the end of
    the function call.  Whatever mode the connection is opened in,
    any of LF, CRLF or CR will be accepted as the EOL marker for a line
    and so will match \code{sep = "\n"}.

    \code{file} can also be a complete URL.
  }
  \item{what}{the type of \code{what} gives the type of data to be
    read.  If \code{what} is a list, it is assumed that the lines of the
    data file are records each containing \code{length(what)} items
    (\dQuote{fields}).  The supported types are \code{logical},
    \code{integer}, \code{numeric}, \code{complex}, \code{character} and
    \code{list}: \code{list} values should have elements which are one
    of the first five types listed or \code{NULL}.}

  \item{nmax}{the maximum number of data values to be read, or if
    \code{what} is a list, the maximum number of records to be read.  If
    omitted (and \code{nlines} is not set to a positive value),
    \code{scan} will read to the end of \code{file}.}

  \item{n}{the maximum number of data values to be read, defaulting to
    no limit.}

  \item{sep}{by default, scan expects to read white-space delimited
    input fields.  Alternatively, \code{sep} can be used to specify a
    character which delimits fields.  A field is always delimited by an
    end-of-line marker 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
    interpreted as missing (\code{\link{NA}}) values.}

  \item{flush}{logical: if \code{TRUE}, \code{scan} will flush to the
    end of the line after reading the last of the fields requested.
    This allows putting comments after the last field, but precludes
    putting more that one record on a line.}
  
  \item{fill}{logical: if \code{TRUE}, \code{scan} will implicitly add
    empty fields to any lines with fewer fields than implied by
    \code{what}.}
  
  \item{strip.white}{vector of logical value(s) corresponding to items
    in the \code{what} argument. It is used only when \code{sep} has
    been specified, and allows the stripping of leading and trailing
    white space from \code{character} fields (\code{numeric} fields
    are always stripped).

    If \code{strip.white} is of length 1, it applies to all fields;
    otherwise, if \code{strip.white[i]} is \code{TRUE} \emph{and} the
    \code{i}-th field is of mode character (because \code{what[i]} is)
    then the leading and trailing white space from field \code{i} is
    stripped.}
  
  \item{quiet}{logical: if \code{FALSE} (default), scan() will print a
    line, saying how many items have been read.}

  \item{blank.lines.skip}{logical: if \code{TRUE} blank lines in the
    input are ignored, except when counting \code{skip} and \code{nlines}.}

  \item{multi.line}{logical. Only used if \code{what} is a list.
    If \code{FALSE}, all of a record must appear on one line (but more
    than one record can appear on a single line).  Note that using
    \code{fill = TRUE} implies that a record will terminated at the end
    of a line.}
  
  \item{comment.char}{character: a character vector of length one
    containing a single character or an empty string.  Use \code{""} to
    turn off the interpretation of comments altogether (the default).}
}
\details{
  The value of \code{what} can be a list of types, in which case
  \code{scan} returns a list of vectors with the types given by the
  types of the elements in \code{what}.  This provides a way of reading
  columnar data.  If any of the types is \code{NULL}, the corresponding
  field is skipped (but a \code{NULL} component appears in the result).

  The type of \code{what} or its components can be one of the five
  atomic types or \code{NULL},

  Empty numeric fields are always regarded as missing values.
  Empty character fields are scanned as empty character vectors, unless
  \code{na.strings} contains \code{""} when they are regarded as missing
  values.
  
  If \code{sep} is the default (\code{""}), the character \code{\\}
  in a quoted string escapes the following character, so quotes may be
  included in the string by escaping them.
  
  If \code{sep} is non-default, the fields may be quoted in the style of
  \file{.csv} files where separators inside quotes (\code{''} or 
  \code{""}) are ignored and quotes may be put inside strings by
  doubling them.  However, if \code{sep = "\\n"} it is assumed
  by default that one wants to read entire lines verbatim.

  Quoting is only interpreted in character fields, and as from \R 1.8.0
  in \code{NULL} fields (which might be skipping character fields).

  Note that since \code{sep} is a separator and not a terminator,
  reading a file by \code{scan("foo", sep="\\n", blank.lines.skip=FALSE)}
  will give an empty file line if the file ends in a linefeed and not if
  it does not.  This might not be what you expected; see also
  \code{\link{readLines}}.

  If \code{comment.char} occurs (except inside a quoted character
  field), it signals that the rest of the line
  should be regarded as a comment and be discarded.  Lines beginning
  with a comment character (possibly after white space) are treated
  as blank lines. 
}
\value{
  if \code{what} is a list, a list of the same length and same names (as
  any) as \code{what}.

  Otherwise, a vector of the type of \code{what}.
}
\note{
  The default for \code{multi.line} differs from S.  To read one record
  per line, use \code{flush = TRUE} and \code{multi.line = FALSE}.
  
  If number of items is not specified, the internal
  mechanism re-allocates memory in powers of two and so could use up
  to three times as much memory as needed.  (It needs both old and new
  copies.)  If you can, specify either \code{n} or \code{nmax} whenever
  inputting a large vector, and \code{nmax} or \code{nlines} when
  inputting a large list.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{read.table}} for more user-friendly reading of data
  matrices;
  \code{\link{readLines}} to read a file a line at a time.
  \code{\link{write}}.
}
\examples{
cat("TITLE extra line", "2 3 5 7", "11 13 17", file="ex.data", sep="\n")
pp <- scan("ex.data", skip = 1, quiet= TRUE)
    scan("ex.data", skip = 1)
    scan("ex.data", skip = 1, nlines=1)# only 1 line after the skipped one
scan("ex.data", what = list("","","")) # flush is F -> read "7"
scan("ex.data", what = list("","",""), flush = TRUE)
unlink("ex.data") # tidy up
}
\keyword{file}
\keyword{connection}
\eof
\name{search}
\title{Give Search Path for R Objects}
\usage{
search()
searchpaths()
}
\alias{search}
\alias{searchpaths}
\description{
  Gives a list of \code{\link{attach}}ed \emph{packages}
  (see \code{\link{library}}), and \R objects, usually
  \code{\link{data.frame}s}.
}
\value{
  A character vector, starting with \code{"\link{.GlobalEnv}"}, and
  ending with \code{"package:base"} which is \R's \pkg{base} package
  required always.

  \code{searchpaths} gives a similar character vector, with the
  entries for packages being the path to the package used to load the
  code.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole. (\code{search}.)

  Chambers, J. M. (1998)
  \emph{Programming with Data. A Guide to the S Language}.
  Springer. (\code{searchPaths}.)
}
\seealso{\code{\link{attach}} and \code{\link{detach}} to change the
  search \dQuote{path}, \code{\link{objects}} to find \R objects in there.
}
\examples{
search()
searchpaths()
}
\keyword{data}

\eof
\name{seek}
\alias{seek}
\alias{seek.connection}
\alias{truncate}
\alias{truncate.connection}
\alias{isSeekable}
\title{Functions to Reposition Connections}
\description{
  Functions to re-position connections.
}
\usage{
seek(con, \dots)
\method{seek}{connection}(con, where = NA, origin = "start", rw = "", \dots)

isSeekable(con)

truncate(con, \dots)
}
\arguments{
  \item{con}{a connection.}
  \item{where}{integer.  A file position (relative to the origin
    specified by \code{origin}), or \code{NA}.}
  \item{rw}{character.  Empty or \code{"read"} or \code{"write"},
    partial matches allowed.}
  \item{origin}{character.  One of \code{"start"}, \code{"current"},
    \code{"end"}.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\details{
  \code{seek} with \code{where = NA} returns the current byte offset
  of a connection (from the beginning), and with a non-missing \code{where}
  argument the connection is re-positioned (if possible) to the
  specified position. \code{isSeekable} returns whether the connection
  in principle supports \code{seek}: currently only (possibly
  compressed) file connections do.
#ifdef windows
  The value returned by \code{seek(where=NA)} appears to be unreliable
  on Windows systems, at least for text files.  Clipboard connections
  can seek too.
#endif
  
  File connections can be open for both writing/appending, in which case
  \R keeps separate positions for reading and writing. Which \code{seek}
  refers to can be set by its \code{rw} argument: the default is the
  last mode (reading or writing) which was used.  Most files are
  only opened for reading or writing and so default to that state.
  If a file is open for reading and writing but has not been used, the
  default is to give the reading position (0).

  The initial file position for reading is always at the beginning.
  The initial position for writing is at the beginning of the file
  for modes \code{"r+"} and \code{"r+b"}, otherwise at the end of the
  file.  Some platforms only allow writing at the end of the file in
  the append modes.

  \code{truncate} truncates a file opened for writing at its current
  position.  It works only for \code{file} connections, and is not
  implemented on all platforms.
}
\value{
  \code{seek} returns the current position (before any move),
  as a byte offset, if relevant, or \code{0} if not.

  \code{truncate} returns \code{NULL}: it stops with an error if
  it fails (or is not implemented).

  \code{isSeekable} returns a logical value, whether the connection is
  support \code{seek}.
}
\seealso{
  \code{\link{connections}}
}
\keyword{file}
\keyword{connection}
\eof
\name{seq.Date}
\alias{seq.Date}
\title{Generate Regular Sequences of Dates}
\description{
  The methodw for \code{\link{seq}} for date-time classes
}
\usage{
\method{seq}{Date}(from, to, by, length.out=NULL, along.with=NULL, \dots)
}
\arguments{
  \item{from}{starting date. Required}
  \item{to}{end date. Optional. If supplied must be after \code{from}.}
  \item{by}{increment of the sequence. Optional. See Details.}
  \item{length.out}{integer, optional. desired length of the sequence.}
  \item{along.with}{take the length from the length of this argument.}
  \item{\dots}{arguments passed to or from other methods.}
}
\details{
  \code{by} can be specified in several ways.
  \itemize{
    \item A number, taken to be in days.
    \item A object of class \code{\link{difftime}}
    \item A character string, containing one of \code{"day"},
    \code{"week"}, \code{"month"} or \code{"year"}.  This can optionally be
    preceded by an integer and a space, or followed by \code{"s"}.
  }
}
\value{
  A vector of class \code{"Date"}.
}
\seealso{\code{\link{Date}}}

\examples{
## first days of years
seq(as.Date("1910/1/1"), as.Date("1999/1/1"), "years")
## by month
seq(as.Date("2000/1/1"), by="month", length=12)
## quarters
seq(as.Date("2000/1/1"), as.Date("2003/1/1"), by="3 months")
}
\keyword{manip}
\keyword{chron}
\eof
\name{seq.POSIXt}
\alias{seq.POSIXt}
\title{Generate Regular Sequences of Dates}
\description{
  The methodw for \code{\link{seq}} for date-time classes
}
\usage{
\method{seq}{POSIXt}(from, to, by, length.out=NULL, along.with=NULL, \dots)
}
\arguments{
  \item{from}{starting date. Required}
  \item{to}{end date. Optional. If supplied must be after \code{from}.}
  \item{by}{increment of the sequence. Optional. See Details.}
  \item{length.out}{integer, optional. desired length of the sequence.}
  \item{along.with}{take the length from the length of this argument.}
  \item{\dots}{arguments passed to or from other methods.}
}
\details{
  \code{by} can be specified in several ways.
  \itemize{
    \item A number, taken to be in seconds.
    \item A object of class \code{\link{difftime}}
    \item A character string, containing one of \code{"sec"},
    \code{"min"}, \code{"hour"}, \code{"day"}, \code{"DSTday"},
    \code{"week"}, \code{"month"} or \code{"year"}.  This can optionally be
    preceded by an integer and a space, or followed by \code{"s"}.
  }
  The difference between \code{"day"} and \code{"DSTday"} is that the
  former ignores changes to/from daylight savings time and the latter takes
  the same clock time each day.  (\code{"week"} ignores DST, but
  \code{"7 DSTdays"}) can be used as an alternative.  \code{"month"} and
  \code{"year"} allow for DST as from \R 1.5.0.)
}
\value{
  A vector of class \code{"POSIXct"}.
}
\seealso{\code{\link{DateTimeClasses}}}

\examples{
## first days of years
seq(ISOdate(1910,1,1), ISOdate(1999,1,1), "years")
## by month
seq(ISOdate(2000,1,1), by="month", length=12)
## quarters
seq(ISOdate(1990,1,1), ISOdate(2000,1,1), by="3 months")
## days vs DSTdays
seq(ISOdate(2000,3,20), by="day", length = 10)
seq(ISOdate(2000,3,20), by="DSTday", length = 10)
seq(ISOdate(2000,3,20), by="7 DSTdays", length = 4)
}
\keyword{manip}
\keyword{chron}
\eof
\name{seq}
\title{Sequence Generation}
\alias{seq}
\alias{seq.default}
\alias{:}
\description{
  Generate regular sequences.
}
\synopsis{
seq(...)
seq.default(from = 1, to = 1, by = ((to - from)/(length.out - 1)),
            length.out = NULL, along.with = NULL, ...)
}
\usage{
from:to
   a:b

seq(from, to)
seq(from, to, by=)
seq(from, to, length=)
seq(along=)
seq(from)
}
\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.}
  \item{a,b}{\code{\link{factor}}s of same length.}
}
\details{
  The binary operator \code{:} has two meanings: for factors \code{a:b} is
  equivalent to \code{\link{interaction}(a, b)} (except for labelling by
  \code{la:lb} not \code{la.lb}).  For numeric arguments \code{a:b} is
  equivalent to \code{seq(from=a, to=b)}.

  The interpretation of the unnamed arguments of \code{seq} is
  \emph{not} standard, and it is recommended always to name the
  arguments when programming.

  Function \code{seq} is generic, and only the default method is
  described here.

  The operator \code{:} and the \code{seq(from, to)} form generate the
  sequence \code{from, from+1, \dots, to}.

  The second form generates \code{from, from+by}, \ldots, up to the
  sequence value less than or equal to \code{to}.

  The third generates a sequence of \code{length} equally spaced values
  from \code{from} to \code{to}.

  The fourth form generates the sequence \code{1, 2, \dots, length(along)}.

  The last generates the sequence \code{1, 2, \dots, length(from)}
  (as if argument \code{along} had been specified),
  \emph{unless} the argument is numeric of length 1 when it is
  interpreted as \code{1:from} (even for \code{seq(0)} for
  compatibility with S).

  If \code{from} and \code{to} are factors of the same length, then
  \code{from : to} returns the \dQuote{cross} of the two.

  Very small sequences (with \code{from - to} of the order of \eqn{10^{-14}}
  times the larger of the ends) will return \code{from}.
}
\value{
  The result is of \code{mode} \code{"integer"} if \code{from} is
  (numerically equal to an) integer and \code{by} is not specified.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  The method \code{\link{seq.POSIXt}}.

  \code{\link{rep}},
  \code{\link{sequence}},
  \code{\link{row}},
  \code{\link{col}}.

  As an alternative to using \code{:} for factors, \code{\link{interaction}}.
}
\examples{
1:4
pi:6 # float
6:pi # integer

seq(0,1, length=11)
seq(rnorm(20))
seq(1,9, by = 2) # match
seq(1,9, by = pi)# stay below
seq(1,6, by = 3)
seq(1.575, 5.125, by=0.05)
seq(17) # same as 1:17

for (x in list(NULL, letters[1:6], list(1,pi)))
  cat("x=",deparse(x),";  seq(along = x):",seq(along = x),"\n")

f1 <- gl(2,3); f1
f2 <- gl(3,2); f2
f1:f2 # a factor, the "cross"  f1 x f2
}
\keyword{manip}
\eof
\name{sequence}
\title{Create A Vector of Sequences}
\usage{
sequence(nvec)
}
\alias{sequence}
\arguments{
\item{nvec}{an integer vector each element of which specifies the upper
bound of a sequence.}
}
\description{
For each element of \code{nvec} the sequence \code{seq(nvec[i])}
is created. These are appended and the result returned.
}
\seealso{
\code{\link{gl}}, \code{\link{seq}}, \code{\link{rep}}.
}
\examples{
sequence(c(3,2))# the concatenated sequences 1:3 and 1:2.
#> [1] 1 2 3 1 2
}
\keyword{manip}
\eof
\name{serialize}
\alias{.readRDS}
\alias{.saveRDS}
\alias{serialize}
\alias{unserialize}
\title{Simple Serialization Interface}
\description{
  A simple low level interface for serializing to connections.
}
\usage{
serialize(object, connection, ascii = FALSE, refhook = NULL)
unserialize(connection, refhook = NULL)
.saveRDS(object, file = "", ascii = FALSE, version = NULL,
         compress = FALSE, refhook = NULL)
.readRDS(file, refhook = NULL)
}
\arguments{
  \item{object}{\R object to serialize.}
  \item{file}{a connection or the name of the file where the R object
    is saved to or read from.}
  \item{ascii}{a logical.  If \code{TRUE}, an ASCII representation is
    written; otherwise (default), a more compact binary one is used.}
  \item{version}{the workspace format version to use.  \code{NULL}
    specifies the current default format.  The version used from \R
    0.99.0 to \R 1.3.1 was version 1.  The default format as from \R
    1.4.0 is version 2.}
  \item{compress}{a logical specifying whether saving to a named file is
    to use compression.  Ignored when \code{file} is a connection and for
    workspace format version 1.}
  \item{connection}{an open connection.}
  \item{refhook}{a hook function for handling reference objects.}
}
\details{
  The function \code{serialize} writes \code{object} to the specified
  connection.  Sharing of reference objects is preserved within the
  object but not across separate calls to serialize.  If
  \code{connection} is \code{NULL} then \code{object} is serialized to a
  scaler string, which is returned as the result of \code{serialize}.
  For a text mode connection, the default value of \code{ascii} is set
  to \code{TRUE}.

  \code{unserialize} reads an object from \code{connection}.
  \code{connection} may also be a scaler string.

  The \code{refhook} functions can be used to customize handling of
  non-system reference objects (all external pointers and weak
  references, and all environments other than name space and package
  environments and \code{.GlobalEnv}).  The hook function for
  \code{serialize} should return a character vector for references it
  wants to handle; otherwise it should return \code{NULL}.  The hook for
  \code{unserialize} will be called with character vectors supplied to
  \code{serialize} and should return an appropriate object.
}
\section{Warning}{
  These functions are still experimental.  Both names, interfaces and
  values might change in future versions.  \code{.saveRDS} and
  \code{.readRDS} are intended for internal use.
}
\examples{
x<-serialize(list(1,2,3),NULL)
unserialize(x)
}
\keyword{internal}
\keyword{file}
\eof
\name{sets}
\alias{union}
\alias{intersect}
\alias{setdiff}
\alias{is.element}
\alias{setequal}
\title{Set Operations}
\usage{
union(x, y)
intersect(x, y)
setdiff(x, y)
setequal(x, y)
is.element(el, set)
}
\arguments{
  \item{x, y, el, set}{vectors (of the same mode) containing a sequence
    of items (conceptually) with no duplicated values.}
}
\description{
  Performs \bold{set} union, intersection, (asymmetric!) difference,
  equality and membership on two vectors.
}
\details{
  Each of \code{union}, \code{intersect} and \code{setdiff} will remove
  any duplicated values in the arguments.

  \code{is.element(x, y)} is identical to \code{x \%in\% y}.
}
\value{
  A vector of the same \code{\link{mode}} as \code{x} or \code{y} for
  \code{setdiff} and \code{intersect}, respectively, and
  of a common mode for \code{union}.

  A logical scalar for \code{setequal} and a logical of the same
  length as \code{x} for \code{is.element}.
}
\seealso{\code{\link{\%in\%}}}

\examples{
(x <- c(sort(sample(1:20, 9)),NA))
(y <- c(sort(sample(3:23, 7)),NA))
union(x, y)
intersect(x, y)
setdiff(x, y)
setdiff(y, x)
setequal(x, y)

## True for all possible x & y :
setequal( union(x,y),
          c(setdiff(x,y), intersect(x,y), setdiff(y,x)))

is.element(x, y)# length 10
is.element(y, x)# length  8
}
\keyword{misc}
\eof
\name{showConnections}
\alias{showConnections}
\alias{getConnection}
\alias{getAllConnections}
\alias{closeAllConnections}
\alias{stdin}
\alias{stdout}
\alias{stderr}
\title{Display Connections}
\description{
  Display aspects of connections.
}
\usage{
showConnections(all=FALSE)
getConnection(what)
closeAllConnections()

stdin()
stdout()
stderr()
}
\arguments{
  \item{all}{logical: if true all connections, including closed ones
    and the standard ones are displayed. If false only open user-created
    connections are included.}

  \item{what}{integer: a row number of the table given by
    \code{showConnections}.}
}
\details{
  \code{stdin()}, \code{stdout()} and \code{stderr()} are standard
  connections corresponding to input, output and error on the console
  respectively (and not necessarily to file streams).  They are text-mode
  connections of class \code{"terminal"} which cannot be opened or
  closed, and are read-only, write-only and write-only respectively.
  The \code{stdout()} and \code{stderr()} connections can be
  re-directed by \code{\link{sink}}.

  \code{showConnections} returns a matrix of information.  If a
  connection object has been lost or forgotten, \code{getConnection}
  will take a row number from the table and return a connection object
  for that connection, which can be used to close the connection,
  for example.

  \code{closeAllConnections} closes (and destroys) all open user
  connections, restoring all \code{\link{sink}} diversions as it does so.
}
\value{
  \code{stdin()}, \code{stdout()} and \code{stderr()} return connection
  objects.

  \code{showConnections} returns a character matrix of information with
  a row for each connection, by default only for open non-standard connections.

  \code{getConnection} returns a connection object, or \code{NULL}.
}
\seealso{\code{\link{connections}}}

\examples{
showConnections(all = TRUE)

textConnection(letters)
# oops, I forgot to record that one
showConnections()
#  class     description      mode text   isopen   can read can write
#3 "letters" "textConnection" "r"  "text" "opened" "yes"    "no"     
\dontrun{close(getConnection(3))}
\dontshow{r <- as.numeric(row.names(showConnections()))
close(getConnection(r))}
showConnections()
}
\keyword{connection}
\eof
\name{sign}
\title{Sign Function}
\usage{
sign(x)
}
\alias{sign}
\arguments{
  \item{x}{a numeric vector}
}
\description{
  \code{sign} returns a vector with the signs of the corresponding
  elements of \code{x} (the sign of a real number is 1, 0, or \eqn{-1}
  if the number is positive, zero, or negative, respectively).

  Note that \code{sign} does not operate on complex vectors.
}
\details{
  This is a generic function: methods can be defined for it
  directly or via the \code{\link{Math}} group generic.
}
\seealso{
  \code{\link{abs}}
}
\examples{
sign(pi) # == 1
sign(-2:3)# -1 -1 0 1 1 1
}
\keyword{arith}

\eof
\name{sink}
\alias{sink}
\alias{sink.number}
\title{Send R Output to a File}
\usage{
sink(file = NULL, append = FALSE, type = c("output", "message"), split=FALSE)
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.}
  \item{split}{logical: if \code{TRUE}, output will be sent to the new
    sink and to the current output stream.}
}
\description{
  \code{sink} diverts \R output to a connection.

  \code{sink.number()} reports how many diversions are in use.

  \code{sink.number(type = "message")} reports the number of the
  connection currently being used for error messages.
}
\details{
  \code{sink} diverts \R output to a connection. If \code{file} is a
  character string, a file connection with that name will be established
  for the duration of the diversion.

  Normal \R output is diverted by the default \code{type = "output"}.
  Only prompts and warning/error messages continue to appear on the terminal.
  The latter can diverted by \code{type = "message"} (see below).

  \code{sink()} or \code{sink(file=NULL)} ends the last diversion (of
  the specified type).  As from \R version 1.3.0 there is a stack of
  diversions for normal output, so output reverts to the previous
  diversion (if there was one).  The stack is of up to 21 connections
  (20 diversions).

  If \code{file} is a connection if will be opened if necessary.

  Sink-ing the messages stream should be done only with great care.
  For that stream \code{file} must be an already open connection, and
  there is no stack of connections.
}
\value{
  \code{sink} returns \code{NULL}.

  For \code{sink.number()} the number (0, 1, 2, \dots) of diversions of
  output in place.

  For \code{sink.number("message")} the connection number used for
  messages, 2 if no diversion has been used.
}
\section{Warning}{
  Don't use a connection that is open for \code{sink} for any other
  purpose.  The software will stop you closing one such inadvertently.

  Do not sink the messages stream unless you understand the source code
  implementing it and hence the pitfalls.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Chambers, J. M. (1998)
  \emph{Programming with Data. A Guide to the S Language}.
  Springer.
}
\seealso{\code{\link[utils]{capture.output}}}
\examples{
sink("sink-examp.txt")
i <- 1:10
outer(i, i, "*")
sink()
unlink("sink-examp.txt")
\dontrun{
## capture all the output to a file.
zz <- file("all.Rout", open="wt")
sink(zz)
sink(zz, type="message")
try(log("a"))
## back to the console
sink(type="message")
sink()
try(log("a"))
}}
\keyword{file}
\keyword{connection}
\eof
\name{sleep}
\docType{data}
\alias{sleep}
\title{Student's Sleep Data}
\description{
  Data which show the effect of two soporific drugs (increase in hours
  of sleep) on groups consisting of 10 patients each.
}
\usage{data(sleep)}
\format{
  A data frame with 20 observations on 2 variables.
  \tabular{rlll}{
    [, 1] \tab extra \tab numeric \tab increase in hours of sleep\cr
    [, 2] \tab group \tab factor  \tab patient group
  }
}
\source{
  Student (1908)
  The probable error of the mean.
  \emph{Biometrika}, \bold{6}, 20.
}
\references{
  Scheffé, Henry (1959)
  \emph{The Analysis of Variance}.
  New York, NY: Wiley.
}
\examples{
require(stats)
data(sleep)
## ANOVA
anova(lm(extra ~ group, data = sleep))
}
\keyword{datasets}
\eof
\name{slice.index}
\alias{slice.index}
\title{Slice Indexes in an Array}
\description{
  Returns a matrix of integers indicating the number of their slice in a
  given array.
}
\usage{
slice.index(x, MARGIN)
}
\arguments{
  \item{x}{an array.  If \code{x} has no dimension attribute, it is
    considered a one-dimensional array.}
  \item{MARGIN}{an integer giving the dimension number to slice by.}
}
\value{
  An integer array \code{y} with dimensions corresponding to those of
  \code{x} such that all elements of slice number \code{i} with respect
  to dimension \code{MARGIN} have value \code{i}.
}
\seealso{
  \code{\link{row}} and \code{\link{col}} for determining row and column
  indexes; in fact, these are special cases of \code{slice.index}
  corresponding to \code{MARGIN} equal to 1 and 2, respectively when \code{x}
  is a matrix.
}
\examples{
x <- array(1 : 24, c(2, 3, 4))
slice.index(x, 2)
}
\keyword{array}
\eof
\name{slotOp}
\title{Extract Slots}
\alias{@}
\description{
  Extract tbe contents of a slot in a object with a formal class
  structure.
}
\usage{
object@name
}
\arguments{
  \item{object}{An object from a formally defined class.}
  \item{name}{The character-string name of the slot.}
}
\details{
  These operators support the formal classes of package \pkg{methods}.
  See \code{\link[methods]{slot}} for further details.
  Currently there is no checking that the object is an instance of a
  class.
}
\seealso{
  \code{\link{Extract}},
  \code{\link[methods]{slot}}
}
\keyword{manip}
\eof
\name{socketSelect}
\alias{socketSelect}
\title{Wait on Socket Connections}
\usage{
socketSelect(socklist, write = FALSE, timeout = NULL)
}
\arguments{
  \item{socklist}{list of open socket connections}
  \item{write}{logical. If \code{TRUE} wait for corresponding socket to
               become available for writing; otherwise wait for it to become
               available for reading.}
  \item{timeout}{numeric or \code{NULL}. Time in seconds to wait for a
                 socket to become available; \code{NULL} means wait
                 indefinitely.}
}
\description{
  Waits for the first of several socket connections to become available.  
}
\value{Logical the same length as \code{socklist} indicating
  whether the corresponding socket connection is available for
  output or input, depending on the corresponding value of \code{write}.
}
\details{
  The values in \code{write} are recycled if necessary to make up a
  logical vector the same length as \code{socklist}. Socket connections
  can appear more than once in \code{socklist}; this can be useful if
  you want to determine whether a socket is available for reading or
  writing.
}
\examples{
\dontrun{
## test whether socket connection s is available for writing or reading
socketSelect(list(s,s),c(TRUE,FALSE),timeout=0)
}
}
\keyword{connection}
\eof
\name{solve}
\title{Solve a System of Equations}
\usage{
solve(a, b, \dots)

\method{solve}{default}(a, b, tol, LINPACK = FALSE, \dots)
}
\alias{solve}
\alias{solve.default}
\arguments{
  \item{a}{a square numeric or complex matrix containing the coefficients of
    the linear system.}
  \item{b}{a numeric or complex vector or matrix giving the right-hand
    side(s) of the linear system.  If missing, \code{b} is taken to be
    an identity matrix and \code{solve} will return the inverse of \code{a}.}
  \item{tol}{the tolerance for detecting linear dependencies in the
    columns of \code{a}.  If \code{LINPACK} is \code{TRUE} the default
    is \code{1e-7}, otherwise it is \code{.Machine$double.eps}. Future
    versions of R may use a tighter tolerance. Not presently used with
    complex matrices \code{a}.}
  \item{LINPACK}{logical. Should LINPACK be used (for compatibility with
    \R < 1.7.0)?  Otherwise LAPACK is used.}
  \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{
  \code{a} or \code{b} can be complex, but this uses double complex
  arithmetic which might not be available on all platforms and LAPACK
  will always be used.

  The row and column names of the result are taken from the column
  names of \code{a} and of \code{b} respectively.  As from \R 1.7.0
  if \code{b} is missing the column names of the result are the row
  names of \code{a}.  No check is made that the column names of \code{a}
  and the row names of \code{b} are equal.

  For back-compatibility \code{a} can be a (real) QR decomposition,
  although \code{\link{qr.solve}} should be called in that case.
  \code{\link{qr.solve}} can handle non-square systems.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{solve.qr}} for the \code{qr} method,
  \code{\link{chol2inv}} for inverting from the Choleski factor
  \code{\link{backsolve}}, \code{\link{qr.solve}}.
}
\examples{
hilbert <- function(n) { i <- 1:n; 1 / outer(i - 1, i, "+") }
h8 <- hilbert(8); h8
sh8 <- solve(h8)
round(sh8 \%*\% h8, 3)

A <- hilbert(4)
A[] <- as.complex(A)
## might not be supported on all platforms
try(solve(A))
}
\keyword{algebra}
\eof
\name{sort}
\alias{sort}
\alias{is.unsorted}
\title{Sorting or Ordering Vectors}
\description{
  Sort (or \emph{order}) a numeric or complex vector (partially) into
  ascending (or descending) order.
}
\usage{
sort(x, partial = NULL, na.last = NA, decreasing = FALSE,
     method = c("shell", "quick"), index.return = FALSE)
is.unsorted(x, na.rm = FALSE)
}
\arguments{
  \item{x}{a numeric or complex vector.}
  \item{partial}{a vector of indices for partial sorting.}
  \item{na.last}{for controlling the treatment of \code{NA}s.
    If \code{TRUE}, missing values in the data are put last; if
    \code{FALSE}, they are put first; if \code{NA}, they are removed.}
  \item{decreasing}{logical.  Should the sort be increasing or decreasing?}
  \item{method}{character specifying the algorithm used.}
  \item{index.return}{logical indicating if the ordering index vector should
    be returned as well; this is only available for the default
  \code{na.last = NA}.}
  \item{na.rm}{logical.  Should missing values be removed?}
}
\details{
  If \code{partial} is not \code{NULL}, it is taken to contain indices
  of elements of \code{x} which are to be placed in their correct
  positions by partial sorting.  After the sort, the values specified in
  \code{partial} are in their correct position in the sorted array.  Any
  values smaller than these values are guaranteed to have a smaller
  index in the sorted array and any values which are greater are
  guaranteed to have a bigger index in the sorted array.

  The sort order for character vectors will depend on the collating
  sequence of the locale in use: see \code{\link{Comparison}}.

  \code{is.unsorted} returns a logical indicating if \code{x} is sorted
  increasingly, i.e., \code{is.unsorted(x)} is true if \code{any(x !=
    sort(x))} (and there are no \code{NA}s).

  \code{method = "shell"} uses Shellsort (an \eqn{O(n^{4/3})} variant
  from Sedgewick (1996)).  If \code{x} has names a stable sort is used,
  so ties are not reordered.  (This only matters if names are present.)

  Method \code{"quick"} uses Singleton's Quicksort implementation and is
  only available when \code{x} is numeric (double or integer) and
  \code{partial} is \code{NULL}.  It is normally somewhat faster than
  Shellsort (perhaps twice as fast on vectors of length a million) but
  has poor performance in the rare worst case.
  (Peto's modification using a pseudo-random midpoint is used to make
  the worst case rarer.)  This is not a stable sort, and ties may be
  reordered.
}
\value{
  For \code{sort} the sorted vector unless
  \code{index.return} is true, when the result is
  a list with components named \code{x} and \code{ix} containing the
  sorted numbers and the ordering index vector.  In the latter case,
  if \code{method == "quick"} ties may be reversed in the ordering,
  unlike \code{sort.list}, as quicksort is not stable.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Sedgewick, R. (1986)
  A new upper bound for Shell sort.
  \emph{J. Algorithms} \bold{7}, 159--173.

  Singleton, R. C. (1969) An efficient algorithm for sorting with
  minimal storage: Algorithm 347.
  \emph{Communications of the ACM} \bold{12}, 185--187.
}
\seealso{
  \code{\link{order}}, \code{\link{rank}}.
}
\examples{
require(stats)
data(swiss)
x <- swiss$Education[1:25]
x; sort(x); sort(x, partial = c(10, 15))
median # shows you another example for 'partial'

## illustrate 'stable' sorting (of ties):
sort(c(10:3,2:12), method = "sh", index=TRUE) # is stable
## $x : 2  3  3  4  4  5  5  6  6  7  7  8  8  9  9 10 10 11 12
## $ix: 9  8 10  7 11  6 12  5 13  4 14  3 15  2 16  1 17 18 19
sort(c(10:3,2:12), method = "qu", index=TRUE) # is not
## $x : 2  3  3  4  4  5  5  6  6  7  7  8  8  9  9 10 10 11 12
## $ix: 9 10  8  7 11  6 12  5 13  4 14  3 15 16  2 17  1 18 19
##        ^^^^^

\dontrun{## Small speed comparison simulation:
N <- 2000
Sim <- 20
rep <- 50 # << adjust to your CPU
c1 <- c2 <- numeric(Sim)
for(is in 1:Sim){
  x <- rnorm(N)
  gc()  ## sort should not have to pay for gc
  c1[is] <- system.time(for(i in 1:rep) sort(x, method = "shell"))[1]
  c2[is] <- system.time(for(i in 1:rep) sort(x, method = "quick"))[1]
  stopifnot(sort(x, meth = "s") == sort(x, meth = "q"))
}
100 * rbind(ShellSort = c1, QuickSort = c2)
cat("Speedup factor of quick sort():\n")
summary({qq <- c1 / c2; qq[is.finite(qq)]})

## A larger test
x <- rnorm(1e6)
gc()
system.time(x1 <- sort(x, method = "shell"))
gc()
system.time(x2 <- sort(x, method = "quick"))
stopifnot(identical(x1, x2))
}}
\keyword{univar}
\keyword{manip}
\keyword{arith}
\eof
\name{source}
\title{Read R Code from a File or a Connection}
\usage{
source(file, local = FALSE, echo = verbose, print.eval = echo,
       verbose = getOption("verbose"),  prompt.echo = getOption("prompt"),
       max.deparse.length = 150, chdir = FALSE)
}
\alias{source}
\arguments{
  \item{file}{a connection or a character string giving the name
    of the file or URL to read from.}
  \item{local}{if \code{local} is \code{FALSE}, the statements scanned
    are evaluated in the user's workspace (the global environment),
    otherwise in the environment calling \code{source}.}
  \item{echo}{logical; if \code{TRUE}, each expression is printed
    after parsing, before evaluation.}
  \item{print.eval}{logical; if \code{TRUE}, the result of
    \code{eval(i)} is printed for each expression \code{i}; defaults
    to \code{echo}.}
  \item{verbose}{if \code{TRUE}, more diagnostics (than just
    \code{echo = TRUE}) are printed during parsing and evaluation of
    input, including extra info for \bold{each} expression.}
  \item{prompt.echo}{character; gives the prompt to be used if
    \code{echo = TRUE}.}
  \item{max.deparse.length}{integer; is used only if \code{echo} is
    \code{TRUE} and gives the maximal length of the \dQuote{echo} of a
    single expression.}
  \item{chdir}{logical; if \code{TRUE}, the R working directory is
    changed to the directory containing \code{file} for evaluating.}
}
\description{
  \code{source} causes \R to accept its input from the named file (the
  name must be quoted). Input is read from that file until the end of
  the file is reached.   \code{\link{parse}} is used to scan the
  expressions in, they are then evaluated sequentially in the chosen
  environment.
}
\details{
  All versions of \R accept input from a connection with end of line
  marked by LF (as used on Unix), CRLF (as used on DOS/Windows)
  or CR (as used on classic MacOS).  The final line can be incomplete, that
  is missing the final EOL marker.

  If \code{\link{options}}("keep.source") is true (the default), the
  source of functions is kept so they can be listed exactly as input.
  This imposes a limit of 128K chars on the function size and a nesting
  limit of 265.  Use \code{option(keep.source = FALSE)} when these
  limits might take effect: if exceeded they generate an error.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link[utils]{demo}} which uses \code{source};
  \code{\link{eval}}, \code{\link{parse}} and \code{\link{scan}};
  \code{\link{options}("keep.source")}.
}
\keyword{file}
\keyword{programming}
\keyword{connection}
\eof
\name{split}
\title{Divide into Groups}
\alias{split}
\alias{split.default}
\alias{split.data.frame}
\alias{split<-}
\alias{split<-.default}
\alias{split<-.data.frame}
\alias{unsplit}
\description{
  \code{split} divides the data in the vector \code{x} into the groups
  defined by \code{f}.  The assignment forms replace values
  corresponding to such a division.  Unsplit reverses the effect of
  \code{split}.
}
\usage{
split(x, f)
split(x, f) <- value
unsplit(value, f)
}
\arguments{
  \item{x}{vector or data frame containing values to be divided into groups.}
  \item{f}{a \dQuote{factor} such that \code{factor(f)} defines the
    grouping, or a list of such factors in which case their interaction
    is used for the grouping.}
  \item{value}{a list of vectors or data frames compatible with a
    splitting of \code{x}}
}
\details{
  \code{split} and \code{split<-} are generic functions with default and
  \code{data.frame} methods.

  \code{f} is recycled as necessary and if the length of \code{x} is not
  a multiple of the length of \code{f} a warning is printed.
  \code{unsplit} works only with  lists of vectors. The data frame
  method can also be used to split a matrix into a list of matrices,
  and the assignment form likewise, provided they are invoked
  explicitly.

  Any missing values in \code{f} are dropped together with the
  corresponding values of \code{x}.
}
\value{
  The value returned from \code{split} is a list of vectors containing
  the values for the groups.  The components of the list are named by
  the \emph{used} factor levels given by \code{f}.  (If \code{f} is
  longer than \code{x} then some of the components will be of zero length.)

  The assignment forms return their right hand side. \code{unsplit}
  returns a vector for which \code{split(x, f)} equals \code{value}
}
\seealso{
  \code{\link{cut}}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
require(stats)
n <- 10; nn <- 100
g <- factor(round(n * runif(n * nn)))
x <- rnorm(n * nn) + sqrt(as.numeric(g))
xg <- split(x, g)
boxplot(xg, col = "lavender", notch = TRUE, varwidth = TRUE)
sapply(xg, length)
sapply(xg, mean)

## Calculate z-scores by group

z <- unsplit(lapply(split(x, g), scale), g)
tapply(z, g, mean)

# or

z <- x
split(z, g) <- lapply(split(x, g), scale)
tapply(z, g, sd)

## Split a matrix into a list by columns
ma <- cbind(x = 1:10, y = (-4:5)^2)
split(ma, col(ma))

split(1:10, 1:2)
}
\keyword{category}
\eof
\name{sprintf}
\alias{sprintf}
\title{Use C-style String Formatting Commands}
\description{
  A wrapper for the C function \code{sprintf}, that
  returns a character vector of length one containing a formatted
  combination of text and variable values.
}
\usage{
sprintf(fmt, \dots)
}
\arguments{
  \item{fmt}{a format string.}
  \item{\dots}{values to be passed into \code{fmt}. Only logical,
    integer, real and character vectors are accepted, and only the first
    value is read from each vector.}
}
\details{
  This is a wrapper for the system \code{sprintf} C-library function.  
  Attempts are made to
  check that the mode of the values passed match the format supplied,
  and \R's special values (\code{NA}, \code{Inf}, \code{-Inf} and
  \code{NaN}) are handled correctly.
  
  The following is abstracted from K&R (see References, below).  The
  string \code{fmt} contains normal characters, which are passed through
  to the output string, and also special characters that operate on the
  arguments provided through \code{\dots}.  Special characters start
  with a \code{\%} and terminate with one of the letters in the set
  \code{difeEgGs\%}.  These letters denote the following types:

  \describe{
    \item{\code{d,i}}{Integer value}

    \item{\code{f}}{Double precision value, in decimal notation of the form
      "[-]mmm.ddd".  The number of decimal places is specified by the
      precision: the default is 6; a precision of 0 suppresses the decimal point.}

    \item{\code{e,E}}{Double precision value, in decimal notation of the form
      \code{[-]m.ddde[+-]xx} or \code{[-]m.dddE[+-]xx}}

    \item{\code{g,G}}{Double precision value, in \code{\%e} or
      \code{\%E} format if the exponent is less than -4 or greater than or
      equal to the precision, and \code{\%f} format otherwise}

    \item{\code{s}}{Character string}

    \item{\code{\%}}{Literal \code{\%} (none of the formatting
      characters given below are permitted in this case)}
  }

  In addition, between the initial \code{\%} and the terminating
  conversion character there may be, in any order:

  \describe{
    \item{\code{m.n}}{Two numbers separated by a period, denoting the
      field width (\code{m}) and the precision (\code{n})}
    \item{\code{-}}{Left adjustment of converted argument in its field}
    \item{\code{+}}{Always print number with sign}
    \item{a space}{Prefix a space if the first number is not a sign}
    \item{\code{0}}{For numbers, pad to the field width with leading zeros}
  }
}

\value{
  A character vector of length one.  Character \code{NA}s are converted
  to \code{"NA"}.
}

\references{
  Kernighan, B. W. and Ritchie, D. M. (1988)
  \emph{The C Programming Language.} Second edition, Prentice Hall.
  describes the format options in table B-1 in the Appendix.
}

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

\seealso{
  \code{\link{formatC}} for a way of formatting vectors of
  numbers in a similar fashion.

  \code{\link{paste}} for another way of
  creating a vector combining text and values.
}

\examples{
% Escape all the '%' here !
## be careful with the format: most things in R are floats

sprintf("\%s is \%f feet tall\n", "Sven", 7) # OK
try(sprintf("\%s is \%i feet tall\n", "Sven", 7)) # not OK
sprintf("\%s is \%i feet tall\n", "Sven", as.integer(7)) # OK again

## use a literal \% :

sprintf("\%.0f\%\% said yes (out of a sample of size \%.0f)", 66.666, 3)

## various formats of pi :

sprintf("\%f", pi)
sprintf("\%.3f", pi)
sprintf("\%1.0f", pi)
sprintf("\%5.1f", pi)
sprintf("\%05.1f", pi)
sprintf("\%+f", pi)
sprintf("\% f", pi)
sprintf("\%-10f", pi)# left justified
sprintf("\%e", pi)
sprintf("\%E", pi)
sprintf("\%g", pi)
sprintf("\%g",   1e6 * pi) # -> exponential
sprintf("\%.9g", 1e6 * pi) # -> "fixed"
sprintf("\%G", 1e-6 * pi)

## no truncation:
sprintf("\%1.f",101)

## More sophisticated:

lapply(c("a", "ABC", "and an even longer one"),
       function(ch) sprintf("10-string '\%10s'", ch))

sapply(1:18, function(n)
       sprintf(paste("e with \%2d digits = \%.",n,"g",sep=""),
               n, exp(1)))
}
\keyword{print}
\keyword{character}
\eof
\name{stack}
\alias{stack}
\alias{stack.default}
\alias{stack.data.frame}
\alias{unstack}
\alias{unstack.default}
\alias{unstack.data.frame}
\title{Stack or Unstack Vectors from a Data Frame or List}
\description{
  Stacking vectors concatenates multiple vectors into a single vector
  along with a factor indicating where each observation originated.
  Unstacking reverses this operation.
}
\usage{
stack(x, \dots)
\method{stack}{default}(x, \dots)
\method{stack}{data.frame}(x, select, \dots)

unstack(x, \dots)
\method{unstack}{default}(x, form, \dots)
\method{unstack}{data.frame}(x, form = formula(x), \dots)
}
\arguments{
  \item{x}{object to be stacked or unstacked}
  \item{select}{expression, indicating variables to select from a
    data frame}
  \item{form}{a two-sided formula whose left side evaluates to the
    vector to be unstacked and whose right side evaluates to the
    indicator of the groups to create.  Defaults to \code{formula(x)}
    in \code{unstack.data.frame}.}
  \item{\dots}{further arguments passed to or from other methods.}
}
\details{
  The \code{stack} function is used to transform data available as
  separate columns in a data frame or list into a single column that can
  be used in an analysis of variance model or other linear model.  The
  \code{unstack} function reverses this operation. 
}
\value{
  \code{unstack} produces a list of columns according to the formula
  \code{form}.  If all the columns have the same length, the resulting
  list is coerced to a data frame.
  
  \code{stack} produces a data frame with two columns
  \item{values}{the result of concatenating the selected vectors in
    \code{x}}
  \item{ind}{a factor indicating from which vector in \code{x} the
    observation originated}
}
\author{Douglas Bates}
\seealso{
  \code{\link[stats]{lm}}, \code{\link[stats]{reshape}}
}
\examples{
require(stats)
data(PlantGrowth)
formula(PlantGrowth)         # check the default formula
pg <- unstack(PlantGrowth)   # unstack according to this formula
pg
stack(pg)                    # now put it back together
stack(pg, select = -ctrl)    # omitting one vector
}
\keyword{manip}
\eof
\name{stackloss}
\docType{data}
\alias{stackloss}
\alias{stack.loss}
\alias{stack.x}
\title{Brownlee's Stack Loss Plant Data}
\description{
  Operational data of a plant for the oxidation of ammonia to nitric
  acid.
}
\usage{data(stackloss)}
\format{
  \code{stackloss} is a data frame with 21 observations on 4 variables.

  \tabular{rll}{
    [,1] \tab \code{Air Flow}   \tab Flow of cooling air\cr
    [,2] \tab \code{Water Temp} \tab Cooling Water Inlet
    Temperature\cr
    [,3] \tab  \code{Acid Conc.} \tab Concentration of acid [per
    1000, minus 500]\cr
    [,4] \tab  \code{stack.loss} \tab Stack loss\cr
  }

  For compatibility with S-PLUS, the data sets \code{stack.x}, a matrix
  with the first three (independent) variables of the data frame, and
  \code{stack.loss}, the numeric vector giving the fourth (dependent)
  variable, are provided as well.
}
\source{
  Brownlee, K. A. (1960, 2nd ed. 1965)
  \emph{Statistical Theory and Methodology in Science and Engineering}.
  New York: Wiley. pp. 491--500.
}
\details{
  \dQuote{Obtained from 21 days of operation of a plant for the
    oxidation of ammonia (NH\eqn{_3}{3}) to nitric acid
    (HNO\eqn{_3}{3}).  The nitric oxides produced are absorbed in a
    countercurrent absorption tower}.
  (Brownlee, cited by Dodge, slightly reformatted by MM.)

  \code{Air Flow} represents the rate of operation of the plant.
  \code{Water Temp} is the temperature of cooling water circulated
  through coils in the absorption tower.
  \code{Acid Conc.} is the concentration of the acid circulating, minus
  50, times 10: that is, 89 corresponds to 58.9 per cent acid.
  \code{stack.loss} (the dependent variable) is 10 times the percentage
  of the ingoing ammonia to the plant that escapes from the absorption
  column unabsorbed; that is, an (inverse) measure of the over-all
  efficiency of the plant.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Dodge, Y. (1996)
  The guinea pig of multiple regression. In:
  \emph{Robust Statistics, Data Analysis, and Computer Intensive
    Methods; In Honor of Peter Huber's 60th Birthday}, 1996,
  \emph{Lecture Notes in Statistics} \bold{109}, Springer-Verlag, New York.
}
\examples{
data(stackloss)
summary(lm.stack <- lm(stack.loss ~ stack.x))
}
\keyword{datasets}

\eof
\name{standardGeneric}
\alias{standardGeneric}
\title{Formal Method System Placeholders}
\description{
  Routines which are primitives used with the \pkg{methods} package.
  They should not be used without it and do not need to be called
  directly in any case.
}
\usage{
standardGeneric(f)
}
\details{
  \code{standardGeneric} dispatches the method defined for a generic
  function \code{f}, using the actual arguments in the frame from which
  it is called.
}
\author{ John Chambers }
\keyword{programming}
\keyword{internal}
\eof
\name{state}
\docType{data}
\alias{state}
\alias{state.abb}
\alias{state.area}
\alias{state.center}
\alias{state.division}
\alias{state.name}
\alias{state.region}
\alias{state.x77}
\title{US State Facts and Figures}
\description{Data sets related to the 50 states of the United States of
  America.}
\usage{data(state)}
\details{
  \R currently contains the following \dQuote{state} data sets.  Note
  that all data are arranged according to alphabetical order of the
  state names.
  \describe{
    \item{\code{state.abb}:}{character vector of 2-letter abbreviations
      for the state names.}
    \item{\code{state.area}:}{numeric vector of state areas (in square
      miles).}
    \item{\code{state.center}:}{ list with components named \code{x} and
      \code{y} giving the approximate geographic center of each state in
      negative longitude and latitude.  Alaska and Hawaii are placed
      just off the West Coast.}
    \item{\code{state.division}:}{factor giving state divisions (New
      England, Middle Atlantic, South Atlantic, East South Central, West
      South Central, East North Central, West North Central, Mountain,
      and Pacific).}
    \item{\code{state.name}:}{character vector giving the full state
      names.}
    \item{\code{state.region}:}{factor giving the region (Northeast,
      South, North Central, West) that each state belongs to.}
    \item{\code{state.x77}:}{matrix with 50 rows and 8 columns giving
      the following statistics in the respective columns.
      \describe{
      	\item{\code{Population}:}{population estimate as of July 1,
	  1975}
       	\item{\code{Income}:}{per capita income (1974)}
       	\item{\code{Illiteracy}:}{illiteracy (1970, percent of
	  population)}
       	\item{\code{Life Exp}:}{life expectancy in years (1969--71)}
       	\item{\code{Murder}:}{murder and non-negligent manslaughter rate
	  per 100,000 population (1976)}
       	\item{\code{HS Grad}:}{percent high-school graduates (1970)}
       	\item{\code{Frost}:}{mean number of days with minimum
	  temperature below freezing (1931--1960) in capital or large
	  city}
       \item{\code{Area}:}{land area in square miles}
    }}
  }
}
\source{
  U.S. Department of Commerce, Bureau of the Census (1977)
  \emph{Statistical Abstract of the United States}.

  U.S. Department of Commerce, Bureau of the Census (1977)
  \emph{County and City Data Book}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\keyword{datasets}
\eof
\name{stop}
\title{Stop Function Execution}
\usage{
stop(\dots, call. = TRUE)
geterrmessage()
}
\alias{stop}
\alias{geterrmessage}
\arguments{
  \item{\dots}{character vectors (which are pasted together with no
    separator), a condition object, or \code{NULL}.}
  \item{call.}{logical, indicating if the call should become part of the
    error message.}
}
\description{
  \code{stop} stops execution of the current expression and executes
  an error action.

  \code{geterrmessage} gives the last error message.
}
\details{
  The error action is controlled by error handlers established within
  the executing code and by the current default error handler set by
  \code{options(error=)}.  The error is first signaled as if using
  \code{\link{signalCondition}()}.  If there are no handlers or if all handlers
  return, then the error message is printed (if
  \code{options("show.error.messages")} is true) and the default error
  handler is used.  The default behaviour (the \code{NULL}
  error-handler) in interactive use is to return to the top level
  prompt or the top level browser, and in non-interactive use to
  (effectively) call \code{\link{q}("no", status=1, runLast=FALSE}).
  The default handler stores the error message in a buffer; it can be
  retrieved by \code{geterrmessage()}.  It also stores a trace of
  the call stack that can be retrieved by \code{\link{traceback}()}.

  Errors will be truncated to \code{getOption("warning.length")}
  characters, default 1000.
}
\value{
  \code{geterrmessage} gives the last error message, as character string
  ending in \code{"\\n"}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{warning}}, \code{\link{try}} to catch errors and retry,
  and \code{\link{options}} for setting error handlers.
  \code{\link{stopifnot}} for validity testing.  \code{tryCatch}
  and \code{withCallingHandlers} can be used to establish custom handlers
  while executing an expression.
}
\examples{
options(error = expression(NULL))# don't stop on stop(.)  << Use with CARE! >>

iter <- 12
if(iter > 10) stop("too many iterations")

tst1 <- function(...) stop("dummy error")
tst1(1:10,long,calling,expression)

tst2 <- function(...) stop("dummy error", call. = FALSE)
tst2(1:10,long,calling,expression,but.not.seen.in.Error)

options(error = NULL)# revert to default
}
\keyword{environment}
\keyword{programming}
\keyword{error}
\eof
\name{stopifnot}
\alias{stopifnot}
\concept{assertion}
\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

op <- 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(op)# revert to previous error handler
}
\keyword{environment}
\keyword{programming}
\keyword{error}
\eof
\name{strptime}
\alias{format.POSIXct}
\alias{format.POSIXlt}
\alias{strftime}
\alias{strptime}
\alias{as.character.POSIXt}
\alias{ISOdatetime}
\alias{ISOdate}
\title{Date-time Conversion Functions to and from Character}
\description{
  Functions to convert between character representations and objects of
  classes \code{"POSIXlt"} and \code{"POSIXct"} representing calendar
  dates and times.
}
\usage{
\method{format}{POSIXct}(x, format = "", tz = "", usetz = FALSE, \dots)
\method{format}{POSIXlt}(x, format = "", usetz = FALSE, \dots)

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

strftime(x, format="", usetz = FALSE, \dots)
strptime(x, format)

ISOdatetime(year, month, day, hour, min, sec, tz = "")
ISOdate(year, month, day, hour = 12, min = 0, sec = 0, tz = "GMT")
}
\arguments{
  \item{x}{An object to be converted.}
  \item{tz}{A timezone specification to be used for the conversion.
    System-specific, but \code{""} is the current time zone, and
    \code{"GMT"} is UTC.}
  \item{format}{A character string.  The default is
    \code{"\%Y-\%m-\%d \%H:\%M:\%S"} if any component has a time
    component which is not midnight, and \code{"\%Y-\%m-\%d"}
    otherwise.}
  \item{\dots}{Further arguments to be passed from or to other methods.}
  \item{usetz}{logical.  Should the timezone be appended to the output?
    This is used in printing time, and as a workaround for problems with
    using \code{"\%Z"} on most Linux systems.}
  \item{year, month, day}{numerical values to specify a day.}
  \item{hour, min, sec}{numerical values for a time within a day.}
}
\details{
  \code{strftime} is an alias for \code{format.POSIXlt}, and
  \code{format.POSIXct} first converts to class \code{"POSIXct"} by
  calling \code{\link{as.POSIXct}}. Note that only that conversion
  depends on the time zone.

  The usual vector re-cycling rules are applied to \code{x} and
  \code{format} so the answer will be of length that of the longer of the
  vectors.
  
  Locale-specific conversions to and from character strings are used
  where appropriate and available.  This affects the names of the days
  and months, the AM/PM indicator (if used) and the separators in
  formats such as \code{\%x} and \code{\%X}.

  The details of the formats are system-specific, but the following are
  defined by the ISO C / POSIX standard for \code{strftime} and are
  likely to be widely available.  Any character in the format string other than
  the \code{\%} escape sequences 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 (or 68) are prefixed by 20 and 70--99 by 19.}
    \item{\code{\%Y}}{Year with century.}
    \item{\code{\%z}}{(output only.) Offset from Greenwich, so
      \code{-0800} is 8 hours west of Greenwich.}
    \item{\code{\%Z}}{(output only.) Time zone as a character
      string (empty if not available).}
  }
  Where leading zeros are shown they will be used on output but are
  optional on input.

  Also defined in the current standards but less widely implemented
  (e.g. not for output on Windows) are
  \describe{
    \item{\code{\%F}}{Equivalent to \%Y-\%m-\%d (the ISO 8601 date
      format).}
    \item{\code{\%g}}{The last two digits of the week-based year
      (see \code{\%V}).}
    \item{\code{\%G}}{The week-based year (see \code{\%V}) as a decimal
      number.}
    \item{\code{\%u}}{Weekday as a decimal number (1--7, Monday is 1).}
    \item{\code{\%V}}{Week of the year as decimal number (00--53).
      If the week (starting on Monday) containing 1 January has four or
      more days in the new year, then it is considered week 1. Otherwise, it
      is the last week of the previous year, and the next week is week 1.}
  }

  Other format specifiers in common use include
  \describe{
    \item{\code{\%D}}{Locale-specific date format such as \code{\%m/\%d/\%y}.}
    \item{\code{\%k}}{The 24-hour clock time with single digits preceded
      by a blank.}
    \item{\code{\%l}}{The 12-hour clock time with single digits preceded
      by a blank.}
    \item{\code{\%n}}{Newline on output, arbitrary whitespace on input.}
    \item{\code{\%r}}{The 12-hour clock time (using the locale's AM or PM).}
    \item{\code{\%R}}{Equivalent to \code{\%H:\%M}.}
    \item{\code{\%t}}{Newline on output, arbitrary whitespace on input.}
    \item{\code{\%T}}{Equivalent to \code{\%H:\%M:\%S}.}
  }
  There are also \code{\%O[dHImMSUVwWy]} which may emit numbers in an
  alternative local-dependent format (e.g. roman numerals), and
  \code{\%E[cCyYxX]} which can use an alternative \sQuote{era}
  (e.g. a different religious calendar).  Which of these are supported is
  OS-dependent.
    
  \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 it specifies a date
  incorrectly, reliable implementations will give an error and the date
  is reported as \code{NA}.  Unfortunately some common implementations
  (such as \samp{glibc}) are unreliable and guess at the intended meaning.

  If the timezone specified is invalid on your system, what happens is
  system-specific but it will probably be ignored.

  OS facilities will probably not print years before 1CE (aka 1AD)
  correctly.
}
\references{
  International Organization for Standardization (1988, 1997, \dots)
  \emph{ISO 8601. Data elements and interchange formats --
    Information interchange -- Representation of dates and times.}
  The 1997 version is available on-line at
  \url{ftp://ftp.qsl.net/pub/g1smd/8601v03.pdf}
}
\seealso{
  \link{DateTimeClasses} for details of the date-time classes;
  \code{\link{locales}} to query or set a locale.
  
  Your system's help pages on \code{strftime} and \code{strptime} to
  see how to specify their formats.
#ifdef windows
  Windows users will find no help page for \code{strptime}: code based
  on \samp{glibc} is used (with corrections), so all the format
  specifiers described here are supported, but with no alternative
  number representation nor era available in any locale.
#endif
}
\examples{
## locale-specific version of date()
format(Sys.time(), "\%a \%b \%d \%X \%Y \%Z")

## read in date info in format 'ddmmmyyyy'
## This will give NA(s) in some locales; setting the C locale
## as in the commented lines will overcome this on most systems.
## lct <- Sys.getlocale("LC_TIME"); Sys.setlocale("LC_TIME", "C")
x <- c("1jan1960", "2jan1960", "31mar1960", "30jul1960")
z <- strptime(x, "\%d\%b\%Y")
## Sys.setlocale("LC_TIME", lct)
z

## read in date/time info in format 'm/d/y h:m:s'
dates <- c("02/27/92", "02/27/92", "01/14/92", "02/28/92", "02/01/92")
times <- c("23:03:20", "22:29:56", "01:03:30", "18:21:03", "16:56:26")
x <- paste(dates, times)
z <- strptime(x, "\%m/\%d/\%y \%H:\%M:\%S")
z
}
\keyword{utilities}
\keyword{chron}
\eof
\name{strsplit}
\alias{strsplit}
\title{Split the Elements of a Character Vector}
\description{
  Split the elements of a character vector \code{x} into substrings
  according to the presence of substring \code{split} within them.
}
\usage{
strsplit(x, split, extended = TRUE, fixed = FALSE, perl = FALSE)
}
\arguments{
  \item{x}{
    character vector, each element of which is to be split.
  }
  \item{split}{
    character vector containing \link{regular expression}(s)
    (unless \code{fixed = TRUE}) to use as \dQuote{split}.  If empty
    matches occur, in particular if \code{split} has length 0, \code{x} is
    split into single characters.  If \code{split} has length greater than
    1, it is re-cycled along \code{x}.
  }
  \item{extended}{
    logical. if \code{TRUE}, extended regular expression matching
    is used, and if \code{FALSE} basic regular expressions are used.
  }
  \item{fixed}{
    logical. If \code{TRUE} match string exactly, otherwise
    use regular expressions.
  }
  \item{perl}{
    logical. Should perl-compatible regexps be used?
    Has priority over \code{extended}.
  }
}
\value{
  A list of length \code{length(x)} the \code{i}-th element of which
  contains the vector of splits of \code{x[i]}.
}
\details{
  Arguments \code{x} and \code{split} will be coerced to character, so
  you will see uses with \code{split = NULL} to mean
  \code{split = character(0)}, including in the examples below.

  Note that spltting into single characters can be done via
  \code{split=character(0)} or \code{split=""}; the two are equivalent
  as from \R 1.9.0.

  A missing value of \code{split} does not split the the corresponding
  element(s) of \code{x} at all.
}
\section{Warning}{
  The standard regular expression code has been reported to be very slow
  or give errors when applied to extremely long character strings
  (tens of thousands of characters or more): the code used when
  \code{perl=TRUE} seems faster and more reliable for such usages.
}
\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}}.

  \link{regular expression} for the details of the pattern specification.
}
\examples{
noquote(strsplit("A text I want to display with spaces", NULL)[[1]])

x <- c(as = "asfef", qu = "qwerty", "yuiop[", "b", "stuff.blah.yech")
# split x on the letter e
strsplit(x,"e")

unlist(strsplit("a.b.c", "."))
## [1] "" "" "" "" ""
## Note that 'split' is a regexp!
## If you really want to split on '.', use
unlist(strsplit("a.b.c", "\\\\."))
## [1] "a" "b" "c"
## or
unlist(strsplit("a.b.c", ".", fixed = TRUE))

## a useful function: rev() for strings
strReverse <- function(x)
	sapply(lapply(strsplit(x, NULL), rev), paste, collapse="")
strReverse(c("abc", "Statistics"))

## get the first names of the members of R-core
a <- readLines(file.path(R.home(),"AUTHORS"))[-(1:8)]
a <- a[(0:2)-length(a)]
(a <- sub(" .*","", a))
# and reverse them
strReverse(a)
}
\keyword{character}
\eof
\name{structure}
\title{Attribute Specification}
\usage{
structure(.Data, \dots)
}
\alias{structure}
\arguments{
  \item{.Data}{an object which will have
    various attributes attached to it.}
  \item{\dots}{attributes, specified in \code{tag=value}
    form, which will be attached to data.}
}
\description{
  \code{structure} returns the given object with its attributes set.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
structure(1:6, dim = 2:3)
}
\keyword{attribute}
\keyword{manip}
\eof
\name{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,
  possible sentence ends at line breaks are not considered specially.
  
  Indentation is relative to the number of characters in the prefix
  string.
}
\examples{
## Read in file 'THANKS'.
x <- paste(readLines(file.path(R.home(), "THANKS")), collapse = "\n")
## Split into paragraphs and remove the first three ones
x <- unlist(strsplit(x, "\n[ \t\n]*\n"))[-(1:3)]
## Join the rest
x <- paste(x, collapse = "\n\n")
## Now for some fun:
writeLines(strwrap(x, width = 60))
writeLines(strwrap(x, width = 60, indent = 5))
writeLines(strwrap(x, width = 60, exdent = 5))
writeLines(strwrap(x, prefix = "THANKS> "))
}
\keyword{character}
\eof
\name{subset}
\alias{subset}
\alias{subset.default}
\alias{subset.data.frame}
\title{Subsetting Vectors and Data Frames}
\description{
  Return subsets of vectors or data frames which meet conditions.
}
\usage{
subset(x, \dots)

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

\method{subset}{data.frame}(x, subset, select, drop = FALSE, \dots)
}
\arguments{
  \item{x}{object to be subsetted.}
  \item{subset}{logical expression.}
  \item{select}{expression, indicating columns to select from a
    data frame.}
  \item{drop}{passed on to \code{[} indexing operator.}
  \item{\dots}{further arguments to be passed to or from other methods.}
}
\details{
  For ordinary vectors, the result is simply
  \code{x[subset & !is.na(subset)]}.

  For data frames, the \code{subset} argument works similarly on the
  rows.  Note that \code{subset} will be evaluated in the data frame, so
  columns can be referred to (by name) as variables.

  The \code{select} argument exists only for the method for data frames.
  It works by
  first replacing names in the selection expression with the
  corresponding column numbers in the data frame and then using the
  resulting integer vector to index the columns.  This allows the use
  of the standard indexing conventions so that for example ranges of
  columns can be specified easily.

  Setting \code{drop=TRUE} will drop unused levels from factors in a
  data frame. The default is to retain them.
}
\value{
  An object similar to \code{x} contain just the selected elements (for
  a vector), rows and columns (for a data frame), and so on.
}
\author{Peter Dalgaard}
\seealso{
  \code{\link{[}}, % = ./Extract.Rd
  \code{\link{transform}}
}
\examples{
data(airquality)
subset(airquality, Temp > 80, select = c(Ozone, Temp))
subset(airquality, Day == 1, select = -Temp)
subset(airquality, select = Ozone:Wind)

with(airquality, subset(Ozone, Temp > 80))
}
\keyword{manip}
\eof
\name{substitute}
\title{Substituting and Quoting Expressions}
\usage{
substitute(expr, env=<<see below>>)
quote(expr)
}
\alias{substitute}
\alias{quote}
\description{
  \code{substitute} returns the parse tree for the (unevaluated)
  expression \code{expr}, substituting any variables bound in
  \code{env}.

  \code{quote} simply returns its argument. The argument is not evaluated
  and can be any R expression.
}
\arguments{
  \item{expr}{Any syntactically valid \R expression}
  \item{env}{An environment or a list object. Defaults to the
    current evaluation environment.}
}
\details{
  The typical use of \code{substitute} is to create informative labels
  for data sets and plots.
  The \code{myplot} example below shows a simple use of this facility.
  It uses the functions \code{\link{deparse}} and \code{substitute}
  to create labels for a plot which are character string versions
  of the actual arguments to the function \code{myplot}.

  Substitution takes place by examining each component of the parse tree
  as follows: If it is not a bound symbol in \code{env}, it is
  unchanged. If it is a promise object, i.e., a formal argument to a
  function or explicitly created using \code{\link{delay}()}, the expression
  slot of the promise replaces the symbol. If it is an ordinary
  variable, its value is substituted, unless \code{env} is
  \code{\link{.GlobalEnv}} in which case the symbol is left unchanged.
}
\value{
  The \code{\link{mode}} of the result is generally \code{"call"} but
  may in principle be any type. In particular, single-variable
  expressions have mode \code{"name"} and constants have the
  appropriate base mode.
}
\note{
  Substitute works on a purely lexical basis. There is no guarantee
  that the resulting expression makes any sense.

  Substituting and quoting often causes confusion when the argument is
  \code{expression(\dots)}. The result is a call to the
  \code{\link{expression}} constructor function and needs to be evaluated
  with \code{\link{eval}} to give the actual expression object.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{missing}} for argument \dQuote{missingness},
  \code{\link{bquote}} for partial substitution,
  \code{\link{sQuote}} and \code{\link{dQuote}} for adding quotation
  marks to strings.
}
\examples{
(s.e <- substitute(expression(a + b), list(a = 1)))  #> expression(1 + b)
(s.s <- substitute( a + b,            list(a = 1)))  #> 1 + b
c(mode(s.e), typeof(s.e)) #  "call", "language"
c(mode(s.s), typeof(s.s)) #   (the same)
# but:
(e.s.e <- eval(s.e))          #>  expression(1 + b)
c(mode(e.s.e), typeof(e.s.e)) #  "expression", "expression"

substitute(x <- x + 1, list(x=1)) # nonsense

myplot <- function(x, y)
    plot(x, y, xlab=deparse(substitute(x)),
         ylab=deparse(substitute(y)))

## Simple examples about lazy evaluation, etc:

f1 <- function(x, y = x)             { x <- x + 1; y }
s1 <- function(x, y = substitute(x)) { x <- x + 1; y }
s2 <- function(x, y) { if(missing(y)) y <- substitute(x); x <- x + 1; y }
a <- 10
f1(a)# 11
s1(a)# 11
s2(a)# a
typeof(s2(a))# "symbol"
}
\keyword{programming}
\keyword{data}
\eof
\name{substr}
\alias{substr}
\alias{substring}
\alias{substr<-}
\alias{substring<-}
\title{Substrings of a Character Vector}
\usage{
substr(x, start, stop)
substring(text, first, last = 1000000)
substr(x, start, stop) <- value
substring(text, first, last = 1000000) <- value
}
\arguments{
  \item{x, text}{a character vector}
  \item{start, first}{integer. The first element to be replaced.}
  \item{stop, last}{integer. The last element to be replaced.}
  \item{value}{a character vector, recycled if necessary.}
}
\description{
  Extract or replace substrings in a character vector.
}
\value{
  For \code{substr}, a character vector of the same length as \code{x}.

  For \code{substring}, a character vector of length the longest of the
  arguments.
}
\details{
  \code{substring} is compatible with S, with \code{first} and
  \code{last} instead of \code{start} and \code{stop}.
  For vector arguments, it expands the arguments cyclically to the
  length of the longest \emph{provided} none are of zero length.

  When extracting, if \code{start} is larger than the string length then
  \code{""} is returned.

  For the replacement functions, if \code{start} is larger than the
  string length then no replacement is done.  If the portion to be
  replaced is longer than the replacement string, then only the
  portion the length of the string is replaced.
}
\note{
  The S4 version of \code{substring<-} ignores \code{last}; this version
  does not.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole. (\code{substring}.)
}
\seealso{
 \code{\link{strsplit}}, \code{\link{paste}}, \code{\link{nchar}}.
}
\examples{
substr("abcdef",2,4)
substring("abcdef",1:6,1:6)
## strsplit is more efficient ...

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

substring(x, 2) <- c("..", "+++")
x
}
\keyword{character}
\eof
\name{sum}
\title{Sum of Vector Elements}
\usage{
sum(\dots, na.rm=FALSE)
}
\alias{sum}
\description{
  \code{sum} returns the sum of all the values
  present in its arguments.
  If \code{na.rm} is \code{FALSE} an \code{NA}
  value in any of the arguments will cause
  a value of \code{NA} to be returned, otherwise
  \code{NA} values are ignored.
}
\arguments{
  \item{\dots}{numeric or complex vectors.}
  \item{na.rm}{logical. Should missing values be removed?}
}
\value{
  The sum. If all of \code{\dots} are of type integer, then so is the
  sum, and in that case the result will be \code{NA} (with a warning)
  if integer overflow occurs.

  NB: the sum of an empty set is zero, by definition.
}
\details{
  This is a generic function: methods can be defined for it
  directly or via the \code{\link{Summary}} group generic.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\keyword{arith}
\eof
\name{summary}
\alias{summary}
\alias{summary.default}
\alias{summary.data.frame}
\alias{summary.factor}
\alias{summary.matrix}
\title{Object Summaries}
\description{
  \code{summary} is a generic function used to produce result summaries
  of the results of various model fitting functions.  The function
  invokes particular \code{\link[utils]{methods}} which depend on the
  \code{\link[base]{class}} of the first argument.
}
\usage{
summary(object, \dots)

\method{summary}{default}(object, \dots, digits = max(3, getOption("digits")-3))
\method{summary}{data.frame}(object, maxsum = 7,
       digits = max(3, getOption("digits")-3), \dots)
\method{summary}{factor}(object, maxsum = 100, \dots)
\method{summary}{matrix}(object, \dots)
}
\arguments{
  \item{object}{an object for which a summary is desired.}
  \item{maxsum}{integer, indicating how many levels should be shown for
    \code{\link{factor}}s.}
  \item{digits}{integer, used for number formatting with
    \code{\link{signif}()} (for \code{summary.default}) or
    \code{\link{format}()} (for \code{summary.data.frame}).}
  \item{\dots}{additional arguments affecting the summary produced.}
}
\details{
    For \code{\link{factor}}s, the frequency of the first \code{maxsum - 1}
    most frequent levels is shown, where the less frequent levels are
    summarized in \code{"(Others)"} (resulting in \code{maxsum} frequencies).

    The functions \code{summary.lm} and \code{summary.glm} are examples
    of particular methods which summarise the results produced by
    \code{\link[stats]{lm}} and \code{\link[stats]{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[stats]{anova}},
  \code{\link[stats]{summary.glm}},
  \code{\link[stats]{summary.lm}}.
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S}.
  Wadsworth \& Brooks/Cole.
}
\examples{
data(attenu)
summary(attenu, digits = 4) #-> summary.data.frame(...), default precision
summary(attenu $ station, maxsum = 20) #-> summary.factor(...)

lst <- unclass(attenu$station) > 20 # logical with NAs
## summary.default() for logicals -- different from *.factor:
summary(lst)
summary(as.factor(lst))
}
\keyword{methods}
\eof
\name{svd}
\alias{svd}
\alias{La.svd}
\title{Singular Value Decomposition of a Matrix}
\usage{
svd(x, nu = min(n, p), nv = min(n, p), LINPACK = FALSE)
La.svd(x, nu = min(n, p), nv = min(n, p), method = c("dgesdd", "dgesvd"))
}
\arguments{
  \item{x}{a matrix whose SVD decomposition is to be computed.}
  \item{nu}{the number of left  singular vectors to be computed.
    This must be one of \code{0}, \code{nrow(x)} and \code{ncol(x)},
    except for \code{method = "dgesdd"}.}
  \item{nv}{the number of right singular vectors to be computed.
    This must be one of \code{0} and \code{ncol(x)}.}
  \item{LINPACK}{logical. Should LINPACK be used (for compatibility with
    \R < 1.7.0)?}
  \item{method}{The LAPACK routine to use in the real case.}
}
\description{
  Compute the singular-value decomposition of a rectangular matrix.
}
\details{
  The singular value decomposition plays an important role in many
  statistical techniques.  \code{svd} and \code{La.svd} provide two
  slightly different interfaces.  The main functions used are
  the LAPACK routines DGESDD and ZGESVD; \code{svd(LINPACK=TRUE)}
  provides an interface to the LINPACK routine DSVDC, purely for
  backwards compatibility.
  
  \code{La.svd} provides an interface to both the LAPACK routines
  DGESVD and DGESDD.  The latter is usually substantially faster
  if singular vectors are required: see
  \url{http://www.cs.berkeley.edu/~demmel/DOE2000/Report0100.html}.
  Most benefit is seen with an optimized BLAS system.
  Using \code{method="dgesdd"} requires IEEE 754 arithmetic.  Should
  this not be supported on your platform, \code{method="dgesvd"} is
  used, with a warning.

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

  Unsuccessful results from the underlying LAPACK code will result in an
  error giving a positive error code: these can only be interpreted by
  detailed study of the FORTRAN code.
}
\value{
  The SVD decomposition of the matrix as computed by LINPACK,
  \deqn{ \bold{X = U D V'},} where \eqn{\bold{U}} and \eqn{\bold{V}} are
  orthogonal, \eqn{\bold{V'}} means \emph{V transposed}, and
  \eqn{\bold{D}} is a diagonal matrix with the singular
  values \eqn{D_{ii}}{D[i,i]}.  Equivalently, \eqn{\bold{D = U' X V}},
  which is verified in the examples, below.

  The returned value is a list with components
  \item{d}{a vector containing the singular values of \code{x}.}
  \item{u}{a matrix whose columns contain the left singular vectors of
    \code{x}, present if \code{nu > 0}}
  \item{v}{a matrix whose columns contain the right singular vectors of
    \code{x}, present if \code{nv > 0}.}

  For \code{La.svd} the return value replaces \code{v} by \code{vt}, the
  (conjugated if complex) transpose of \code{v}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

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

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

  \code{\link{capabilities}} to test for IEEE 754 arithmetic.
}
\examples{
hilbert <- function(n) { i <- 1:n; 1 / outer(i - 1, i, "+") }
X <- hilbert(9)[,1:6]
(s <- svd(X))
D <- diag(s$d)
s$u \%*\% D \%*\% t(s$v) #  X = U D V'
t(s$u) \%*\% X \%*\% s$v #  D = U' X V
}
\keyword{algebra}
\keyword{array}

\eof
\name{sweep}
\alias{sweep}
\title{Sweep out Array Summaries}
\description{
  Return an array obtained from an input array by sweeping out a summary
  statistic.
}
\usage{
sweep(x, MARGIN, STATS, FUN="-", \dots)
}
\arguments{
  \item{x}{an array.}
  \item{MARGIN}{a vector of indices giving the extents of \code{x}
    which correspond to \code{STATS}.}
  \item{STATS}{the summary statistic which is to be swept out.}
  \item{FUN}{the function to be used to carry out the sweep.  In the
    case of binary operators such as \code{"/"} etc., the function name
    must be quoted.}
  \item{\dots}{optional arguments to \code{FUN}.}
}
\value{
  An array with the same shape as \code{x}, but with the summary
  statistics swept out.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{apply}} on which \code{sweep} used to be based;
  \code{\link{scale}} for centering and scaling.
}
\examples{
require(stats) # for median
data(attitude)
med.att <- apply(attitude, 2, median)
sweep(data.matrix(attitude), 2, med.att)# subtract the column medians
}
\keyword{array}
\keyword{iteration}
\eof
\name{swiss}
\docType{data}
\alias{swiss}
\title{Swiss Fertility and Socioeconomic Indicators (1888) Data}
\description{
  Standardized fertility measure and socio-economic indicators for each
  of 47 French-speaking provinces of Switzerland at about 1888.
}
\usage{data(swiss)}
\format{
  A data frame with 47 observations on 6 variables, \emph{each} of which
  is in percent, i.e., in \eqn{[0,100]}.

  \tabular{rll}{
    [,1] \tab Fertility \tab \eqn{I_g}{Ig}, \dQuote{common standardized
    fertility measure}\cr
    [,2] \tab Agriculture\tab \% of males involved in agriculture
    as occupation\cr
    [,3] \tab Examination\tab \% \dQuote{draftees} receiving highest mark
    on army examination\cr
    [,4] \tab Education \tab \% education beyond primary school for
    \dQuote{draftees}.\cr
    [,5] \tab Catholic \tab \% catholic (as opposed to \dQuote{protestant}).\cr
    [,6] \tab Infant.Mortality\tab live births who live less than 1
    year.
  }

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

  Switzerland, in 1888, was entering a period known as the
  \dQuote{demographic transition}; i.e., its fertility was beginning to
  fall from the high level typical of underdeveloped countries.

  The data collected are for 47 French-speaking \dQuote{provinces} at
  about 1888.

  Here, all variables are scaled to \eqn{[0,100]}, where in the
  original, all but \code{"Catholic"} were scaled to \eqn{[0,1]}.
}
\source{
  Project \dQuote{16P5}, pages 549--551 in

  Mosteller, F. and Tukey, J. W. (1977)
  \emph{Data Analysis and Regression: A Second Course in Statistics}.
  Addison-Wesley, Reading Mass.

  indicating their source as
  \dQuote{Data used by permission of Franice van de Walle. Office of
  Population Research, Princeton University, 1976.  Unpublished data
  assembled under NICHD contract number No 1-HD-O-2077.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\note{
  Files for all 182 districts in 1888 and other years are available at
  \url{http://opr.princeton.edu/archive/eufert/switz.html}.

  They state that variables \code{Examination} and \code{Education}
  are averages for 1887, 1888 and 1889.
}
\examples{
data(swiss)
pairs(swiss, panel = panel.smooth, main = "swiss data",
      col = 3 + (swiss$Catholic > 50))
summary(lm(Fertility ~ . , data = swiss))
}
\keyword{datasets}
\eof
\name{switch}
\alias{switch}
\title{Select One of a List of Alternatives}
\description{
  \code{switch} evaluates \code{EXPR} and accordingly chooses one of the
  further arguments (in \code{\dots}).
}
\usage{
switch(EXPR, \dots)
}
\arguments{
  \item{EXPR}{an expression evaluating to a number or a character
    string.}
  \item{\dots}{the list of alternatives, given explicitly.}
}
\details{
  If the value of \code{EXPR} is an integer between 1 and
  \code{nargs()-1} then the corresponding element of \code{\dots} is
  evaluated and the result returned.

  If \code{EXPR} returns a character string then that string is used to
  match the names of the elements in \code{\dots}.  If there is an exact
  match then that element is evaluated and returned if there is one,
   otherwise the next element is chosen, e.g.,
  \code{switch("cc", a=1, cc=, d=2)} evaluates to \code{2}.

  In the case of no match, if there's a further argument in \code{switch}
  that one is returned, otherwise \code{NULL}.
}
\section{Warning}{
  Beware of partial matching: an alternative \code{E = foo} will match
  the first argument \code{EXPR} unless that is named. See the examples
  for good practice in naming the first argument.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
require(stats)
centre <- function(x, type) {
  switch(type,
        mean = mean(x),
        median = median(x),
        trimmed = mean(x, trim = .1))
}
x <- rcauchy(10)
centre(x, "mean")
centre(x, "median")
centre(x, "trimmed")

ccc <- c("b","QQ","a","A","bb")
for(ch in ccc) cat(ch,":",switch(EXPR = ch, a=1,    b=2:3),            "\n")
for(ch in ccc) cat(ch,":",switch(EXPR = ch, a=,A=1, b=2:3, "Otherwise: last"),"\n")

## Numeric EXPR don't allow an 'otherwise':
for(i in c(-1:3,9))  print(switch(i, 1,2,3,4))
}
\keyword{programming}
\eof
\name{sys.parent}
\alias{sys.parent}
\alias{sys.call}
\alias{sys.calls}
\alias{sys.frame}
\alias{sys.frames}
\alias{sys.nframe}
\alias{sys.function}
\alias{sys.parents}
\alias{sys.on.exit}
\alias{sys.status}
\alias{parent.frame}
\title{Functions to Access the Function Call Stack}
\description{
  These functions provide access to \code{\link{environment}}s
  (\dQuote{frames} in S terminology) associated with functions further
  up the calling stack.
}
\usage{
sys.call(which = 0)
sys.frame(which = 0)
sys.nframe()
sys.function(n = 0)
sys.parent(n = 1)

sys.calls()
sys.frames()
sys.parents()
sys.on.exit()
sys.status()
parent.frame(n = 1)
}
\arguments{
  \item{which}{the frame number if non-negative, the number of generations
    to go back if negative. (See the Details section.)}
  \item{n}{the number of frame generations to go back.}
}
\details{
  \code{\link{.GlobalEnv}} is given number 0 in the list of frames.
  Each subsequent function evaluation increases the frame stack by 1
  and the environment for evaluation of that function is returned by
  \code{sys.frame} with the appropriate index.

  The parent of a function evaluation is the environment in which the
  function was called. It is not necessarily numbered one less than the frame
  number of the current evaluation, nor is it the environment within
  which the function was defined.  \code{sys.parent} returns the number
  of the parent frame if \code{n} is 1 (the default), the grandparent if
  \code{n} is 2, and so on. \code{sys.frame} returns the environment
  associated with a given frame number.

  \code{sys.call} and \code{sys.frame} both accept integer values
  for the argument \code{which}.  Non-negative values of
  \code{which} are normal frame numbers whereas negative values are counted
  back from the frame number of the current evaluation.

  \code{sys.nframe} returns the number of the current frame in that
  list. \code{sys.function} gives the definition of the function
  currently being evaluated in the frame \code{n} generations back.
  
  \code{sys.frames} gives a list of all the active frames and
  \code{sys.parents} gives the indices of the parent frames of each
  of the frames.
  
  Notice that even though the \code{sys.}\emph{xxx} functions (except
  \code{sys.status}) are
  interpreted, their contexts are not counted nor are they reported.
  There is no access to them.

  \code{sys.status()} returns a list with components \code{sys.calls},
  \code{sys.parents} and \code{sys.frames}.

  \code{sys.on.exit()} retrieves the expression stored for use by
  \code{\link{on.exit}} in the function currently being evaluated.
  (Note that this differs from S, which returns a list of expressions
  for the current frame and its parents.)

  \code{parent.frame(n)} is a convenient shorthand for
  \code{sys.frame(sys.parent(n))} (implemented slightly more efficiently).
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole. (not \code{parent.frame}.)
}
\seealso{
  \code{\link{eval}} for the usage of \code{sys.frame} and \code{parent.frame}.
}
\examples{
ff <- function(x) gg(x)
gg <- function(y) sys.status()
str(ff(1))

gg <- function(y) {
    ggg <- function() {
        cat("current frame is", sys.nframe(), "\n")
        cat("parents are", sys.parents(), "\n")
        print(sys.function(0)) # ggg
        print(sys.function(2)) # gg
    }
    if(y > 0) gg(y-1) else ggg()
}
gg(3)

t1 <- function() {
  aa <- "here"
  t2 <- function() {
    ## in frame 2 here
    cat("current frame is", sys.nframe(), "\n")
    str(sys.calls()) ## list with two components t1() and t2()
    cat("parents are frame nos", sys.parents(), "\n") ## 0 1
    print(ls(envir=sys.frame(-1))) ## [1] "aa" "t2"
    invisible()
  }
  t2()
}
t1()

test.sys.on.exit <- function() {
  on.exit(print(1))
  ex <- sys.on.exit()
  str(ex)
  cat("exiting...\n")
}
test.sys.on.exit()
## gives 'language print(1)', prints 1 on exit
}
\keyword{programming}
\keyword{data}
\eof
\name{sys.source}
\alias{sys.source}
\title{Parse and Evaluate Expressions from a File}
\description{
  Parses expressions in the given file, and then successively evaluates
  them in the specified environment.
}
\usage{
sys.source(file, envir = NULL, chdir = FALSE,
           keep.source = getOption("keep.source.pkgs"))
}
\arguments{
  \item{file}{a character string naming the file to be read from}
  \item{envir}{an \R object specifying the environment in which the
    expressions are to be evaluated.  May also be a list or an integer.
    The default value \code{NULL} corresponds to evaluation in the base
    environment.  This is probably not what you want; you should
    typically supply an explicit \code{envir} argument.}
  \item{chdir}{logical; if \code{TRUE}, the \R working directory is
    changed to the directory containing \code{file} for evaluating.}
  \item{keep.source}{logical.  If \code{TRUE}, functions \dQuote{keep
      their source} including comments, see
    \code{\link{options}(keep.source = *)} for more details.}
}
\details{
  For large files, \code{keep.source = FALSE} may save quite a bit of
  memory.
%%FIXME:  the following paragraph should be somewhere it's likely to be seen
  In order for the code being evaluated to use the correct environment
  (for example, in global assignments), source code in packages should
  call 
  \code{\link{topenv}}(), which will return the namespace, if any, the
  environment set up by \code{sys.source}, or the global environment
  if a saved image is being used.
}
\seealso{\code{\link{source}}, and \code{\link{library}} which uses
  \code{sys.source}.
}
\keyword{file}
\keyword{utilities}
\eof
\name{system.file}
\title{Find Names of R System Files}
\usage{
system.file(\dots, package = "base", lib.loc = NULL)
}
\alias{system.file}
\arguments{
  \item{\dots}{character strings, specifying subdirectory and file(s)
    within some package.  The default, none, returns the
    root of the package.  Wildcards are not supported.}
  \item{package}{a character string with the name of a single package.
    An error occurs if more than one package name is given.}
  \item{lib.loc}{a character vector with path names of \R libraries, or
    \code{NULL}.  The default value of \code{NULL} corresponds to all
    libraries currently known.  If the default is used, the loaded
    packages are searched before the libraries.}
}
\description{
  Finds the full file names of files in packages etc.
}
\value{
  A character vector of positive length, containing the file names
  that matched \code{\dots}, or the empty string, \code{""}, if none
  matched.  If matching the root of a package, there is no trailing
  separator.

  As a special case, \code{system.file()} gives the root of the
  \pkg{base} package only.
}
\seealso{\code{\link{list.files}}}
\examples{
system.file()                  # The root of the 'base' package
system.file(package = "stats") # The root of package 'stats'
system.file("INDEX")
system.file("help", "AnIndex", package = "splines")
}
\keyword{file}
\keyword{utilities}
\eof
\name{system.time}
\title{CPU Time Used}
\usage{
system.time(expr)
unix.time(expr)
}
\alias{system.time}
\alias{unix.time}
\arguments{
  \item{expr}{Valid \R expression to be \dQuote{timed}}
}
\description{Return CPU (and other) times that \code{expr} used.
}    
\details{
  \code{system.time} calls the builtin \code{\link{proc.time}},
  evaluates \code{expr}, and then calls \code{proc.time} once more,
  returning the difference between the two \code{proc.time} calls.

  The values returned by the \code{proc.time} are (on Unix) those
  returned by the C library function \code{times}(3v), if available.

  \code{unix.time} is an alias of \code{system.time}, for
  compatibility reasons.
}
\value{
  A numeric vector of length 5 containing the user cpu, system cpu, elapsed,
  subproc1, subproc2 times. The subproc times are the user and
  system cpu time used by child processes (and so are usually zero).
#ifdef windows
  On Windows the subproc times are not available and so are always
  \code{NA}. The first two components are not available on Windows 9x,
  and so are reported as \code{NA}; they do return real values on
  Windows NT4/2000/XP.
#endif

  The resolution of the times will be system-specific; it is common for
  them to be recorded to of the order of 1/100 second, and elapsed
  time is rounded to the nearest 1/100.
}
#ifdef unix
\note{
  It is possible to compile \R without support for \code{system.time},
  when all the values will be \code{NA}.
}
#endif
\seealso{
  \code{\link{proc.time}}, \code{\link[stats]{time}} which is for time series.
}
\examples{
require(stats)
system.time(for(i in 1:100) mad(runif(1000)))
\dontrun{
exT <- function(n = 1000) {
  # Purpose: Test if system.time works ok;   n: loop size
  system.time(for(i in 1:n) x <- mean(rt(1000, df=4)))
}
#-- Try to interrupt one of the following (using Ctrl-C / Escape):
exT()                 #- about 3 secs on a 1GHz PIII
system.time(exT())    #~ +/- same
}}
\keyword{utilities}
\eof
\name{t}
\alias{t}
\alias{t.default}
\alias{t.data.frame}
\title{Matrix Transpose}
\description{
  Given a matrix or \code{\link{data.frame}} \code{x},
  \code{t} returns the transpose of \code{x}.
}
\usage{
t(x)
}
\arguments{
  \item{x}{a matrix or data frame, typically.}
}
\details{
  A data frame is first coerced to a matrix: see \code{\link{as.matrix}}.
  When \code{x} is a vector, it is treated as \dQuote{column}, i.e., the
  result is a 1-row matrix.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{aperm}} for permuting the dimensions of arrays.
}
\examples{
a <- matrix(1:30, 5,6)
ta <- t(a) ##-- i.e.,  a[i, j] == ta[j, i] for all i,j :
for(j in seq(ncol(a)))
  if(! all(a[, j] == ta[j, ])) stop("wrong transpose")
}
\keyword{array}
\eof
\name{table}
\title{Cross Tabulation and Table Creation}
\alias{table}
\alias{summary.table}
\alias{print.summary.table}
\alias{as.data.frame.table}
\alias{as.table}
\alias{as.table.default}
\alias{is.table}
\description{
  \code{table} uses the cross-classifying factors to build a contingency
  table of the counts at each combination of factor levels.
}
\usage{
table(\dots, exclude = c(NA, NaN), dnn = list.names(...), deparse.level = 1)
as.table(x, \dots)
is.table(x)

\method{as.data.frame}{table}(x, row.names = NULL, optional = FALSE, \dots)
}
\arguments{
  \item{\dots}{objects which can be interpreted as factors (including
    character strings), or a list (or data frame) whose components can
    be so interpreted}
  \item{exclude}{values to use in the exclude argument of \code{factor}
    when interpreting non-factor objects; if specified, levels to remove
    from all factors in \dots.}
  \item{dnn}{the names to be given to the dimensions in the result (the
    \emph{dimnames names}).}
  \item{deparse.level}{controls how the default \code{dnn} is
    constructed.  See details.}
  \item{x}{an arbitrary \R object, or an object inheriting from class
    \code{"table"} for the \code{as.data.frame} method.}
  \item{row.names}{a character vector giving the row names for the data
    frame.}
  \item{optional}{a logical controlling whether row names are set.
    Currently not used.}
}
\value{
  \code{table()} returns a \emph{contingency table}, an object of
  \code{\link[base]{class}} \code{"table"}, an array of integer values.

  There is a \code{summary} method for objects created by \code{table}
  or \code{\link[stats]{xtabs}}, which gives basic information and performs a
  chi-squared test for independence of factors (note that the function
  \code{\link[stats]{chisq.test}} in package \pkg{ctest} currently only
  handles 2-d tables).

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

  The \code{as.data.frame} method for objects inheriting from class
  \code{"table"} can be used to convert the array-based representation
  of a contingency table to a data frame containing the classifying
  factors and the corresponding counts (the latter as component
  \code{Freq}).  This is the inverse of \code{\link[stats]{xtabs}}.
}
\details{
  If the argument \code{dnn} is not supplied, the internal function
  \code{list.names} is called to compute the \sQuote{dimname names}.  If the
  arguments in \code{\dots} are named, those names are used.  For the
  remaining arguments, \code{deparse.level = 0} gives an empty name,
  \code{deparse.level = 1} uses the supplied argument if it is a symbol,
  and \code{deparse.level = 2} will deparse the argument.

  Only when \code{exclude} is specified (i.e., not by default), will
  \code{table} drop levels of factor arguments potentially.
}
\seealso{Use \code{\link[stats]{ftable}} for printing (and more) of
  multidimensional tables.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
require(stats) # for rpois and xtabs
## Simple frequency distribution
table(rpois(100,5))
data(warpbreaks)
attach(warpbreaks)
## Check the design:
table(wool, tension)
data(state)
table(state.division, state.region)
detach()

data(airquality)
# simple two-way contingency table
with(airquality, table(cut(Temp, quantile(Temp)), Month))

a <- letters[1:3]
table(a, sample(a))                    # dnn is c("a", "")
table(a, sample(a), deparse.level = 0) # dnn is c("", "")
table(a, sample(a), deparse.level = 2) # dnn is c("a", "sample(a)")

## xtabs() <-> as.data.frame.table() :
data(UCBAdmissions) ## already a contingency table
DF <- as.data.frame(UCBAdmissions)
class(tab <- xtabs(Freq ~ ., DF)) # xtabs & table
## tab *is* "the same" as the original table:
all(tab == UCBAdmissions)
all.equal(dimnames(tab), dimnames(UCBAdmissions))

a <- rep(c(NA, 1/0:3), 10)
table(a)
table(a, exclude=NULL)
b <- factor(rep(c("A","B","C"), 10))
table(b)
table(b, exclude="B")
d <- factor(rep(c("A","B","C"), 10), levels=c("A","B","C","D","E"))
table(d, exclude="B")

## NA counting:
is.na(d) <- 3:4
d <- factor(d, exclude=NULL)
d[1:7]
table(d, exclude = NULL)
}
\keyword{category}
\eof
\name{tabulate}
\title{Tabulation for Vectors}
\description{
  \code{tabulate} takes the integer-valued vector \code{bin} and counts
  the number of times each integer occurs in it. 
}
\usage{
tabulate(bin, nbins = max(1, bin))
}
\alias{tabulate}
\arguments{
    \item{bin}{a numeric vector (of positive integers), or a factor.}
    \item{nbins}{the number of bins to be used.}
}
\details{
   \code{tabulate} is used as the basis of the \code{\link{table}} function.
  
  If \code{bin} is a factor, its internal integer representation
  is tabulated.
  
  If the elements of \code{bin} are numeric but not integers,
  they are truncated to the nearest integer.
}
\value{
  An integer vector (without names).  There is a bin for each of the
  values \code{1, \dots, nbins}; values outside that range are (silently)
  ignored.
}
\seealso{
  \code{\link{table}}, \code{\link{factor}}.
}
\examples{
tabulate(c(2,3,5))
tabulate(c(2,3,3,5), nbins = 10)
tabulate(c(-2,0,2,3,3,5))  # -2 and 0 are ignored
tabulate(c(-2,0,2,3,3,5), nbins = 3)
tabulate(factor(letters[1:10]))
}
\keyword{arith}
\eof
\name{tapply}
\alias{tapply}
\title{Apply a Function Over a ``Ragged'' Array}
\description{
  Apply a function to each cell of a ragged array, that is to each
  (non-empty) group of values given by a unique combination of the
  levels of certain factors.
}
\usage{
tapply(X, INDEX, FUN = NULL, \dots, simplify = TRUE)
}
\arguments{
  \item{X}{an atomic object, typically a vector.}
  \item{INDEX}{list of factors, each of same length as \code{X}.}
  \item{FUN}{the function to be applied.  In the case of functions like
    \code{+}, \code{\%*\%}, etc., the function name must be quoted.  If
    \code{FUN} is \code{NULL}, tapply returns a vector which can be used
    to subscript the multi-way array \code{tapply} normally produces.}
  \item{\dots}{optional arguments to \code{FUN}.}
  \item{simplify}{If \code{FALSE}, \code{tapply} always returns an array
    of mode \code{"list"}.  If \code{TRUE} (the default), then if
    \code{FUN} always returns a scalar, \code{tapply} returns an array
    with the mode of the scalar.}
}
\value{
  When \code{FUN} is present, \code{tapply} calls \code{FUN} for each
  cell that has any data in it.  If \code{FUN} returns a single atomic
  value for each cell (e.g., functions \code{mean} or \code{var}) and
  when \code{simplify} is \code{TRUE}, \code{tapply} returns a multi-way
  \link{array} containing the values.  The array has the same number of
  dimensions as \code{INDEX} has components; the number of levels in a
  dimension is the number of levels (\code{nlevels()}) in the
  corresponding component of \code{INDEX}.

  Note that contrary to S, \code{simplify = TRUE} always returns an
  array, possibly 1-dimensional.

  If \code{FUN} does not return a single atomic value, \code{tapply}
  returns an array of mode \code{\link{list}} whose components are the
  values of the individual calls to \code{FUN}, i.e., the result is a
  list with a \code{\link{dim}} attribute.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  the convenience functions \code{\link{by}} and
  \code{\link[stats]{aggregate}} (using \code{tapply});
  \code{\link{apply}},
  \code{\link{lapply}} with its versions
  \code{\link{sapply}} and \code{\link{mapply}}.
}
\examples{
require(stats)
groups <- as.factor(rbinom(32, n = 5, p = .4))
tapply(groups, groups, length) #- is almost the same as
table(groups)

data(warpbreaks)
## contingency table from data.frame : array with named dimnames
tapply(warpbreaks$breaks, warpbreaks[,-1], sum)
tapply(warpbreaks$breaks, warpbreaks[, 3, drop = FALSE], sum)

n <- 17; fac <- factor(rep(1:3, len = n), levels = 1:5)
table(fac)
tapply(1:n, fac, sum)
tapply(1:n, fac, sum, simplify = FALSE)
tapply(1:n, fac, range)
tapply(1:n, fac, quantile)

## example of ... argument: find quarterly means
data(presidents)
tapply(presidents, cycle(presidents), mean, na.rm = TRUE)

ind <- list(c(1, 2, 2), c("A", "A", "B"))
table(ind)
tapply(1:3, ind) #-> the split vector
tapply(1:3, ind, sum)
}
\keyword{iteration}
\keyword{category}
\eof
\name{taskCallback}
\alias{addTaskCallback}
\alias{removeTaskCallback}
\title{Add or remove a top-level task callback}
\description{
  \code{addTaskCallback} registers an R function
  that is to be called each time a top-level task
  is completed.

  \code{removeTaskCallback} un-registers a function
  that was registered earlier via \code{addTaskCallback}.

  These provide low-level access to the internal/native
  mechanism for managing task-completion actions.
  One can use \code{\link{taskCallbackManager}}
  at the S-language level to manage S functions
  that are called at the completion of each task.
  This is easier and more direct.
}
\usage{
addTaskCallback(f, data = NULL, name = character(0))
removeTaskCallback(id)
}
\arguments{
  \item{f}{the function that is to be invoked each time a top-level task
    is successfully completed. This is called with 5 or 4 arguments
    depending on whether \code{data} is specified or not, respectively.
    The return value should be a logical value indicating whether to
    keep the callback in the list of active callbacks or discard it.}
  \item{data}{if specified, this is the 5-th argument in the call to the
    callback function \code{f}.}
  \item{id}{a string or an integer identifying the element in the
    internal callback list to be removed.
    Integer indices are 1-based, i.e the first element is 1.
    The names of currently registered handlers is available
    using \code{\link{getTaskCallbackNames}}
    and is also returned in a call to \code{\link{addTaskCallback}}.
  }
  \item{name}{character: names to be used.}
}
\value{
  \code{addTaskCallback} returns
  an integer value giving  the position in the list
  of task callbacks that this new callback occupies.
  This is only the current position of the callback.
  It can be used to remove the entry as long as
  no other values are removed from earlier positions
  in the list first.

  \code{removeTaskCallback} returns a logical value
  indicating whether the specified element was removed.
  This can fail (i.e., return \code{FALSE})
  if an incorrect name or index is given that does not
  correspond to the name or position of an element in the list.
}
\details{
Top-level tasks are individual expressions
rather than entire lines of input. Thus an input
line of the form \code{expression1 ; expression2}
will give rise to 2 top-level tasks.
  
A top-level task callback is called with the expression for the
top-level task, the result of the top-level task, a logical value
indicating whether it was successfully completed or not (always TRUE
at present), and a logical value indicating whether the result was
printed or not. If the \code{data} argument was specified in the call
to \code{addTaskCallback}, that value is given as the fifth argument.

The callback function should return a logical value.
If the value is FALSE, the callback is removed from the task
list and will not be called again by this mechanism.
If the function returns TRUE, it is kept in the list and
will be called on the completion of the next top-level task.
}
\note{
  This is an experimental feature and the interface may be changed
  in the future.

  There is also C-level access to top-level task callbacks
  to allow C routines rather than R functions be used.
}
\seealso{
  \code{\link{getTaskCallbackNames}}
  \code{\link{taskCallbackManager}}
  \url{http://developer.r-project.org/TaskHandlers.pdf}
}
\examples{
  times <- function(total = 3, str="Task a") {
    ctr <- 0

    function(expr, value, ok, visible) {
     ctr <<- ctr + 1
     cat(str, ctr, "\n")
     if(ctr == total) {
       cat("handler removing itself\n")
     }
     return(ctr < total)
    }
  }

  # add the callback that will work for
  # 4 top-level tasks and then remove itself.
  n <- addTaskCallback(times(4))

  # now remove it, assuming it is still first in the list.
  removeTaskCallback(n)

\dontrun{
 # There is no point in running this
 # as 
  addTaskCallback(times(4))

  sum(1:10)
  sum(1:10)
  sum(1:10)
  sum(1:10)
  sum(1:10)
}
}
}
\keyword{environment}
\eof
\name{taskCallbackManager}
\alias{taskCallbackManager}
\title{Create an R-level task callback manager}
\description{
  This provides an entirely S-language mechanism
  for managing callbacks or actions  that are invoked at
  the conclusion of each top-level task.  Essentially,
  we register a single R function from this manager
  with the underlying, native
  task-callback mechanism and this function handles invoking the other
  R callbacks under the control of the manager.
  The manager consists of a collection of functions that access shared
  variables to manage the list of user-level callbacks.
}
\usage{
taskCallbackManager(handlers = list(), registered = FALSE, verbose = FALSE)
}
\arguments{
  \item{handlers}{this can be a list of callbacks in which each element
    is a list with  an element  named \code{"f"}
    which is a callback function, and an optional
    element named \code{"data"} which is the 5-th argument to be
    supplied  to the callback when it is invoked.
    Typically this argument is not specified, and one uses \code{add} to
    register callbacks after the manager is created.}
  \item{registered}{a logical value indicating whether
    the \code{evaluate} function has already been registered
    with the internal task callback mechanism.
    This is usually \code{FALSE} and 
    the first time a callback is added
    via the \code{add} function, the
    \code{evaluate} function is automatically registered.
    One can control when the function is registered
    by specifying \code{TRUE} for this argument
    and calling \code{\link{addTaskCallback}} manually.
  }
  \item{verbose}{a logical value, which if \code{TRUE},
    causes information to be printed to the console
    about certain activities this dispatch manager performs.
    This is useful for debugging callbacks and the handler
    itself.
  }
}
\value{
  A list containing 6 functions:
  \item{add}{register a callback with this manager, giving the
    function, an optional 5-th argument, an optional name
    by which the callback is stored in the list,
    and a \code{register} argument which controls whether
    the \code{evaluate} function is registered with the internal
    C-level dispatch mechanism if necessary.}
  \item{remove}{remove an element from the manager's collection
    of callbacks, either by name or position/index.}
  \item{evaluate}{the \sQuote{real} callback function that is registered
    with the C-level dispatch mechanism and which invokes each of the
    R-level callbacks within this manager's control.}
  \item{suspend}{a function to set the suspend state
    of the manager. If it is suspended, none of the callbacks will be
    invoked when a task is completed. One sets the state by specifying
    a logical value for the \code{status} argument.
  }
  \item{register}{a function to register the \code{evaluate}
    function with the internal C-level dispatch mechanism. This is
    done automatically by the \code{add} function, but can be called
    manually.}
  \item{callbacks}{returns the list of callbacks being maintained by this
   manager.}
}
\note{
  This is an experimental feature and the interface may be changed
  in the future.
}
\seealso{
  \code{\link{addTaskCallback}}
  \code{\link{removeTaskCallback}}
  \code{\link{getTaskCallbackNames}}
  \url{http://developer.r-project.org/TaskHandlers.pdf}  
}
\examples{
   # create the manager
  h <- taskCallbackManager()

   # add a callback
  h$add(function(expr, value, ok, visible) {
                         cat("In handler\n")
                         return(TRUE)
                       }, name = "simpleHandler")

   # look at the internal callbacks.
  getTaskCallbackNames()

   # look at the R-level callbacks
  names(h$callback())
 
   #
  getTaskCallbackNames()
  removeTaskCallback("R-taskCallbackManager")
}
\keyword{environment}
\eof
\name{taskCallbackNames}
\alias{getTaskCallbackNames}
\title{Query the names of the current internal top-level task callbacks}
\description{
  This provides a way to get the names (or identifiers)
  for the currently registered task callbacks
  that are invoked at the conclusion of each top-level task.
  These identifiers can be used to remove a callback.
}
\usage{
getTaskCallbackNames()
}
\arguments{
}
\value{
  A character vector giving the name for each of the
  registered callbacks which are invoked when
  a top-level task is completed successfully.
  Each name is the one used when registering
  the callbacks and returned as the in the
  call to \code{\link{addTaskCallback}}. 
}
\note{
  One can use \code{\link{taskCallbackManager}}
  to manage user-level task callbacks,
  i.e., S-language functions, entirely within
  the S language and access the names
  more directly.
}
\seealso{
  \code{\link{addTaskCallback}}
  \code{\link{removeTaskCallback}}
  \code{\link{taskCallbackManager}}
  \url{http://developer.r-project.org/TaskHandlers.pdf}  
}
\examples{
  n <- addTaskCallback(function(expr, value, ok, visible) {
                         cat("In handler\n")
                         return(TRUE)
                       }, name = "simpleHandler")

  getTaskCallbackNames()

    # now remove it by name
  removeTaskCallback("simpleHandler")


  h <- taskCallbackManager()
  h$add(function(expr, value, ok, visible) {
                         cat("In handler\n")
                         return(TRUE)
                       }, name = "simpleHandler")
  getTaskCallbackNames()
  removeTaskCallback("R-taskCallbackManager")
}
\keyword{environment}
\eof
\name{tempfile}
\alias{tempfile}
\alias{tempdir}
\title{Create Names for Temporary Files}
\description{
  \code{tempfile} returns a vector of character strings which can be used as
  names for temporary files.
}
\usage{
tempfile(pattern = "file", tmpdir = tempdir())
tempdir()
}
\arguments{
  \item{pattern}{a non-empty character vector giving the initial part
    of the name.}
  \item{tmpdir}{a non-empty character vector giving the directory name}  
}
\value{
  For \code{tempfile} a character vector giving the names of possible
  (temporary) files. Note that no files are generated by
  \code{tempfile}.

  For \code{tempdir}, the path of the per-session temporary directory.
}
\details{
  If \code{pattern} has length greater than one then the result is of the
  same length giving a temporary file name for each component of
  \code{pattern}. 

  The names are very likely to be unique among calls to \code{tempfile}
  in an \R session and across simultaneous \R sessions.  The filenames are
  guaranteed not to be currently in use.

#ifdef unix
  The file name is made of the pattern, the process number in hex and a
  random suffix in hex.  By default, the filenames will be in the
  directory given by \code{tempdir()}.  This will be a subdirectory of
  the directory given by the environment variable \env{TMPDIR} if set,
  otherwise \code{"/tmp"}.
#endif
#ifdef windows
  By default, \code{tempdir()} gives a subdirectory of the first found
  of the environment variables \env{TMP}, \env{TEMP} and \env{R\_USER}
  (see \code{\link[utils]{Rconsole}}) which points to a writeable directory.
  If the path to the directory contains a space in any of the
  components, the path returned will use the shortnames version of the
  path.
#endif
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{\code{\link{unlink}} for deleting files.}
\examples{
tempfile(c("ab", "a b c"))   # give file name with spaces in!
}
\keyword{file}
\eof
\name{textConnection}
\alias{textConnection}
\title{Text Connections}
\description{
  Input and output text connections.
}
\usage{
textConnection(object, open = "r", local = FALSE)
}
\arguments{
  \item{object}{character.  A description of the connection. 
    For an input this is an \R character vector object, and for an output
    connection the name for the \R character vector to receive the
    output.
  }
  \item{open}{character.  Either \code{"r"} (or equivalently \code{""})
    for an input connection or \code{"w"} or \code{"a"} for an output
    connection.}
  \item{local}{logical.  Used only for output connections.  If \code{TRUE},
    output is assigned to a variable in the calling environment.  Otherwise
    the global environment is used.}
}
\details{
  An input text connection is opened and the character vector is copied
  at time the connection object is created, and \code{close}
  destroys the copy.

  An output text connection is opened and creates an \R character vector
  of the given name in the user's workspace or in the calling environment,
  depending on the value of the \code{local} argument.  This object will at all
  times hold the completed lines of output to the connection, and
  \code{\link{isIncomplete}} will indicate if there is an incomplete
  final line.  Closing the connection will output the final line,
  complete or not.  (A line is complete once it has been terminated by
  end-of-line, represented by \code{"\\n"} in \R.)

  Opening a text connection with \code{mode = "a"} will attempt to
  append to an existing character vector with the given name in the
  user's workspace or the calling environment.  If none is found (even
  if an object exists of the right name but the wrong type) a new
  character vector wil be created, with a warning.

  You cannot \code{seek} on a text connection, and \code{seek} will
  always return zero as the position.
}

\value{
  A connection object of class \code{"textConnection"} which inherits
  from class \code{"connection"}.
}

\note{
  As output text connections keep the character vector up to date
  line-by-line, they are relatively expensive to use, and it is often
  better to use an anonymous \code{\link{file}()} connection to collect
  output.

  On platforms where \code{vsnprintf} does not return the needed length
  of output (e.g., Windows) there is a 100,000 character limit on the
  length of line for output connections: longer lines will be truncated
  with a warning.
}
 
\seealso{
  \code{\link{connections}}, \code{\link{showConnections}},
  \code{\link{pushBack}}, \code{\link[utils]{capture.output}}.
}

\examples{
zz <- textConnection(LETTERS)
readLines(zz, 2)
scan(zz, "", 4)
pushBack(c("aa", "bb"), zz)
scan(zz, "", 4)
close(zz)

zz <- textConnection("foo", "w")
writeLines(c("testit1", "testit2"), zz)
cat("testit3 ", file=zz)
isIncomplete(zz)
cat("testit4\n", file=zz)
isIncomplete(zz)
close(zz)
foo

\dontrun{# capture R output: use part of example from help(lm)
zz <- textConnection("foo", "w")
ctl <- c(4.17, 5.58, 5.18, 6.11, 4.5, 4.61, 5.17, 4.53, 5.33, 5.14)
trt <- c(4.81, 4.17, 4.41, 3.59, 5.87, 3.83, 6.03, 4.89, 4.32, 4.69)
group <- gl(2, 10, 20, labels = c("Ctl", "Trt"))
weight <- c(ctl, trt)
sink(zz)
anova(lm.D9 <- lm(weight ~ group))
cat("\nSummary of Residuals:\n\n")
summary(resid(lm.D9))
sink()
close(zz)
cat(foo, sep = "\n")
}
}
\keyword{file}
\keyword{connection}
\eof
\name{tilde}
\alias{~}
\alias{tilde}
\title{Tilde Operator}
\description{
  Tilde is used to separate the left- and right-hand sides in model formula.
}
\usage{
y ~ model
}
\arguments{
  \item{y, model}{symbolic expressions.}
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical models.}
  Chapter 2 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
}
\seealso{\code{\link[stats]{formula}}}
\keyword{models}
\eof
\name{toString}
\alias{toString}
\alias{toString.default}

\title{toString Converts its Argument to a Character String}
\description{
  This is a helper function for \code{\link{format}}. It converts its argument
  to a string. If the argument is a vector then its elements are
  concatenated with a \code{,} as a separator. 
  Most methods should honor the width argument. 
  The minimum value for \code{width} is six. 
}
\usage{
toString(x, \dots)

\method{toString}{default}(x, width, \dots)
}
\arguments{
  \item{x}{The object to be converted.}
  \item{width}{The returned value is at most the first \code{width} characters.}
  \item{\dots}{Optional arguments for methods.}
}
\value{
  A character vector of length 1 is returned.
}
\author{ Robert Gentleman }

\seealso{ \code{\link{format}} }

\examples{
x <- c("a", "b", "aaaaaaaaaaa")
toString(x)
toString(x, width=8)
}
\keyword{utilities}
\eof
\name{trace}
\title{Interactive Tracing and Debugging of Calls to a Function or Method}
\alias{trace}
\alias{untrace}
\alias{tracingState}
%% internal
\alias{.primTrace}
\alias{.primUntrace}
\description{
  A call to \code{trace} allows you to insert debugging code (e.g., a
  call to \code{\link{browser}} or \code{\link[utils]{recover}}) at chosen
  places in any function.  A call to \code{untrace} cancels the tracing.
  Specified methods can be traced the same way, without tracing all
  calls to the function.  Trace code can be any \R expression.  Tracing
  can be temporarily turned on or off globally by calling \code{tracingState}.
}
\usage{
trace(what, tracer, exit, at, print, signature, where = topenv(parent.frame()))
untrace(what, signature = NULL, where = topenv(parent.frame()))

tracingState(on = NULL)
}
\arguments{
  \item{what}{The name (quoted or not) of a function to be traced or
    untraced.  More than one name can be given in the quoted form, and
    the same action will be applied to each one.}
  \item{tracer}{Either a function or an unevaluated expression.  The
    function will be called or the expression will be evaluated either
    at the beginning of the call, or before those steps in the call
    specified by the argument \code{at}.
    See the details section.}
  \item{exit}{ Either a function or an unevaluated expression.  The
    function will be called or the expression will be evaluated on
    exiting the function.
    See the details section.}
  \item{at}{optional numeric vector.  If supplied, \code{tracer}
    will be called just before the corresponding step in the body of the
    function.
    See the details section. }
  \item{print}{If \code{TRUE} (as per default), a descriptive line is
    printed before any trace expression is evaluated.}
  \item{signature}{ If this argument is supplied, it should be a
    signature for a method for function \code{what}.  In this case, the
    method, and \emph{not} the function itself, is traced.}
  \item{where}{the environment from which to look for the function to be
    traced; by default, the top-level environment of the call to
    \code{trace}.  If you put a call to \code{trace} into code in a
    package, you may need to specify \code{where=.GlobalEnv} if
    the package containing the call has a namespace, but the function
    you want to trace is somewhere on the search list.
  }
  \item{on}{logical; a call to \code{tracingState} returns \code{TRUE}
    if tracing is globally turned on, \code{FALSE} otherwise.  An
    argument of one or the other of those values sets the state.  If the
    tracing state is \code{FALSE}, none of the trace actions will
    actually occur (used, for example, by debugging functions to shut
    off tracing during debugging).}
}
\details{
  The \code{trace} function operates by constructing a revised version
  of the function (or of the method, if \code{signature} is supplied),
  and assigning the new object back where the original was found.
  If only the \code{what} argument is given, a line of trace printing is
  produced for each call to the function (back compatible with the
  earlier version of \code{trace}).

  The object constructed by \code{trace} is from a class that extends
  \code{"function"} and which contains the original, untraced version.
  A call to \code{untrace} re-assigns this version.

  If the argument \code{tracer} or \code{exit} is the name of a
  function, the tracing expression will be a call to that function, with
  no arguments.  This is the easiest and most common case, with the
  functions \code{\link{browser}} and \code{\link[utils]{recover}} the
  likeliest candidates; the former browses in the frame of the function
  being traced, and the latter allows browsing in any of the currently
  active calls.

  The \code{tracer} or \code{exit} argument can also be an unevaluated
  expression (such as returned by a call to \code{\link{quote}} or
  \code{\link{substitute}}).  This expression itself is inserted in the
  traced function, so it will typically involve arguments or local
  objects in the traced function.  An expression of this form is useful
  if you only want to interact when certain conditions apply (and in
  this case you probably want to supply \code{print=FALSE} in the call
  to \code{trace} also).

  When the \code{at} argument is supplied, it should be a vector of
  integers referring to the substeps of the body of the function (this
  only works if the body of the function is enclosed in \code{{ ...}}.  In
  this case \code{tracer} is \emph{not} called on entry, but instead
  just before evaluating each of the steps listed in \code{at}.  (Hint:
  you don't want to try to count the steps in the printed version of a
  function; instead, look at \code{as.list(body(f))} to get the numbers
  associated with the steps in function \code{f}.)

  An intrinsic limitation in the \code{exit} argument is that it won't
  work if the function itself uses \code{on.exit}, since the existing
  calls will override the one supplied by \code{trace}.

  Tracing does not nest.  Any call to \code{trace} replaces previously
  traced versions of that function or method, and \code{untrace} always
  restores an untraced version.  (Allowing nested tracing has too many
  potentials for confusion and for accidentally leaving traced versions
  behind.)

  Tracing primitive functions (builtins and specials) from the base
  package works, but only by a special mechanism and not very
  informatively.  Tracing a primitive causes the primitive to be
  replaced by a function with argument \dots (only).  You can get a bit
  of information out, but not much.  A warning message is issued when
  \code{trace} is used on a primitive.

  The practice of saving the traced version of the function back where
  the function came from means that tracing carries over from one
  session to another, \emph{if} the traced function is saved in the
  session image.  (In the next session, \code{untrace} will remove the
  tracing.)  On the other hand, functions that were in a package, not in
  the global environment, are not saved in the image, so tracing expires
  with the session for such functions.

  Tracing a method is basically just like tracing a function, with the
  exception that the traced version is stored by a call to
  \code{\link[methods]{setMethod}} rather than by direct assignment, and so is
  the untraced version after a call to \code{untrace}.

  The version of \code{trace} described here is largely compatible with
  the version in S-Plus, although the two work by entirely different
  mechanisms.  The S-Plus \code{trace} uses the session frame, with the
  result that tracing never carries over from one session to another (\R
  does not have a session frame).  Another relevant distinction has
  nothing directly to do with \code{trace}:  The browser in S-Plus
  allows changes to be made to the frame being browsed, and the changes
  will persist after exiting the browser.  The \R browser allows changes,
  but they disappear when the browser exits.  This may be relevant in
  that the S-Plus version allows you to experiment with code changes
  interactively, but the \R version does not.  (A future revision may
  include a \dQuote{destructive} browser for \R.)
}
\note{
  The version of function tracing that includes any of the arguments
  except for the function name requires the methods package (because it
  uses special classes of objects to store and restore versions of the
  traced functions).

  If methods dispatch is not currently on, \code{trace} will load the
  methods namespace, but will not put the methods package on the search
  list.
}
\value{
  The traced function(s) name(s).  The relevant consequence is the
  assignment that takes place.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{browser}} and \code{\link[utils]{recover}}, the likeliest
  tracing functions;
  also, \code{\link{quote}} and \code{\link{substitute}} for
  constructing general expressions.
}
\examples{
if(.isMethodsDispatchOn()) { # trace needs method package attached.

f <- function(x, y) {
    y <- pmax(y, .001)
    x ^ y
}

## arrange to call the browser on entering and exiting
## function f
trace("f", browser, exit = browser)

## instead, conditionally assign some data, and then browse
## on exit, but only then.  Don't bother me otherwise

trace("f", quote(if(any(y < 0)) yOrig <- y),
      exit = quote(if(exists("yOrig")) browser()),
      print = FALSE)

## trace a utility function, with recover so we
## can browse in the calling functions as well.

trace("as.matrix", recover)

## turn off the tracing

untrace(c("f", "as.matrix"))
}
}
\keyword{programming}
\keyword{debugging}
\eof
\name{traceback}
\title{Print Call Stack of Last Error}
\usage{
traceback()
}
\alias{traceback}
\alias{.Traceback}
\description{
  \code{traceback()} prints the call stack of the last uncaught error,
  i.e., the sequence of calls that lead to the error.  This is useful when an
  error occurs with an unidentifiable error message.
}
\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.
}
\details{
  The stack is stored as a list in \code{.Traceback},
  which \code{traceback} prints in a user-friendly format.

  Errors which are caught \emph{via} \code{\link{try}} or
  \code{\link{tryCatch}} do not generate a traceback, so what is printed
  is the call sequence for the last uncaught error, and not necessarily
  the last error.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
foo <- function(x) { print(1); bar(2) }
bar <- function(x) { x + a.variable.which.does.not.exist }
\dontrun{
foo(2) # gives a strange error
traceback()}
## 2: bar(2)
## 1: foo(2)
bar
## Ah, this is the culprit ...
}
\keyword{programming}
\eof
\name{transform}
\alias{transform}
\alias{transform.default}
\alias{transform.data.frame}
\title{Transform an Object, for Example a Data Frame}
\usage{
transform(x, \dots)
%transform.default(x, \dots)
%transform.data.frame(x, \dots)
}
\arguments{
    \item{x}{The object to be transformed}
    \item{\dots}{Further arguments of the form \code{tag=value}}
}
\description{
  \code{transform} is a generic function, which---at least
  currently---only does anything useful with
  data frames. \code{transform.default} converts its first argument to
  a data frame if possible and calls \code{transform.data.frame}. 
}
\details{
  The \code{\dots} arguments to \code{transform.data.frame} are tagged
  vector expressions, which are evaluated in the data frame
  \code{x}.  The tags are matched against \code{names(x)}, and for
  those that match, the value replace the corresponding variable in
  \code{x}, and the others are appended to \code{x}.
} 
\value{
  The modified value of \code{x}.
}
\author{Peter Dalgaard}
\note{If some of the values are not vectors of the appropriate length,
  you deserve whatever you get!}
\seealso{
    \code{\link{subset}},
    \code{\link{list}},
    \code{\link{data.frame}}
}
\examples{
data(airquality)
transform(airquality, Ozone = -Ozone)
transform(airquality, new = -Ozone, Temp = (Temp-32)/1.8)

attach(airquality)
transform(Ozone, logOzone = log(Ozone)) # marginally interesting ...
detach(airquality)
}
\keyword{manip}
\eof
\name{trees}
\docType{data}
\alias{trees}
\title{Girth, Height and Volume for Black Cherry Trees}
\description{
  This data set provides measurements of the girth, height and volume
  of timber in 31 felled black cherry trees.  Note that girth is the
  diameter of the tree (in inches) measured at 4 ft 6 in above the
  ground.
}
\usage{data(trees)}
\format{
  A data frame with 31 observations on 3 variables.
  \tabular{rlll}{
    \code{[,1]} \tab \code{Girth} \tab numeric
    \tab Tree diameter in inches\cr
    \code{[,2]} \tab \code{Height}\tab numeric
    \tab Height in ft\cr
    \code{[,3]} \tab \code{Volume}\tab numeric
    \tab Volume of timber in cubic ft\cr}
}
\source{
  Ryan, T. A., Joiner, B. L. and Ryan, B. F. (1976)
  \emph{The Minitab Student Handbook}.
  Duxbury Press.
}
\references{
  Atkinson, A. C. (1985)
  \emph{Plots, Transformations and Regression}.
  Oxford University Press.
}
\examples{
data(trees)
pairs(trees, panel = panel.smooth, main = "trees data")
plot(Volume ~ Girth, data = trees, log = "xy")
coplot(log(Volume) ~ log(Girth) | Height, data = trees,
       panel = panel.smooth)
summary(fm1 <- lm(log(Volume) ~ log(Girth), data = trees))
summary(fm2 <- update(fm1, ~ . + log(Height), data = trees))
step(fm2)
## i.e., Volume ~= c * Height * Girth^2  seems reasonable
}
\keyword{datasets}
\eof
\name{try}
\alias{try}
\title{Try an Expression Allowing Error Recovery}
\description{
  \code{try} is a wrapper to run an expression that might fail and allow
  the user's code to handle error-recovery.
}
\usage{
try(expr, silent = FALSE)
}
\arguments{
  \item{expr}{an \R expression to try.}
  \item{silent}{logical: should the report of error messages be suppressed?}
}
\details{
  \code{try} evaluates an expression and traps any errors that occur
  during the evaluation.  \code{try} establishes a handler for
  errors that uses the default error handling protocol. It also
  establishes a \code{tryRestart} restart that can be used by
  \code{invokeRestart}.
}
\value{
  The value of the expression if \code{expr} is evaluated without error,
  but an invisible object of class \code{"try-error"} containing the
  error message if it fails. The normal error handling will print the
  same message unless \code{options("show.error.messages")} is false or
  the call includes \code{silent = TRUE}.
}
\seealso{
  \code{\link{options}} for setting error handlers and suppressing the
  printing of error messages;
  \code{\link{geterrmessage}} for retrieving the last error message.
  \code{tryCatch} provides another means of catching and handling
  errors.
}
\examples{
## this example will not work correctly in example(try), but
## it does work correctly if pasted in
options(show.error.messages = FALSE)
try(log("a"))
print(.Last.value)
options(show.error.messages = TRUE)

## alternatively,
print(try(log("a"), TRUE))

## run a simulation, keep only the results that worked.
set.seed(123)
x <- rnorm(50)
doit <- function(x)
{
    x <- sample(x, replace=TRUE)
    if(length(unique(x)) > 30) mean(x)
    else stop("too few unique points")
}
## alternative 1
res <- lapply(1:100, function(i) try(doit(x), TRUE))
## alternative 2
\dontrun{res <- vector("list", 100)
for(i in 1:100) res[[i]] <- try(doit(x), TRUE)}
unlist(res[sapply(res, function(x) !inherits(x, "try-error"))])
}
\keyword{programming}
\eof
\name{type.convert}
\alias{type.convert}
\title{Type Conversion on Character Variables}
\description{
  Convert a character vector to logical, integer, numeric, complex or
  factor as appropriate.
}
\usage{
type.convert(x, na.strings = "NA", as.is = FALSE, dec = ".")
}
\arguments{
  \item{x}{a character vector.}

  \item{na.strings}{a vector of strings which are to be interpreted as
    \code{\link{NA}} values.  Blank fields are also considered to be
    missing values.}

  \item{as.is}{logical. See Details.}

  \item{dec}{the character to be assumed for decimal points.}
}
\details{
  This is principally a helper function for \code{\link{read.table}}.
  Given a character vector, it attempts to convert it to logical,
  integer, numeric or complex, and failing that converts it to factor
  unless \code{as.is = TRUE}.  The first type that can accept all the
  non-missing values is chosen.

  Vectors which are entirely missing values are converted to logical,
  since \code{NA} is primarily logical.
}
\value{
  A vector of the selected class, or a factor.
}

\seealso{\code{\link{read.table}}}

\keyword{manip}
\eof
\name{typeof}
\alias{typeof}
\title{The Type of an Object}
\description{
  \code{typeof} determines the (\R internal)
  type or storage mode of any object
}
\usage{
typeof(x)
}
\arguments{
  \item{x}{any \R object.}
}
\value{
  A character string.
}
\seealso{
  \code{\link{mode}}, \code{\link{storage.mode}}.
}
\examples{
typeof(2)
mode(2)
}
\keyword{attribute}
\eof
\name{unique}
\alias{unique}
\alias{unique.default}
\alias{unique.data.frame}
\alias{unique.matrix}
\alias{unique.array}
\title{Extract Unique Elements}
\description{
  \code{unique} returns a vector, data frame or array like \code{x}
  but with duplicate  elements removed.
}
\usage{
unique(x, incomparables = FALSE, \dots)

\method{unique}{array}(x, incomparables = FALSE, MARGIN = 1, \dots)
}
\arguments{
  \item{x}{an atomic vector or a data frame or an array.}
  \item{incomparables}{a vector of values that cannot be compared.
    Currently, \code{FALSE} is the only possible value, meaning that all
    values can be compared.}
  \item{\dots}{arguments for particular methods.}
  \item{MARGIN}{the array margin to be held fixed: a single integer.}
}
\details{
  This is a generic function with methods for vectors, data frames and
  arrays (including matrices).

  The array method calculates for each element of the dimension
  specified by \code{MARGIN} if the remaining dimensions are identical
  to those for an earlier element (in row-major order).  This would most
  commonly be used to find unique rows (the default) or columns
  (with \code{MARGIN = 2}).
}
\value{
  An object of the same type of \code{x}. but if
  an element is equal to one with a smaller index, it is removed.
  Dimensions of arrays are not dropped.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{duplicated}} which gives the indices of duplicated
  elements.
}
\examples{
unique(c(3:5, 11:8, 8 + 0:5))
length(unique(sample(100, 100, replace=TRUE)))
## approximately 100(1 - 1/e) = 63.21

data(iris)
unique(iris)
}
\keyword{manip}
\keyword{logic}
\eof
\name{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[graphics]{par}}).

  \code{xyinch} does the same for a pair of numbers \code{xy},
  simultaneously.

  \code{cm} translates inches in to cm (centimeters).
}
\usage{
xinch(x = 1, warn.log = TRUE)
yinch(y = 1, warn.log = TRUE)
xyinch(xy = 1, warn.log = TRUE)
cm(x)
}
\arguments{
  \item{x,y}{numeric vector}
  \item{xy}{numeric of length 1 or 2.}
  \item{warn.log}{logical; if \code{TRUE}, a warning is printed in case
    of active log scale.}
}
\examples{
all(c(xinch(),yinch()) == xyinch()) # TRUE
xyinch()
xyinch #- to see that is really   delta{"usr"} / "pin"

cm(1)# = 2.54

## plot labels offset 0.12 inches to the right
## of plotted symbols in a plot
data(mtcars)
with(mtcars, {
    plot(mpg, disp, pch=19, main= "Motor Trend Cars")
    text(mpg + xinch(0.12), disp, row.names(mtcars),
         adj = 0, cex = .7, col = 'blue')
    })
}
\keyword{dplot}
\eof
\name{unlink}
\title{Delete Files and Directories}
\usage{unlink(x, recursive = FALSE)}
\alias{unlink}
\arguments{
  \item{x}{a character vector with the names of the file(s) or
    directories to be deleted.
    Wildcards (normally \file{*} and \file{?}) are allowed.}
  \item{recursive}{logical. Should directories be deleted
    recursively?}
}
\description{
  \code{unlink} deletes the file(s) or directories specified by \code{x}.
}
\details{
  If \code{recursive = FALSE} directories are not deleted,
  not even empty ones.

  \code{\link{file.remove}} can only remove files, but gives more
  detailed error information.
}
\value{
#ifdef unix
  The return value of the corresponding system command, \code{rm -f},
  normally \code{0} for success, \code{1} for failure.
#endif
#ifdef windows
  \code{0} for success, \code{1} for failure.
#endif
  Not deleting a non-existent file is not a failure.
}
\note{
  Prior to \R version 1.2.0 the default on Unix was \code{recursive =
    TRUE}, and on Windows empty directories could be deleted.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{file.remove}}.
}
%Examples: tempfile has an 'unlink' example
\keyword{file}
\eof
\name{unlist}
\title{Flatten Lists}
\description{
  Given a list structure \code{x}, \code{unlist} simplifies it to
  produce a vector which contains all the atomic components
  which occur in \code{x}.
}
\usage{
unlist(x, recursive = TRUE, use.names = TRUE)
}
\alias{unlist}
\arguments{
  \item{x}{A list or vector.}
  \item{recursive}{logical. Should unlisting be applied to list
    components of \code{x}?}
  \item{use.names}{logical. Should names be preserved?}
}
\details{
  \code{unlist} is generic: you can write methods to handle
  specific classes of objects, see \link{InternalMethods}.
  
  If \code{recursive = FALSE}, the function will not recurse beyond
  the first level items in \code{x}.

  \code{x} can be a vector, but then \code{unlist} does nothing useful,
  not even drop names.

  By default, \code{unlist} tries to retain the naming
  information present in \code{x}.
  If \code{use.names = FALSE} all naming information is dropped.

  Where possible the list elements are coerced to a common mode during
  the unlisting, and so the result often ends up as a character vector.

  A list is a (generic) vector, and the simplified vector might still be
  a list (and might be unchanged).  Non-vector elements of the list
  (for example language elements such as names, formulas and calls)
  are not coerced, and so a list containing one or more of these remains a
  list.  (The effect of unlisting an \code{\link[stats]{lm}} fit is a list which
  has individual residuals as components,)
}
\value{
  A vector of an appropriate mode to hold the list components.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{c}}, \code{\link{as.list}}.
}
\examples{
unlist(options())
unlist(options(), use.names=FALSE)

l.ex <- list(a = list(1:5, LETTERS[1:5]), b = "Z", c = NA)
unlist(l.ex, recursive = FALSE)
unlist(l.ex, recursive = TRUE)

l1 <- list(a="a", b=2, c=pi+2i)
unlist(l1) # a character vector
l2 <- list(a="a", b=as.name("b"), c=pi+2i)
unlist(l2) # remains a list
}
\keyword{list}
\keyword{manip}
\eof
\name{unname}
\alias{unname}
\title{Remove `names' or `dimnames'}
\description{
  Remove the \code{\link{names}} or \code{\link{dimnames}} attribute of
  an \R object.
}
\usage{
unname(obj, force = FALSE)
}
\arguments{
 \item{obj}{the \R object which is wanted \dQuote{nameless}.}
 \item{force}{logical; if true, the \code{dimnames} are even removed
   from \code{\link{data.frame}}s.
   \emph{This argument is currently \bold{experimental} and hence
     might change!}}
}
\value{
  Object as \code{obj} but without \code{\link{names}} or
  \code{\link{dimnames}}.
}
\examples{
## Answering a question on R-help (14 Oct 1999):
col3 <- 750+ 100* rt(1500, df = 3)
breaks <- factor(cut(col3,breaks=360+5*(0:155)))
z <- table(breaks)
z[1:5] # The names are larger than the data ...
barplot(unname(z), axes= FALSE)
}
\keyword{utilities}
\eof
\name{UserHooks}
\alias{getHook}
\alias{setHook}
\alias{packageEvent}
\alias{.userHooksEnv}
\title{Functions to Get and Set Hooks for Load, Attach, Detach and Unload}
\description{
  These function allow users to set actions to be taken before packages
  are attached/detached and namespaces are (un)loaded.
}
\usage{
getHook(hookName)
setHook(hookName, value, action = c("append", "prepend", "replace"))

packageEvent(pkgname, event=c("onLoad", "attach", "detach", "onUnload"))
}
\arguments{
  \item{hookName}{character string: the hook name}
  \item{pkgname}{character string: the package/namespace name.
    If versioned install has been used, \code{pkgname} should the unversioned
    name of the package and any version information will be stripped.}
  \item{event}{character string: an event for the package}
  \item{value}{A function, or for \code{action="replace"}, \code{NULL}.}
  \item{action}{The action to be taken.  The names can be appreviated.}
}

\details{
  \code{setHook} provides a general mechanism for users to register
  hooks, a list of functions to be called from system (or user)
  functions.  The initial set of hooks is associated with events on
  packages/namespaces: these hooks are named via calls to \code{packageEvent}.

  To remove a hook completely, call \code{setHook(hookName, NULL, "replace")}.
  
  When an \R package is attached by \code{\link{library}}, it can call
  initialization code via a function \code{.First.lib}, and when it is
  \code{\link{detach}}-ed it can tidy up via a function \code{.Last.lib}.
  Users can add their own initialization code via the hooks provided by
  these functions, functions which will be called as
  \code{funname(pkgname, pkgpath)} inside a \code{\link{try}}
  call.  (The attach hook is called after \code{.First.lib} and the detach
  hook before \code{.Last.lib}.)

  If a package has a namespace, there are two further actions, when the
  namespace is loaded (before being attached and after \code{.onLoad} is
  called ) and when it is unloaded (after being detached and before
  \code{.onUnload}).  Note that code in these hooks is run without the
  package being on the search path, so objects in the package need to be
  referred to using the double colon operator as in the example.
  (Unlike \code{.onLoad}, the user hook is run after the name space has
  been sealed.)

  Hooks are normally run in the order shown by \code{getHook},
  but the \code{"detach"} and \code{"onUnload"} hooks are run
  in reverse order so the default for package events is to add hooks
  \sQuote{inside} existing ones.
  
  Note that when an \R is finished, packages are not detached and
  namespaces are not unloaded, so the corresponding hooks will not be
  run.

  The hooks are stored in the environment \code{.userHooksEnv} in the
  base package, with \sQuote{mangled} names.
}
\value{
  For \code{getHook} function, a list of functions (possible empty).
  For \code{setHook} function, no return value.
  For \code{packageEvent}, the derived hook name (a character string).
}
\seealso{
  \code{\link{library}}, \code{\link{detach}}, \code{\link{loadNamespace}}.

  Other hooks may be added later: \code{\link[graphics]{plot.new}} and
  \code{\link[graphics]{persp}} already have them.
}
\examples{
setHook(packageEvent("graphics", "onLoad"),
        function(...) graphics::ps.options(horizontal=FALSE)) 
}
\keyword{utilities}
\eof
\name{vector}
\title{Vectors}
\usage{
vector(mode = "logical", length = 0)
as.vector(x, mode = "any")
is.vector(x, mode = "any")
}
\alias{vector}
\alias{as.vector}
\alias{as.vector.factor}
\alias{is.vector}
\arguments{
  \item{mode}{A character string giving an atomic mode, or \code{"any"}.}
  \item{length}{A non-negative integer specifying the desired length.}
  \item{x}{An object.}
}
\description{
  \code{vector} produces a vector of the given length and mode.

  \code{as.vector}, a generic, attempts to coerce its argument into a
  vector of mode \code{mode} (the default is to coerce to whichever mode
  is most convenient).  The attributes of \code{x} are removed.

  \code{is.vector} returns \code{TRUE} if \code{x} is a vector (of mode
  logical, integer, real, complex, character or list if not specified)
  and \code{FALSE} otherwise.
}
\details{
  \code{is.vector} returns \code{FALSE} if \code{x} has any attributes
  except names.  (This is incompatible with S.)  On the other hand,
  \code{as.vector} removes \emph{all} attributes including names.
  
  Note that factors are \emph{not} vectors;  \code{is.vector} returns
  \code{FALSE} and \code{as.vector} converts to character mode.
}
\value{
  For \code{vector}, a vector of the given length and mode.  Logical
  vector elements are initialized to \code{FALSE}, numeric vector
  elements to \code{0} and character vector elements to \code{""}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
\code{\link{c}}, \code{\link{is.numeric}}, \code{\link{is.list}}, etc.
}
\examples{
df <- data.frame(x=1:3, y=5:7)
\dontrun{## Error:
  as.vector(data.frame(x=1:3, y=5:7), mode="numeric")
}

x <- c(a = 1, b = 2)
is.vector(x)
as.vector(x)
all.equal(x, as.vector(x)) ## FALSE


###-- All the following are TRUE:
is.list(df)
! is.vector(df)
! is.vector(df, mode="list")

is.vector(list(), mode="list")
is.vector(NULL,   mode="NULL")
}
\keyword{classes}
\eof
\name{volcano}
\docType{data}
\alias{volcano}
\title{Topographic Information on Auckland's Maunga Whau Volcano}
\description{
  Maunga Whau (Mt Eden) is one of about 50 volcanos in the Auckland
  volcanic field.  This data set gives topographic information for
  Maunga Whau on a 10m by 10m grid.
}
\usage{data(volcano)}
\format{
  A matrix with 87 rows and 61 columns, rows corresponding to grid lines
  running east to west and columns to grid lines running south to
  north.}
\source{
  Digitized from a topographic map by Ross Ihaka.
  These data should not be regarded as accurate.
}
% FIXME: missing \references{}
\seealso{\code{\link[graphics]{filled.contour}} for a nice plot.}
\examples{
require(graphics)
data(volcano)
filled.contour(volcano, color = terrain.colors, asp = 1)
title(main = "volcano data: filled contour map")
}
\keyword{datasets}
\eof
\name{warning}
\alias{warning}
\alias{suppressWarnings}
\title{Warning Messages}
\description{
  Generates a warning message that corresponds to its argument(s) and
  (optionally) the expression or function from which it was called.
}
\usage{
warning(\dots, call. = TRUE)
suppressWarnings(expr)
}
\arguments{
  \item{\dots}{character vectors (which are pasted together with no
    separator), a condition object, or \code{NULL}.}
  \item{call.}{logical, indicating if the call should become part of the
    warning message.}
  \item{expr}{expression to evaluate.}
}
\details{
  The result \emph{depends} on the value of
  \code{\link{options}("warn")} and on handlers established in the
  executing code.

  \code{warning} signals a warning condition by (effectively) calling
  \code{signalCondition}.  If there are no handlers or if all handlers
  return, then the value of \code{warn} is used to determine the
  appropriate action.  If \code{warn} is negative warnings are
  ignored; if it is zero they are stored and printed after the
  top--level function has completed; if it is one they are printed as
  they occur and if it is 2 (or larger) warnings are turned into
  errors.

  If \code{warn} is zero (the default), a top-level variable
  \code{last.warning} is created.  It contains the warnings which can be
  printed via a call to \code{\link{warnings}}.

  Warnings will be truncated to \code{getOption("warning.length")}
  characters, default 1000.

  While the warning is being processed, a \code{muffleWarning} restart
  is available.  If this restart is invoked with \code{invokeRestart},
  then \code{warning} returns immediately.

   \code{suppressWarnings} evaluates its expression in a context that
   ignores all warnings.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{stop}} for fatal errors,
  \code{\link{warnings}},
  and \code{\link{options}} with argument \code{warn=}.
}
\examples{
\dontshow{oldopt <- options(warn=1)}
testit <- function() warning("testit")
testit() ## shows call
testit <- function() warning("problem in testit", call. = FALSE)
testit() ## no call
suppressWarnings(warning("testit"))
\dontshow{eigenval <- 10 ^ -rnorm(1, m=6)
if(eigenval < 1.e-7) warning("system near singular")
options(oldopt)}
}
\keyword{programming}
\keyword{error}
\eof
\name{warnings}
\alias{warnings}
\title{Print Warning Messages}
\description{
  \code{warnings} prints the top-level variable \code{last.warning} in a
  pleasing form.
}
\usage{
warnings(\dots)
}
\arguments{
  \item{\dots}{arguments to be passed to \code{\link{cat}}.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{\code{\link{warning}}.}
\examples{
ow <- options("warn")
for(w in -1:1) {
   options(warn = w); cat("\n warn =",w,"\n")
   for(i in 1:3) { cat(i,"..\n"); m <- matrix(1:7, 3,4) }
}
warnings()
options(ow) # reset
}
\keyword{programming}
\keyword{error}
\eof
\name{warpbreaks}
\docType{data}
\alias{warpbreaks}
\title{The Number of Breaks in Yarn during Weaving}
\description{
  This data set gives the number of warp breaks per loom, where a loom
  corresponds to a fixed length of yarn.
}
\usage{data(warpbreaks)}
\format{
  A data frame with 54 observations on 3 variables.
  \tabular{rlll}{
    \code{[,1]} \tab \code{breaks}  \tab numeric \tab The number of breaks\cr
    \code{[,2]} \tab \code{wool}    \tab factor  \tab The type of wool (A or B)\cr
    \code{[,3]} \tab \code{tension} \tab factor  \tab The level of tension (L, M, H)
  }
  There are measurements on 9 looms for each of the six types of warp
  (\code{AL}, \code{AM}, \code{AH}, \code{BL}, \code{BM}, \code{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[stats]{xtabs}} for ways to display these data as a table.
}
\examples{
data(warpbreaks)
summary(warpbreaks)
opar <- par(mfrow = c(1,2), oma = c(0, 0, 1.1, 0))
plot(breaks ~ tension, data = warpbreaks, col = "lightgray",
     varwidth = TRUE, subset = wool == "A", main = "Wool A")
plot(breaks ~ tension, data = warpbreaks, col = "lightgray",
     varwidth = TRUE, subset = wool == "B", main = "Wool B")
mtext("warpbreaks data", side = 3, outer = TRUE)
par(opar)
summary(fm1 <- lm(breaks ~ wool*tension, data = warpbreaks))
anova(fm1)
}
\keyword{datasets}
\eof
\name{weekdays}
\alias{weekdays}
\alias{weekdays.POSIXt}
\alias{weekdays.Date}
\alias{months}
\alias{months.POSIXt}
\alias{months.Date}
\alias{quarters}
\alias{quarters.POSIXt}
\alias{quarters.Date}
\alias{julian}
\alias{julian.POSIXt}
\alias{julian.Date}
\title{Extract Parts of a POSIXt or Date Object}
\description{
  Extract the weekday, month or quarter, or the Julian time
  (days since some origin).  These are generic functions: the methods
  for the internal date-time classes are documented here.
}
\usage{
weekdays(x, abbreviate)
\method{weekdays}{POSIXt}(x, abbreviate = FALSE)
\method{weekdays}{Date}(x, abbreviate = FALSE)

months(x, abbreviate)
\method{months}{POSIXt}(x, abbreviate = FALSE)
\method{months}{Date}(x, abbreviate = FALSE)

quarters(x, abbreviate)
\method{quarters}{POSIXt}(x, \dots)
\method{quarters}{Date}(x, \dots)

julian(x, \dots)
\method{julian}{POSIXt}(x, origin = as.POSIXct("1970-01-01", tz="GMT"), \dots)
\method{julian}{Date}(x, origin = as.Date("1970-01-01"), \dots)
}
\arguments{
  \item{x}{an object inheriting from class \code{"POSIXt"} or \code{"Date"}.}
  \item{abbreviate}{logical.  Should the names be abbreviated?}
  \item{origin}{an length-one object inheriting from class
    \code{"POSIXt"} or \code{"Date"}.}
  \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}}, \code{\link{Date}}
}

\examples{
weekdays(.leap.seconds)
months(.leap.seconds)
quarters(.leap.seconds)
}
\keyword{chron}
\eof
\name{which}
\alias{which}
\title{Which indices are TRUE?}
\description{
  Give the \code{TRUE} indices of a logical object, allowing for array
  indices.
}
\usage{
which(x, arr.ind = FALSE)
}
\arguments{
 \item{x}{a \code{\link{logical}} vector or array.  \code{\link{NA}}s
   are allowed and omitted (treated as if \code{FALSE}).}
 \item{arr.ind}{logical; should \bold{arr}ay \bold{ind}ices be returned
   when \code{x} is an array?}
}
\value{
  If \code{arr.ind == FALSE} (the default), an integer vector with
  \code{length} equal to \code{sum(x)}, i.e., to the number of
  \code{TRUE}s in \code{x}; Basically, the result is
  \code{(1:length(x))[x]}.
  
  If \code{arr.ind == TRUE} and \code{x} is an \code{\link{array}} (has
  a \code{\link{dim}} attribute), the result is a matrix who's rows each
  are the indices of one element of \code{x}; see Examples below.
}
\author{Werner Stahel and Peter Holzer \email{holzer@stat.math.ethz.ch},
  for the array case.}
\seealso{\code{\link{Logic}}, \code{\link{which.min}} for the index of
  the minimum or maximum, and \code{\link{match}} for the first index of
  an element in a vector, i.e., for a scalar \code{a}, \code{match(a,x)}
  is equivalent to  \code{min(which(x == a))} but much more efficient.}
\examples{
which(LETTERS == "R")
which(ll <- c(TRUE,FALSE,TRUE,NA,FALSE,FALSE,TRUE))#> 1 3 7
names(ll) <- letters[seq(ll)]
which(ll)
which((1:12)\%\%2 == 0) # which are even?
which(1:10 > 3, arr.ind=TRUE)

( m <- matrix(1:12,3,4) )
which(m \%\% 3 == 0)
which(m \%\% 3 == 0, arr.ind=TRUE)
rownames(m) <- paste("Case",1:3, sep="_")
which(m \%\% 5 == 0, arr.ind=TRUE)

dim(m) <- c(2,2,3); m
which(m \%\% 3 == 0, arr.ind=FALSE)
which(m \%\% 3 == 0, arr.ind=TRUE)

vm <- c(m)
dim(vm) <- length(vm) #-- funny thing with  length(dim(...)) == 1
which(vm \%\% 3 == 0, arr.ind=TRUE)
}
\keyword{logic}
\keyword{attribute}
\eof
\name{which.min}
\alias{which.min}
\alias{which.max}
\title{Where is the Min() or Max() ?}
\concept{argmin}
\concept{argmax}
\concept{index of minimum}
\concept{index of maximum}
\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 (\code{NA}s are allowed).}
}
\value{
  an \code{\link{integer}} of length 1 or 0 (iff \code{x} has no
  non-\code{NA}s) , giving the index of the \emph{first} minimum or
  maximum respectively of \code{x}.

  If this extremum is unique (or empty), the result is the same (but more
  efficient) as  \code{which(x == min(x))} or \code{which(x == max(x))}
  respectively.
}
\author{Martin Maechler}
\seealso{
  \code{\link{which}}, \code{\link{max.col}}, \code{\link{max}}, etc.

  \code{\link[nnet]{which.is.max}} in package \pkg{nnet} differs in
  breaking ties at random (and having a \dQuote{fuzz} in the definition
  of ties).
}
\examples{
x <- c(1:4,0:5,11)
which.min(x)
which.max(x)

## it *does* work with NA's present:
data(presidents, package="stats")
presidents[1:30]
range(presidents, na.rm = TRUE)
which.min(presidents)# 28
which.max(presidents)# 2
}
\keyword{utilities}
\eof
\name{with}
\alias{with}
\alias{with.default}
\title{Evaluate an Expression in a Data Environment}
\description{
  Evaluate an \R expression in an environment constructed from data.
}
\usage{
with(data, expr, \dots)
%\method{with}{default}(data, expr, \dots)
}
\arguments{
  \item{data}{data to use for constructing an environment. For the
    default method this may be an environment, a list, a data frame,
    or an integer as in \code{sys.call}.}
  \item{expr}{expression to evaluate.}
  \item{\dots}{arguments to be passed to future methods.}
}
\details{
  \code{with} is a generic function that evaluates \code{expr} in a
  local environment constructed from \code{data}.  The environment has
  the caller's environment as its parent.  This is useful for
  simplifying calls to modeling functions.

  Note that assignments within \code{expr} take place in the constructed
  environment and not in the user's workspace.
}
\seealso{
  \code{\link{evalq}}, \code{\link{attach}}.
}
\examples{
require(stats); require(graphics)
#examples from glm:
\dontrun{
library(MASS)
data(anorexia)
with(anorexia, {
    anorex.1 <- glm(Postwt ~ Prewt + Treat + offset(Prewt),
                    family = gaussian)
    summary(anorex.1)
})
}

with(data.frame(u = c(5,10,15,20,30,40,60,80,100),
                lot1 = c(118,58,42,35,27,25,21,19,18),
                lot2 = c(69,35,26,21,18,16,13,12,12)),
    list(summary(glm(lot1 ~ log(u), family = Gamma)),
         summary(glm(lot2 ~ log(u), family = Gamma))))

# example from boxplot:
data(ToothGrowth)
with(ToothGrowth, {
    boxplot(len ~ dose, boxwex = 0.25, at = 1:3 - 0.2,
            subset = (supp == "VC"), col = "yellow",
            main = "Guinea Pigs' Tooth Growth",
            xlab = "Vitamin C dose mg",
            ylab = "tooth length", ylim = c(0,35))
    boxplot(len ~ dose, add = TRUE, boxwex = 0.25, at = 1:3 + 0.2,
            subset = supp == "OJ", col = "orange")
    legend(2, 9, c("Ascorbic acid", "Orange juice"),
           fill = c("yellow", "orange"))
})

# alternate form that avoids subset argument:
with(subset(ToothGrowth, supp == "VC"),
     boxplot(len ~ dose, boxwex = 0.25, at = 1:3 - 0.2,
             col = "yellow", main = "Guinea Pigs' Tooth Growth",
             xlab = "Vitamin C dose mg",
             ylab = "tooth length", ylim = c(0,35)))
with(subset(ToothGrowth,  supp == "OJ"),
     boxplot(len ~ dose, add = TRUE, boxwex = 0.25, at = 1:3 + 0.2,
             col = "orange"))
legend(2, 9, c("Ascorbic acid", "Orange juice"),
       fill = c("yellow", "orange"))
}
\keyword{data}
\keyword{programming}
\eof
\name{women}
\docType{data}
\alias{women}
\title{Average Heights and Weights for American Women}
\description{
  This data set gives the average heights and weights for American women
  aged 30--39.
}
\usage{data(women)}
\format{A data frame with 15 observations on 2 variables.
  \tabular{rlll}{
    \code{[,1]}  \tab \code{height}  \tab numeric  \tab Height (in)\cr
    \code{[,2]}  \tab \code{weight}  \tab numeric  \tab Weight (lbs)
  }
}
\source{The World Almanac and Book of Facts, 1975.}
\details{
  The data set appears to have been taken from the American Society of
  Actuaries \emph{Build and Blood Pressure Study} for some (unknown to
  us) earlier year.
    
  The World Almanac notes: \dQuote{The figures represent weights in
    ordinary indoor clothing and shoes, and heights with shoes}.
}
\references{
  McNeil, D. R. (1977)
  \emph{Interactive Data Analysis}.
  Wiley.
}
\examples{
data(women)
plot(women, xlab = "Height (in)", ylab = "Weight (lb)",
     main = "women data: American women aged 30-39")
}
\keyword{datasets}
\eof
\name{write}
\title{Write Data to a File}
\usage{
write(x, file = "data",
      ncolumns = if(is.character(x)) 1 else 5,
      append = FALSE)
}
\alias{write}
\arguments{
  \item{x}{the data to be written out.}
  \item{file}{A connection, or  a character string naming the file to write to.
    If \code{""}, print to the standard output connection.
#ifdef unix
    If it is \code{"|cmd"}, the output is piped to the command given
    by \file{cmd}.
#endif
  }
  \item{ncolumns}{the number of columns to write the data in.}
  \item{append}{if \code{TRUE} the data \code{x} is appended to file \code{file}.}
}
\description{
  The data (usually a matrix) \code{x} are written to file \code{file}.
  If \code{x} is a two-dimensional matrix you need to transpose it to get the
  columns in \code{file} the same as those in the internal representation.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{save}} for writing any \R objects,
  \code{\link{write.table}} for data frames,
  and \code{\link{scan}} for reading data.
}
\examples{
# create a 2 by 5 matrix
x <- matrix(1:10,ncol=5)

# the file data contains x, two rows, five cols
# 1 3 5 6 9 will form the first row
write(t(x))

# the file data now contains the data in x,
# two rows, five cols but the first row is 1 2 3 4 5
write(x)
unlink("data") # tidy up
}
\keyword{file}
\keyword{connection}
\eof
\name{write.table}
\alias{write.table}
\title{Data Output}
\description{
  \code{write.table} prints its required argument \code{x} (after
  converting it to a data frame if it is not one already) to
  \code{file}.  The entries in each line (row) are separated by the
  value of \code{sep}.
}
\usage{
write.table(x, file = "", append = FALSE, quote = TRUE, sep = " ",
            eol = "\n", na = "NA", dec = ".", row.names = TRUE,
	    col.names = TRUE, qmethod = c("escape", "double"))
}
\arguments{
  \item{x}{the object to be written, typically a data frame.  If not, it
    is attempted to coerce \code{x} to a data frame.}
  \item{file}{either a character string naming a file or a connection.
    \code{""} indicates output to the console.}
  \item{append}{logical.  If \code{TRUE}, the output is appended to the
    file.  If \code{FALSE}, any existing file of the name is destroyed.}
  \item{quote}{a logical value 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
    columns to quote.  In both cases, row and column names
    are quoted if they are written. If \code{FALSE}, nothing is quoted.}
  \item{sep}{the field separator string.  Values within each row of
    \code{x} are separated by this string.}
  \item{eol}{the character(s) to print at the end of each line (row).}
  \item{na}{the string to use for missing values in the data.}
  \item{dec}{the string to use for decimal points.}
  \item{row.names}{either a logical value indicating whether the row
    names of \code{x} are to be written along with \code{x}, or a
    character vector of row names to be written.}
  \item{col.names}{either a logical value indicating whether the column
    names of \code{x} are to be written along with \code{x}, or a
    character vector of column names to be written.}
  \item{qmethod}{a character string specifying how to deal with embedded
    double quote characters when quoting strings.  Must be one of
    \code{"escape"} (default), in which case the quote character is
    escaped in C style by a backslash, or \code{"double"}, in which case
    it is doubled.  You can specify just the initial letter.}
}
\details{
  Normally there is no column name for a column of row names.  If
  \code{col.names=NA} a blank column name is added.  This can be used to
  write CSV files for input to spreadsheets.

  \code{write.table} can be slow for data frames with large numbers
  (hundreds or more) of columns: this is inevitable as each column could
  be of a different class and so must be handled separately.
  Function \code{\link[MASS]{write.matrix}} in package \pkg{MASS}
  may be much more efficient if \code{x} is a matrix or can be
  represented in a numeric matrix.
}

\seealso{
  The \dQuote{R Data Import/Export} manual.
  
  \code{\link{read.table}}, \code{\link{write}}.

  \code{\link[MASS]{write.matrix}}.
}

\examples{
\dontrun{
## To write a CSV file for input to Excel one might use
write.table(x, file = "foo.csv", sep = ",", col.names = NA)
## and to read this file back into R one needs
read.table("file.csv", header = TRUE, sep = ",", row.names=1)
}}
\keyword{print}
\keyword{file}
\eof
\name{writeLines}
\alias{writeLines}
\title{Write Lines to a Connection}
\description{
  Write text lines to a connection.
}
\usage{
writeLines(text, con = stdout(), sep = "\n")
}
\arguments{
  \item{text}{A character vector}
  \item{con}{A connection object or a character string.}
  \item{sep}{character. A string to be written to the connection after
    each line of text.}
}
\details{
  If the \code{con} is a character string, the functions call
  \code{\link{file}} to obtain an file connection which is opened for
  the duration of the function call.

  If the connection is open it is written from its current position.
  If it is not open, it is opened for the duration of the call and then
  closed again.

  Normally \code{writeLines} is used with a text connection, and the
  default separator is converted to the normal separator for that
  platform (LF on Unix/Linux, CRLF on Windows, CR on Classic MacOS).  For
  more control, open a binary connection and specify the precise value
  you want written to the file in \code{sep}.  For even more control,
  use \code{\link{writeChar}} on a binary connection.
}
\seealso{
  \code{\link{connections}}, \code{\link{writeChar}}, \code{\link{writeBin}},
  \code{\link{readLines}}, \code{\link{cat}}
}

\keyword{file}
\keyword{connection}
\eof
\name{.Machine}
\title{Numerical Characteristics of the Machine}
\usage{
.Machine
}
\alias{.Machine}
\description{
  \code{.Machine} is a variable holding information on the numerical
  characteristics of the machine \R is running on, such as the largest
  double or integer and the machine's precision.
}
\value{
  A list with components (for simplicity, the prefix \dQuote{double} is
  omitted in the explanations)
  \item{double.eps}{the smallest positive floating-point number
    \code{x} such that \code{1 + x != 1}.  It equals
    \code{base^ulp.digits} if either \code{base} is 2 or \code{rounding}
    is 0;  otherwise, it is \code{(base^ulp.digits) / 2}.}
  \item{double.neg.eps}{a small positive floating-point number \code{x}
    such that \code{1 - x != 1}.  It equals \code{base^neg.ulp.digits}
    if \code{base} is 2 or \code{round} is 0;  otherwise, it is
    \code{(base^neg.ulp.digits) / 2}.
    As \code{neg.ulp.digits} is bounded below by \code{-(digits + 3)},
    \code{neg.eps} may not be the smallest number that can alter 1 by
    subtraction.}
  \item{double.xmin}{the smallest non-vanishing normalized
    floating-point power of the radix, i.e., \code{base^min.exp}.}
  \item{double.xmax}{the largest finite floating-point number.
    Typically, it is equal to \code{(1 - neg.eps) * base^max.exp}, but
    on some machines it is only the second, or perhaps third, largest
    number, being too small by 1 or 2 units in the last digit of the
    significand.}
  \item{double.base}{the radix for the floating-point representation}
  \item{double.digits}{the number of base digits in the floating-point
    significand}
  \item{double.rounding}{the rounding action. \cr
    0 if floating-point addition chops; \cr
    1 if floating-point addition rounds, but not in the IEEE style; \cr
    2 if floating-point addition rounds in the IEEE style; \cr
    3 if floating-point addition chops, and there is partial underflow; \cr
    4 if floating-point addition rounds, but not in the IEEE style, and
    there is partial underflow; \cr
    5 if floating-point addition rounds in the IEEE style, and there is
    partial underflow}
  \item{double.guard}{the number of guard digits for multiplication
    with truncating arithmetic.  It is 1 if floating-point arithmetic
    truncates and more than \code{digits} base \code{base} digits
    participate in the post-normalization shift of the floating-point
    significand in multiplication, and 0 otherwise.}
  \item{double.ulp.digits}{the largest negative integer \code{i} such
    that \code{1 + base^i != 1}, except that it is bounded below by
    \code{-(digits + 3)}.}
  \item{double.neg.ulp.digits}{the largest negative integer \code{i}
    such that \code{1 - base^i != 1}, except that it is bounded below by
    \code{-(digits + 3)}.}
  \item{double.exponent}{
    the number of bits (decimal places if \code{base} is 10) reserved
    for the representation of the exponent (including the bias or sign)
    of a floating-point number}
  \item{double.min.exp}{
    the largest in magnitude negative integer \code{i} such that
    \code{base ^ i} is positive and normalized.}
  \item{double.max.exp}{
    the smallest positive power of \code{base} that overflows.}
  \item{integer.max}{the largest integer which can be represented.}
  \item{sizeof.long}{the number of bytes in a C \code{long} type.}
  \item{sizeof.longlong}{the number of bytes in a C \code{long long}
    type. Will be zero if there is no such type.}
  \item{sizeof.longdouble}{the number of bytes in a C \code{long double}
    type. Will be zero if there is no such type.}
  \item{sizeof.pointer}{the number of bytes in a C \code{SEXP}
    type.}
}
\details{
  The algorithm is based on Cody's (1988) subroutine MACHAR.
}
\references{
  Cody, W. J. (1988)
  MACHAR: A subroutine to dynamically determine machine parameters.
  \emph{Transactions on Mathematical Software}, \bold{14}, 4, 303--311.
}
\seealso{
  \code{\link{.Platform}} for details of the platform.
}
\examples{
.Machine
## or for a neat printout
noquote(unlist(format(.Machine)))
}
\keyword{sysdata}
\keyword{programming}
\keyword{math}
\eof
\name{InternalMethods}
\alias{InternalMethods}
\title{Internal Generic Functions}
\description{
  Many \R-internal functions are \emph{generic} and allow
  methods to be written for.
}

\details{
  % -------------------- grep -nw DispatchOrEval src/*/*[ch]
  %                         --------------
  The following builtin functions are \emph{generic} as well, i.e., you
  can write \code{\link[utils]{methods}} for them:

  \code{\link{[}},            % do_subset()          [subset.c:464]
  \code{\link{[[}},           % do_subset2()         [subset.c:567]
  \code{\link{$}},
  \code{\link{[<-}},
  \code{\link{[[<-}},
  \code{\link{$<-}},

  \code{\link{length}},
  \code{\link{length<-}},
    
  \code{\link{dimnames<-}},   % do_dimnamesgets()    [attrib.c:422]
  \code{\link{dimnames}},     % do_dimnames()        [attrib.c:489]
  \code{\link{dim<-}},        % do_dimgets()         [attrib.c:513]
  \code{\link{dim}}           % do_dim()             [attrib.c:501]
    
  \code{\link{c}},            % do_c()               [bind.c:524]
  \code{\link{unlist}},       % do_unlist()          [bind.c:648]
  
  \code{\link{as.character}},
  \code{\link{as.vector}},    % do_asvector()        [coerce.c:948]
  \code{\link{is.array}},
  \code{\link{is.atomic}},
  \code{\link{is.call}},
  \code{\link{is.character}},
  \code{\link{is.complex}},
  \code{\link{is.double}},
  \code{\link{is.environment}},
  \code{\link{is.function}},
  \code{\link{is.integer}},
  \code{\link{is.language}},
  \code{\link{is.logical}},
  \code{\link{is.list}},
  \code{\link{is.matrix}},
  \code{\link{is.na}},        % do_isna()            [coerce.c:1244]
  \code{\link{is.nan}}        % do_isnan()           [coerce.c:1332]
  \code{\link{is.null}},
  \code{\link{is.numeric}},
  \code{\link{is.object}},
  \code{\link{is.pairlist}},
  \code{\link{is.recursive}},
  \code{\link{is.single}},
  \code{\link{is.symbol}}.
}
\seealso{
  \code{\link[utils]{methods}} for the methods of non-Internal generic functions.
}
\keyword{methods}
\eof
\name{.Script}
\title{Scripting Language Interface}
\alias{.Script}
\description{
  Run a script through its interpreter with given arguments.
}
\usage{
.Script(interpreter, script, args, \dots)
}
\arguments{
  \item{interpreter}{a character string naming the interpreter for the
    script.}
  \item{script}{a character string with the base file name of the
    script, which must be located in the \file{\code{interpreter}}
    subdirectory of \file{R\_HOME/share}.}
  \item{args}{a character string giving the arguments to pass to the
    script.}
  \item{\dots}{further arguments to be passed to \code{\link{system}}
    when invoking the interpreter on the script.}
}
\note{This function is for R internal use only.}
\examples{
.Script("perl", "massage-Examples.pl",
        paste("tools", system.file("R-ex", package = "tools")))
}
\keyword{interface}
\eof
\name{zip.file.extract}
\alias{zip.file.extract}
\title{Extract File from a Zip Archive}
\usage{
zip.file.extract(file, zipname = "R.zip")
}
\arguments{
 \item{file}{A file name.}
 \item{zipname}{The file name of a \code{zip} archive, including the
   \code{".zip"} extension if required.}
}
\description{
  This will extract the file named \code{file} from the zip archive,
  if possible, and write it in a temporary location.
}
\details{
  The method used is selected by \code{options(unzip=)}. All platforms
  support an \code{"internal"} unzip: this is the default under Windows
  and the fall-back under Unix if no \code{unzip} program was found
  during configuration and \env{R\_UNZIPCMD} is not set.
  
  The file will be extracted if it is in the archive and any required
  \code{unzip} utility is available.  It will probably be extracted to
  the directory given by \code{tempdir}, overwriting an existing file of
  that name.
}
\value{
  The name of the original or extracted file.  Success is indicated by
  returning a different name.
}
\note{
  The \code{"internal"} method is very simple, and will not set file dates.
}

\keyword{file}
\eof
\name{Signals}
\alias{Signals}
\title{Interrupting Execution of R}
\description{
  On receiving \code{SIGUSR1} \R will save the workspace and quit.
  \code{SIGUSR2} has the same result except that the \code{\link{.Last}}
  function and \code{\link{on.exit}} expressions will not be called.
}
\usage{
kill -USR1 pid
kill -USR2 pid
}
\arguments{
  \item{pid}{The process ID of the R process}
}
\section{Warning}{
  It is possible that one or more R objects will be undergoing
  modification at the time the signal is sent.  These objects could be
  saved in a corrupted form.
}
\keyword{utilities}
\eof
\name{system}
\alias{system}
\alias{unix}
\title{Invoke a System Command}
\description{
  \code{system} invokes the OS command specified by \code{command}.
}
\usage{
system(command, intern = FALSE, ignore.stderr = FALSE)
}
\arguments{
  \item{command}{the system command to be invoked, as a string.}
  \item{intern}{a logical, indicates whether to make the output of the
    command an \R object.}
  \item{ignore.stderr}{a logical indicating whether error messages (written
    to \file{stderr}) should be ignored.}
}
\value{
  If \code{intern=TRUE}, a character vector giving the output of the
  command, one line per character string. If the command could not be
  run or gives an error a \R error is generated.

  If \code{intern=FALSE}, the return value is an error code.
}
\details{
  If \code{intern} is \code{TRUE} then \code{popen} is used to invoke the
  command and the output collected, line by line, into an \R
  \code{\link{character}} vector which is returned as the value of
  \code{system}.  Output lines of more than 8095 characters will be split.

  If \code{intern} is \code{FALSE} then the C function \code{system}
  is used to invoke the command and the value returned by \code{system}
  is the exit status of this function.

  \code{unix} is a \emph{deprecated} alternative, available for
  backwards compatibility.
}
\seealso{\code{\link{.Platform}} for platform specific variables.}
\examples{
# list all files in the current directory using the -F flag
\dontrun{system("ls -F")}

# t1 is a character vector, each one
# representing a separate line of output from who
t1 <- system("who", TRUE)

system("ls fizzlipuzzli", TRUE, TRUE)# empty since file doesn't exist
}
\keyword{interface}
\keyword{file}
\keyword{utilities}
\eof
