% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/estimate.default.R
\name{estimate.default}
\alias{estimate.default}
\alias{estimate}
\alias{estimate.mlm}
\title{Influence function based inference}
\usage{
\method{estimate}{default}(
  x = NULL,
  f = NULL,
  ...,
  data,
  id,
  coef,
  IC = TRUE,
  vcov,
  stack = TRUE,
  average = FALSE,
  subset,
  keep,
  use,
  regex = FALSE,
  ignore.case = FALSE,
  print = NULL,
  labels,
  label.width,
  contrast,
  null,
  level = NULL,
  type = NULL,
  var.adj = NULL,
  df = NULL,
  back.transform = NULL
)
}
\arguments{
\item{x}{model object (\code{glm}, \code{lvmfit}, ...) or an existing \code{estimate}
object. When two model objects are supplied (e.g., \code{estimate(g, g0)}) a
likelihood-ratio test is performed.}

\item{f}{transformation of model parameters. Accepts several input types: - A
\strong{function} \code{f(p)} or \code{f(p, data)}: applies the delta method. When \code{f}
returns a named list the names are used as parameter labels. - A
\strong{matrix}: used as a contrast (linear combination) matrix. - A \strong{numeric
vector} of parameter indices: converted to a contrast that selects and
differences those parameters. - A \strong{list} of indices: each element selects
one parameter. - \strong{Character} expressions: supports wildcards (\code{"?"},
\code{"*"}) and arithmetic on parameter names (e.g., \code{"z" - "x"}, \code{2 * "z" - 3 * "x"}).}

\item{...}{additional arguments to lower level functions}

\item{data}{\code{data.frame} used by \code{f} when the transformation depends on
covariates (see \code{average}). Defaults to \code{model.frame(x)}.}

\item{id}{(optional) cluster identifier. Can be a vector of cluster IDs, a
one-sided formula (evaluated in \code{data}), a single character column name, or
a logical scalar (\code{TRUE} for one-to-one matching, \code{FALSE} for
independence). When supplied, the IF is aggregated within clusters to
produce cluster-robust standard errors.}

\item{coef}{(optional) named parameter vector. Used instead of \code{coef(x)} when
constructing an \code{estimate} object without a model.}

\item{IC}{if \code{TRUE} (default) the influence function matrix is estimated and
stored in the returned object (extract with the \link{IC} method). Can also be a
user-supplied IF matrix (one row per observation, one column per
parameter), which is used directly instead of estimating it from \code{x}.}

\item{vcov}{(optional) covariance matrix of parameter estimates, or a
logical. If \code{TRUE}, \link[stats:vcov]{stats::vcov} is used to obtain the (model-based)
covariance matrix from \code{x}, yielding non-robust standard errors. If a
matrix is supplied it is used directly. When omitted or \code{FALSE}, robust
standard errors are computed from the influence function.}

\item{stack}{if \code{TRUE} (default) the influence function contributions are
summed within each cluster defined by \code{id}. Set to \code{FALSE} to keep the
un-stacked (per-observation) decomposition.}

\item{average}{if \code{TRUE} the function computes the standardized
(marginalized) estimate \eqn{\hat\Psi = P_n f(X; \hat\theta)}, i.e., the
empirical mean of \code{f(p, data)} over all rows of \code{data}. The influence
function accounts for both the empirical averaging and the parameter
estimation uncertainty (see Details).}

\item{subset}{(optional) logical vector, expression evaluated in \code{data}, or
column name. When used together with \code{average = TRUE}, the average is
conditioned on the subpopulation where \code{subset} is \code{TRUE}, yielding a
conditional marginalized estimate.}

\item{keep}{(optional) index of parameters to keep from final result. Accepts
integer indices, character names, or (with \code{regex = TRUE}) perl-compatible
regular expressions.}

\item{use}{(optional) index of parameters to use in calculations. The
selected parameters are first extracted (via \code{keep}) and then the remaining
arguments (\code{f}, \code{contrast}, etc.) are applied to this subset.}

\item{regex}{if \code{TRUE} use perl-compatible regular expressions for \code{keep} and
\code{use} arguments}

\item{ignore.case}{ignore case in regular expressions}

\item{print}{(optional) custom print function for the resulting \code{estimate}
object}

\item{labels}{(optional) character vector of coefficient names}

\item{label.width}{(optional) max display width of labels}

\item{contrast}{(deprecated, use summary method) contrast matrix for a final
Wald test. When supplied together with \code{null}, tests \eqn{H_0: B\theta =
b_0}.}

\item{null}{(deprecated, use summary method) null hypothesis vector \eqn{b_0}
to test against (default 0)}

\item{level}{(deprecated, use summary method) level of confidence limits
(default 0.95)}

\item{type}{(deprecated, use summary method) type of small-sample correction
for cluster-robust variance. One of: - \code{"robust"} (default): no correction.
\itemize{
\item \code{"df"}: applies \eqn{n/(n-p)} correction (Mancl & DeRouen, 2001). -
\code{"mbn"}: Morel-Bokossa-Neerchal (2003) correction. - \code{"hc3"}:
leverage-adjusted HC3-type correction (blended with \code{var.adj}). - \code{"hc4"}:
Cribari-Neto (2004) leverage-adjusted correction.
}}

\item{var.adj}{(deprecated, use summary method) blending parameter for the
HC3 leverage adjustment (default 0.25). Controls the weight between
observation-level empirical leverage and the average leverage \eqn{p/n}.}

\item{df}{(deprecated, use summary method) degrees of freedom for t-based
inference (default: \code{NULL} for Gaussian approximation; when set, confidence
intervals and p-values use the t-distribution with \code{df} degrees of
freedom).}

\item{back.transform}{(deprecated, use summary method) function applied to
the point estimates and confidence interval bounds \emph{after} inference is
performed on the original scale. Useful for variance-stabilizing
transformations, e.g., compute CIs on the \code{atanh} (Fisher z) scale and
back-transform with \code{tanh}.}
}
\value{
Object of class \code{estimate} with the following elements:
\item{coef}{Named vector of parameter estimates.}
\item{vcov}{Variance-covariance matrix.}
\item{IC}{Influence function matrix (observations x parameters).}
\item{coefmat}{Formatted coefficient table (estimate, std.err,
confidence limits, p-value).}
\item{id}{Cluster/id variable used.}
\item{ncluster}{Number of clusters.}
\item{n}{Number of observations.}
\item{compare}{(When \code{null} or contrasts are specified) Wald test result.}
}
\description{
Primary tool for obtaining parameter estimates with robust (sandwich)
standard errors, applying the delta method, and testing linear hypotheses.
The function returns an object of class \code{estimate} which serves as a
general container for parameter estimates and their influence functions
(IFs). Three calling conventions are supported:
}
\details{
\itemize{
\item \code{estimate(x, ...)} -- extract estimates from a model object
\item \code{estimate(coef=, IC=, ...)} -- construct from coefficients and IF matrix
\item \code{estimate(coef=, vcov=, ...)} -- construct from coefficients and
covariance matrix
}
}
\section{Influence functions and robust standard errors}{
An estimator \eqn{\widehat{\theta}} is \emph{regular and asymptotically
linear} (RAL) when it admits the iid decomposition
\deqn{\sqrt{n}(\widehat{\theta}-\theta) =
\frac{1}{\sqrt{n}}\sum_{i=1}^n \mathrm{IC}(Z_i; P) + o_p(1)}
where \eqn{\mathrm{IC}} is the unique \emph{influence function} satisfying
\eqn{E\{\mathrm{IC}(Z; P)\} = 0}. By the central limit theorem
\deqn{\sqrt{n}(\widehat{\theta}-\theta)
\overset{d}{\longrightarrow}
N(0,\; \mathrm{Var}\{\mathrm{IC}(Z; P)\})}
and the asymptotic variance is consistently estimated by the empirical
variance of the plugin IF estimate, yielding robust (sandwich) standard
errors. The estimated IF can be extracted with the \link{IC} method.
}

