\HeaderA{glm}{Fitting Generalized Linear Models}{glm}
\methaliasA{glm.fit}{glm}{glm.fit}
\aliasA{print.glm}{glm}{print.glm}
\aliasA{weights.glm}{glm}{weights.glm}
\keyword{models}{glm}
\keyword{regression}{glm}
\begin{Description}\relax
\code{glm} is used to fit generalized linear models, specified by
giving a symbolic description of the linear predictor and a
description of the error distribution.
\end{Description}
\begin{Usage}
\begin{verbatim}
glm(formula, family = gaussian, data, weights, subset,
    na.action, start = NULL, etastart, mustart,
    offset, control = glm.control(...), model = TRUE,
    method = "glm.fit", x = FALSE, y = TRUE, contrasts = NULL,
    ...)

glm.fit(x, y, weights = rep(1, nobs),
        start = NULL, etastart = NULL, mustart = NULL,
        offset = rep(0, nobs), family = gaussian(),
        control = glm.control(), intercept = TRUE)

## S3 method for class 'glm':
weights(object, type = c("prior", "working"), ...)
\end{verbatim}
\end{Usage}
\begin{Arguments}
\begin{ldescription}
\item[\code{formula}] an object of class \code{"\LinkA{formula}{formula}"} (or one that
can be coerced to that class): a symbolic description of the
model to be fitted.  The details of model specification are given
under \sQuote{Details}.
\item[\code{family}] a description of the error distribution and link
function to be used in the model. This can be a character string
naming a family function, a family function or the result of a call
to a family function.  (See \code{\LinkA{family}{family}} for details of
family functions.)
\item[\code{data}] an optional data frame, list or environment (or object
coercible by \code{\LinkA{as.data.frame}{as.data.frame}} to a data frame) containing
the variables in the model.  If not found in \code{data}, the
variables are taken from \code{environment(formula)},
typically the environment from which \code{glm} is called.
\item[\code{weights}] an optional vector of weights to be used in the fitting
process.  Should be \code{NULL} or a numeric vector.
\item[\code{subset}] an optional vector specifying a subset of observations
to be used in the fitting process.
\item[\code{na.action}] a function which indicates what should happen
when the data contain \code{NA}s.  The default is set by
the \code{na.action} setting of \code{\LinkA{options}{options}}, and is
\code{\LinkA{na.fail}{na.fail}} if that is unset.  The \sQuote{factory-fresh}
default is \code{\LinkA{na.omit}{na.omit}}.  Another possible value is
\code{NULL}, no action.  Value \code{\LinkA{na.exclude}{na.exclude}} can be useful.
\item[\code{start}] starting values for the parameters in the linear predictor.
\item[\code{etastart}] starting values for the linear predictor.
\item[\code{mustart}] starting values for the vector of means.
\item[\code{offset}] this can be used to specify an \emph{a priori}
known component to be included in the linear predictor
during fitting.  This should be \code{NULL} or a numeric vector of
length either one or equal to the number of cases.
One or more \code{\LinkA{offset}{offset}} terms can be included in the
formula instead or as well, and if both are specified their sum is
used.  See \code{\LinkA{model.offset}{model.offset}}.
\item[\code{control}] a list of parameters for controlling the fitting
process.  See the documentation for \code{\LinkA{glm.control}{glm.control}}
for details.
\item[\code{model}] a logical value indicating whether \emph{model frame}
should be included as a component of the returned value.
\item[\code{method}] the method to be used in fitting the model.
The default method \code{"glm.fit"} uses iteratively reweighted
least squares (IWLS).  The only current alternative is
\code{"model.frame"} which returns the model frame and does no fitting.
\item[\code{x, y}] For \code{glm}:
logical values indicating whether the response vector and model
matrix used in the fitting process should be returned as components
of the returned value.

For \code{glm.fit}: \code{x} is a design matrix of dimension \code{n
      * p}, and \code{y} is a vector of observations of length \code{n}.

\item[\code{contrasts}] an optional list. See the \code{contrasts.arg}
of \code{model.matrix.default}.
\item[\code{intercept}] logical. Should an intercept be included in the
\emph{null} model?
\item[\code{object}] an object inheriting from class \code{"glm"}.
\item[\code{type}] character, partial matching allowed.  Type of weights to
extract from the fitted model object.
\item[\code{...}] For \code{glm}: arguments to be passed by default to
\code{\LinkA{glm.control}{glm.control}}: see argument \code{control}.

For \code{weights}:
further arguments passed to or from other methods.