\section{Parameter transformations (delta method)}{
When \code{f} is a function \eqn{\phi: R^p \to R^m}, the delta method is
applied:
\deqn{\sqrt{n}\{\phi(\widehat{\theta}) - \phi(\theta)\} =
\frac{1}{\sqrt{n}}\sum_{i=1}^n
\nabla\phi(\theta)\,\mathrm{IC}(Z_i; P) + o_p(1)}
Derivatives are computed numerically via \link[numDeriv:jacobian]{numDeriv::jacobian} unless the
function returns an attribute \code{"grad"} with the analytic Jacobian.

Alternatively, \code{estimate} objects support direct arithmetic operations
(e.g., \code{a * b}, \code{exp(a)}, \code{a^b}) which apply the delta method with
\emph{exact} (analytical) derivatives computed automatically. This influence
function calculus allows building complex transformations from simple
building blocks without numerical differentiation. See the last example
section ("influence function calculus") and
\code{vignette("influencefunction", package = "lava")} for details.
}

\section{Averaging and marginalization}{
When \code{average = TRUE} and \code{f(p, data)} depends on covariates, the
target parameter is the standardized (marginalized) estimate
\eqn{\Psi = E\{f(X;\theta)\}}. The IF for the averaged estimate
accounts for both the empirical averaging and parameter estimation
uncertainty:
\deqn{\mathrm{IC}_\Psi(Z; P) = f(X;\theta) - \Psi +
[E\nabla_\theta f(X;\theta)]\,\phi(Z; P)}
When \code{subset} is also specified, the average is conditioned on the
subpopulation, yielding a conditional marginalized estimate.
}

\section{Cluster-robust standard errors}{
When \code{id} is supplied, the per-observation IF contributions are summed
within clusters (when \code{stack = TRUE}), producing the cluster-level IF
\eqn{\widetilde{\mathrm{IC}}(Z_i; P) = \sum_{k=1}^{N_i}
\frac{n}{N}\mathrm{IC}(Z_{ik}; P)}.
The resulting variance estimate is equivalent to the GEE working
independence sandwich estimator.

For full theoretical background and worked examples see
\code{vignette("influencefunction", package = "lava")}.
}

\examples{

## Simulation from logistic regression model
m <- lvm(y~x+z);
distribution(m,y~x) <- binomial.lvm("logit")
d <- sim(m,1000)
g <- glm(y~z+x,data=d,family=binomial())
g0 <- glm(y~1,data=d,family=binomial())

## LRT
estimate(g, g0)


estimate(g)

## Testing contrasts
summary(estimate(g), null=0)
estimate(g, rbind(c(1,1,0), c(1,0,2)))
summary(estimate(g, rbind(c(1,1,0), c(1,0,2))), null=c(1,2))
estimate(g, 2:3) ## same as cbind(0,1,-1)
estimate(g, as.list(2:3)) ## same as rbind(c(0,1,0),c(0,0,1))
## Alternative syntax
estimate(g, "z", "z"-"x", 2*"z"-3*"x")
estimate(g, "?")  ## Wildcards
estimate(g, "*Int*", "z")
summary(estimate(g, "1", "2"-"3"), null = c(0,1))
estimate(g, 2, 3)

## Usual (non-robust) confidence intervals
estimate(g, vcov=TRUE)
estimate(g, vcov=vcov(g))

## Transformations
estimate(g, function(p) p[1]+p[2])

## Multiple parameters
e <- estimate(g, function(p) c(p[1]+p[2], p[1]*p[2]))
e
vcov(e)

## Label new parameters
estimate(g, function(p) list("a1"=p[1]+p[2], "b1"=p[1]*p[2]))
#'
## Multiple group
m <- lvm(y~x)
m <- baptize(m)
d2 <- d1 <- sim(m,50,seed=1)
e <- estimate(list(m,m),list(d1,d2))
estimate(e) ## Wrong
ee <- estimate(e, id=rep(seq(nrow(d1)), 2)) ## Clustered
ee
estimate(lm(y~x,d1))

## Marginalize / standardization
f <- function(p,data)
  list(p0=expit(p["(Intercept)"] + p["z"]*data[,"z"]),
       p1=expit(p["(Intercept)"] + p["x"] + p["z"]*data[,"z"]))
e <- estimate(g, f, average=TRUE)
e
estimate(e,diff)
estimate(e,cbind(1,1))

## Clusters and subset (conditional marginal effects)
d$id <- rep(seq(nrow(d)/4),each=4)
estimate(g,function(p,data)
         list(p0=expit(p[1] + p["z"]*data[,"z"])),
         subset=d$z>0, id=d$id, average=TRUE)

## More examples with clusters:
m <- lvm(c(y1,y2,y3)~u+x)
d <- sim(m,10)
l1 <- glm(y1~x,data=d)
l2 <- glm(y2~x,data=d)
l3 <- glm(y3~x,data=d)

## Some random id-numbers
id1 <- c(1,1,4,1,3,1,2,3,4,5)
id2 <- c(1,2,3,4,5,6,7,8,1,1)
id3 <- seq(10)

## Un-stacked and stacked i.i.d. decomposition
IC(estimate(l1,id=id1,stack=FALSE))
IC(estimate(l1,id=id1))

## Combined i.i.d. decomposition
e1 <- estimate(l1,id=id1)
e2 <- estimate(l2,id=id2)
e3 <- estimate(l3,id=id3)
(a2 <- merge(e1,e2,e3))

## If all models were estimated on the same data we could use the
## syntax:
## Reduce(merge,estimate(list(l1,l2,l3)))

## Same:
IC(a1 <- merge(l1,l2,l3,id=list(id1,id2,id3)))

IC(merge(l1,l2,l3,id=TRUE)) # one-to-one (same clusters)
IC(merge(l1,l2,l3,id=FALSE)) # independence


# ------ influence function calculus -------
a <- estimate(coef = c("a" = 0.5), IC = scale(rnorm(10), scale=FALSE), id = 1:10)
b <- estimate(coef = c("b" = 0.8), IC = scale(rnorm(10), scale=FALSE), id = 1:10)

e <- c(a, b) # merge
merge(a, b)
c(e1=a, b) # naming of par
labels(e, c("p1", "p2")) # renaming parameters
e["a"] # subset
subset(e, "a")

# pipes
# c(a, b) |>
#  transform(function(x) x^2) |>
#  subset("a") |>
#  labels("sq")

# Parameter transformation with automatic calculation of derivatives
a * b
(3 * cos(a) / sqrt(b) + 1) / a
expit(c(a,b))
c(sum=sum(e), sum2=a+b,
  prod=prod(e), prod2=a*b)
e \%*\% e # inner prod.
c(1, 2) \%*\% e
c(pow = a^b)
a^c(0.5, 2)
c(b=e["a"] * e["b"] / a, also.b=e["b"])

B <- rbind(c(1,-1), c(1,0), c(0,1))
B \%*\% e
e == 1 # wald-test, null-hypothesis H0: b=1
e == c(1,2)
B \%*\% e == 1
}
\seealso{
\link{estimate.array}, \link{merge.estimate}, \link{contr}, \link{parsedesign},
\link{pairwise.diff}, \link{c.estimate}, \link{summary.estimate},
\code{coef.estimate},
\code{vcov.estimate}, \code{transform.estimate}, \code{labels.estimate},
}