\end{ldescription}
\end{Arguments}
\begin{Details}\relax
A typical predictor has the form \code{response \textasciitilde{} terms} where
\code{response} is the (numeric) response vector and \code{terms} is a
series of terms which specifies a linear predictor for \code{response}.
For \code{binomial} and \code{quasibinomial} families the response can
also be specified as a \code{\LinkA{factor}{factor}} (when the first level
denotes failure and all
others success) or as a two-column matrix with the columns giving the
numbers of successes and failures.  A terms specification of the form
\code{first + second} indicates all the terms in \code{first} together
with all the terms in \code{second} with duplicates removed.  The terms in
the formula will be re-ordered so that main effects come first,
followed by the interactions, all second-order, all third-order and so
on: to avoid this pass a \code{terms} object as the formula.

A specification of the form \code{first:second} indicates the
the set of terms obtained by taking the interactions of
all terms in \code{first} with all terms in \code{second}.
The specification \code{first*second} indicates the \emph{cross}
of \code{first} and \code{second}.
This is the same as \code{first + second + first:second}.

\code{glm.fit} is the workhorse function.

If more than one of \code{etastart}, \code{start} and \code{mustart}
is specified, the first in the list will be used.  It is often
advisable to supply starting values for a \code{\LinkA{quasi}{quasi}} family,
and also for families with unusual links such as \code{gaussian("log")}.

All of \code{weights}, \code{subset}, \code{offset}, \code{etastart}
and \code{mustart} are evaluated in the same way as variables in
\code{formula}, that is first in \code{data} and then in the
environment of \code{formula}.
\end{Details}
\begin{Value}
\code{glm} returns an object of class inheriting from \code{"glm"}
which inherits from the class \code{"lm"}. See later in this section.

The function \code{\LinkA{summary}{summary}} (i.e., \code{\LinkA{summary.glm}{summary.glm}}) can
be used to obtain or print a summary of the results and the function
\code{\LinkA{anova}{anova}} (i.e., \code{\LinkA{anova.glm}{anova.glm}})
to produce an analysis of variance table.

The generic accessor functions \code{\LinkA{coefficients}{coefficients}},
\code{effects}, \code{fitted.values} and \code{residuals} can be used to
extract various useful features of the value returned by \code{glm}.

\code{weights} extracts a vector of weights, one for each case in the
fit (after subsetting and \code{na.action}).

An object of class \code{"glm"} is a list containing at least the
following components:

\begin{ldescription}
\item[\code{coefficients}] a named vector of coefficients
\item[\code{residuals}] the \emph{working} residuals, that is the residuals
in the final iteration of the IWLS fit.  Since cases with zero
weights are omitted, their working residuals are \code{NA}.
\item[\code{fitted.values}] the fitted mean values, obtained by transforming
the linear predictors by the inverse of the link function.
\item[\code{rank}] the numeric rank of the fitted linear model.
\item[\code{family}] the \code{\LinkA{family}{family}} object used.
\item[\code{linear.predictors}] the linear fit on link scale.
\item[\code{deviance}] up to a constant, minus twice the maximized
log-likelihood.  Where sensible, the constant is chosen so that a
saturated model has deviance zero.
\item[\code{aic}] Akaike's \emph{An Information Criterion}, minus twice the
maximized log-likelihood plus twice the number of coefficients (so
assuming that the dispersion is known).
\item[\code{null.deviance}] The deviance for the null model, comparable with
\code{deviance}. The null model will include the offset, and an
intercept if there is one in the model.  Note that this will be
incorrect if the link function depends on the data other than
through the fitted mean: specify a zero offset to force a correct
calculation.
\item[\code{iter}] the number of iterations of IWLS used.
\item[\code{weights}] the \emph{working} weights, that is the weights
in the final iteration of the IWLS fit.
\item[\code{prior.weights}] the case weights initially supplied.
\item[\code{df.residual}] the residual degrees of freedom.
\item[\code{df.null}] the residual degrees of freedom for the null model.
\item[\code{y}] the \code{y} vector used. (It is a vector even for a binomial
model.)
\item[\code{converged}] logical. Was the IWLS algorithm judged to have converged?
\item[\code{boundary}] logical. Is the fitted value on the boundary of the
attainable values?
\item[\code{call}] the matched call.
\item[\code{formula}] the formula supplied.
\item[\code{terms}] the \code{\LinkA{terms}{terms}} object used.
\item[\code{data}] the \code{data argument}.
\item[\code{offset}] the offset vector used.
\item[\code{control}] the value of the \code{control} argument used.
\item[\code{method}] the name of the fitter function used, currently always
\code{"glm.fit"}.
\item[\code{contrasts}] (where relevant) the contrasts used.
\item[\code{xlevels}] (where relevant) a record of the levels of the factors
used in fitting.
\end{ldescription}


In addition, non-empty fits will have components \code{qr}, \code{R}
and \code{effects} relating to the final weighted linear fit.

Objects of class \code{"glm"} are normally of class \code{c("glm",
    "lm")}, that is inherit from class \code{"lm"}, and well-designed
methods for class \code{"lm"} will be applied to the weighted linear
model at the final iteration of IWLS.  However, care is needed, as
extractor functions for class \code{"glm"} such as
\code{\LinkA{residuals}{residuals}} and \code{weights} do \bold{not} just pick out
the component of the fit with the same name.

If a \code{\LinkA{binomial}{binomial}} \code{glm} model was specified by giving a
two-column response, the weights returned by \code{prior.weights} are
the total numbers of cases (factored by the supplied case weights) and
the component \code{y} of the result is the proportion of successes.
\end{Value}
\begin{Author}\relax
The original \R{} implementation of \code{glm} was written by Simon
Davies working for Ross Ihaka at the University of Auckland, but has
since been extensively re-written by members of the R Core team.

The design was inspired by the S function of the same name described
in Hastie \& Pregibon (1992).
\end{Author}
\begin{References}\relax
Dobson, A. J. (1990)
\emph{An Introduction to Generalized Linear Models.}
London: Chapman and Hall.

Hastie, T. J. and Pregibon, D. (1992)
\emph{Generalized linear models.}
Chapter 6 of \emph{Statistical Models in S}
eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.

McCullagh P. and Nelder, J. A. (1989)
\emph{Generalized Linear Models.}
London: Chapman and Hall.

Venables, W. N. and Ripley, B. D. (2002)
\emph{Modern Applied Statistics with S.}
New York: Springer.
\end{References}
\begin{SeeAlso}\relax
\code{\LinkA{anova.glm}{anova.glm}}, \code{\LinkA{summary.glm}{summary.glm}}, etc. for
\code{glm} methods,
and the generic functions \code{\LinkA{anova}{anova}}, \code{\LinkA{summary}{summary}},
\code{\LinkA{effects}{effects}}, \code{\LinkA{fitted.values}{fitted.values}},
and \code{\LinkA{residuals}{residuals}}.

\code{\LinkA{lm}{lm}} for non-generalized \emph{linear} models (which SAS
calls GLMs, for \sQuote{general} linear models).

\code{\LinkA{loglin}{loglin}} and \code{\LinkA{loglm}{loglm}} for fitting
log-linear models (which binomial and Poisson GLMs are) to contingency
tables.

\code{bigglm} in package \pkg{biglm} for an alternative
way to fit GLMs to large datasets (especially those with many cases).

\code{\LinkA{esoph}{esoph}}, \code{\LinkA{infert}{infert}} and
\code{\LinkA{predict.glm}{predict.glm}} have examples of fitting binomial glms.
\end{SeeAlso}
\begin{Examples}
\begin{ExampleCode}
## Dobson (1990) Page 93: Randomized Controlled Trial :
counts <- c(18,17,15,20,10,20,25,13,12)
outcome <- gl(3,1,9)
treatment <- gl(3,3)
print(d.AD <- data.frame(treatment, outcome, counts))
glm.D93 <- glm(counts ~ outcome + treatment, family=poisson())
anova(glm.D93)
summary(glm.D93)

## an example with offsets from Venables & Ripley (2002, p.189)
utils::data(anorexia, package="MASS")

anorex.1 <- glm(Postwt ~ Prewt + Treat + offset(Prewt),
                family = gaussian, data = anorexia)
summary(anorex.1)

# A Gamma example, from McCullagh & Nelder (1989, pp. 300-2)
clotting <- data.frame(
    u = c(5,10,15,20,30,40,60,80,100),
    lot1 = c(118,58,42,35,27,25,21,19,18),
    lot2 = c(69,35,26,21,18,16,13,12,12))
summary(glm(lot1 ~ log(u), data=clotting, family=Gamma))
summary(glm(lot2 ~ log(u), data=clotting, family=Gamma))

## Not run: 
## for an example of the use of a terms object as a formula
demo(glm.vr)
## End(Not run)\end{ExampleCode}
\end{Examples}

