| Title: | Extended Instrumental Variables Estimation with Diagnostics |
|---|---|
| Description: | Comprehensive instrumental variables and GMM estimation with automatic diagnostics, inspired by the 'Stata' command 'ivreg2' of Baum, Schaffer, and Stillman (2003) <doi:10.1177/1536867X0300300101> and Baum, Schaffer, and Stillman (2007) <doi:10.1177/1536867X0800700402>. Supports 2SLS, LIML, Fuller, k-class, two-step efficient GMM, and continuously-updated (CUE) estimators. Provides classical, robust, cluster-robust, HAC, and Driscoll-Kraay standard errors. Reports weak identification, underidentification, overidentification, and endogeneity tests at estimation time. All outputs are verified against 'Stata' within tight numerical tolerances. |
| Authors: | Francis DiTraglia [aut, cre], Christopher F. Baum [ctb, cph] (Author of the Stata ivreg2 program from which ivreg2r is adapted), Mark E. Schaffer [ctb, cph] (Author of the Stata ivreg2 program from which ivreg2r is adapted), Steven Stillman [ctb, cph] (Author of the Stata ivreg2 program from which ivreg2r is adapted) |
| Maintainer: | Francis DiTraglia <[email protected]> |
| License: | GPL-3 |
| Version: | 0.1.0 |
| Built: | 2026-07-21 14:49:22 UTC |
| Source: | https://github.com/cran/ivreg2r |
Employment, wages, and capital stock for UK companies: an unbalanced annual panel over 1976–1984 (140 companies, 1,031 firm-year observations). This is the companion dataset to Arellano, M. and Bond, S. (1991), "Some Tests of Specification for Panel Data: Monte Carlo Evidence and an Application to Employment Equations," Review of Economic Studies, 58(2), 277–297, shipped as distributed (levels plus the log transforms and year dummies used throughout the Stata literature).
abdataabdata
A data frame with 1,031 observations and 16 variables:
Industry code.
Calendar year (1976–1984). The time variable: use as
tvar.
Employment.
Real wage.
Gross capital stock.
Industry output.
Log employment, log(emp).
Log real wage, log(wage).
Log gross capital stock, log(cap).
Log industry output, log(indoutpt).
Year dummy: 1 if year == 1980.
Year dummy: 1 if year == 1981.
Year dummy: 1 if year == 1982.
Year dummy: 1 if year == 1983.
Year dummy: 1 if year == 1984.
Firm identifier (140 distinct companies). Use as ivar.
n, w, k, and ys are natural logs of
emp, wage, cap, and indoutpt respectively.
yr1980–yr1984 are year-dummy indicators (1 in the named
year, 0 otherwise).
Arellano, M. and Bond, S. (1991). Some tests of specification for panel data: Monte Carlo evidence and an application to employment equations. Review of Economic Studies, 58(2), 277–297.
Downloaded from http://fmwww.bc.edu/ec-p/data/macro/abdata.dta.
Redistribution basis: system.file("COPYRIGHTS", package = "ivreg2r").
Other ivreg2r datasets:
card,
cigar,
griliches,
grunfeld,
klein,
mroz,
nlswork,
phillips,
stockwatson,
wagepan
data(abdata) # ivreg2 help file line 1558: one-way cluster on firm id fit <- ivreg2(n ~ w + k, data = abdata, clusters = ~id) summary(fit)data(abdata) # ivreg2 help file line 1558: one-way cluster on firm id fit <- ivreg2(n ~ w + k, data = abdata, clusters = ~id) summary(fit)
Adds .fitted and .resid columns to the model frame (or user-supplied
data).
## S3 method for class 'ivreg2' augment(x, data = NULL, ...)## S3 method for class 'ivreg2' augment(x, data = NULL, ...)
x |
An object of class |
data |
A data frame to augment. If |
... |
Additional arguments (ignored). |
A tibble::tibble() with all original data columns plus .fitted,
and .resid when the response is available.
Other broom methods:
glance.ivreg2(),
tidy.ivreg2()
data(mroz) mroz_work <- subset(mroz, inlf == 1) fit <- ivreg2(lwage ~ exper + expersq | educ | age + kidslt6 + kidsge6, data = mroz_work, vcov = "robust") augment(fit) |> head() # Residuals vs fitted aug <- augment(fit) plot(aug$.fitted, aug$.resid, xlab = "Fitted", ylab = "Residuals") abline(h = 0, lty = 2)data(mroz) mroz_work <- subset(mroz, inlf == 1) fit <- ivreg2(lwage ~ exper + expersq | educ | age + kidslt6 + kidsge6, data = mroz_work, vcov = "robust") augment(fit) |> head() # Residuals vs fitted aug <- augment(fit) plot(aug$.fitted, aug$.resid, xlab = "Fitted", ylab = "Residuals") abline(h = 0, lty = 2)
Cross-sectional data from the National Longitudinal Survey of Young Men (1966–1981) used by Card (1995) to estimate the return to schooling using college proximity as an instrument for education.
cardcard
A data frame with 3,010 observations and 33 variables:
Grew up near a 2-year college (binary).
Grew up near a 4-year college (binary).
Years of education.
Age in years (1976).
Father's years of education.
Mother's years of education.
NLS sampling weight.
Lived with both parents at age 14 (binary).
Lived with single mother at age 14 (binary).
Lived with stepparent at age 14 (binary).
Region dummy: New England (1966).
Region dummy: Middle Atlantic (1966).
Region dummy: East North Central (1966).
Region dummy: West North Central (1966).
Region dummy: South Atlantic (1966).
Region dummy: East South Central (1966).
Region dummy: West South Central (1966).
Region dummy: Mountain (1966).
Region dummy: Pacific (1966).
Lived in the South in 1966 (binary).
Black (binary).
Lives in SMSA (binary, 1976).
Lives in the South (binary, 1976).
Lived in SMSA in 1966 (binary).
Hourly wage (cents, 1976).
Enrolled in school in 1976 (binary).
Knowledge of the World of Work test score.
IQ score.
Marital status (1976): coded 1–6 in the source data (1 = married; the remaining codes distinguish other marital statuses). Not a binary indicator; recode before use as a regressor.
Had a library card at age 14 (binary).
Years of labor market experience (age - educ - 6).
Log hourly wage.
Experience squared (exper^2).
Card, D. (1995). "Using Geographic Variation in College Proximity to Estimate the Return to Schooling." In L.N. Christofides, E.K. Grant, and R. Swidinsky (Eds.), Aspects of Labour Market Behaviour: Essays in Honour of John Vanderkamp. University of Toronto Press.
Obtained from Stata's bcuse archive (Boston College),
bcuse card.
Redistribution basis: system.file("COPYRIGHTS", package = "ivreg2r").
Other ivreg2r datasets:
abdata,
cigar,
griliches,
grunfeld,
klein,
mroz,
nlswork,
phillips,
stockwatson,
wagepan
data(card) # IV regression: instrument education with college proximity. # Control set from Card (1995, Table 2) / Wooldridge (2020), Example 15.4. fit <- ivreg2( lwage ~ exper + expersq + black + smsa + south + smsa66 + reg662 + reg663 + reg664 + reg665 + reg666 + reg667 + reg668 + reg669 | educ | nearc4, data = card ) summary(fit)data(card) # IV regression: instrument education with college proximity. # Control set from Card (1995, Table 2) / Wooldridge (2020), Example 15.4. fit <- ivreg2( lwage ~ exper + expersq + black + smsa + south + smsa66 + reg662 + reg663 + reg664 + reg665 + reg666 + reg667 + reg668 + reg669 | educ | nearc4, data = card ) summary(fit)
Annual per-capita cigarette sales for 46 U.S. states over 1963–1992 (a balanced panel, 1,380 state-year observations), along with the price per pack, population, consumer price index, per-capita disposable income, and the minimum price per pack among neighboring states used to instrument for price endogeneity. Baltagi, B. H. and Levin, D. (1992), "Cigarette taxation: raising revenues and reducing consumption," Structural Change and Economic Dynamics, 3(2), 321–335. See also Baltagi, B. H., Griffin, J. M. and Xiong, W. (2000), "To pool or not to pool: homogeneous versus heterogeneous estimators applied to cigarette demand," Review of Economics and Statistics, 82(1), 117–126.
cigarcigar
A data frame with 1,380 observations and 9 variables (46 states times 30 years, 1963–1992):
State identifier code (46 distinct U.S. states). Use as
ivar.
Year, coded 63–92 (i.e., 1963–1992). The time variable:
use as tvar.
Price per pack of cigarettes (nominal).
Population.
Population above the age of 16.
Consumer price index (1983 = 100).
Per-capita nominal disposable income.
Cigarette sales, in packs per capita.
Minimum price per pack of cigarettes in adjoining states.
price and ndi are nominal; deflate by cpi for real
terms.
Baltagi, B. H. and Levin, D. (1992). Cigarette taxation: raising revenues and reducing consumption. Structural Change and Economic Dynamics, 3(2), 321–335.
Baltagi, B. H., Griffin, J. M. and Xiong, W. (2000). To pool or not to pool: homogeneous versus heterogeneous estimators applied to cigarette demand. Review of Economics and Statistics, 82(1), 117–126.
Distributed via R package plm, data(Cigar).
Redistribution basis: system.file("COPYRIGHTS", package = "ivreg2r").
Other ivreg2r datasets:
abdata,
card,
griliches,
grunfeld,
klein,
mroz,
nlswork,
phillips,
stockwatson,
wagepan
data(cigar) # Price-endogeneity IV specification in real (CPI-deflated) terms, with # the neighboring-state minimum price as the excluded instrument, as in # the GFIC empirical example. cigar_real <- transform( cigar, lsales = log(sales), lrprice = log(price / cpi), lrndi = log(ndi / cpi), lrpimin = log(pimin / cpi) ) fit <- ivreg2(lsales ~ lrndi | lrprice | lrpimin, data = cigar_real) summary(fit)data(cigar) # Price-endogeneity IV specification in real (CPI-deflated) terms, with # the neighboring-state minimum price as the excluded instrument, as in # the GFIC empirical example. cigar_real <- transform( cigar, lsales = log(sales), lrprice = log(price / cpi), lrndi = log(ndi / cpi), lrpimin = log(pimin / cpi) ) fit <- ivreg2(lsales ~ lrndi | lrprice | lrpimin, data = cigar_real) summary(fit)
Extract coefficients from an ivreg2 object
## S3 method for class 'ivreg2' coef(object, ...)## S3 method for class 'ivreg2' coef(object, ...)
object |
An object of class |
... |
Additional arguments (ignored). |
Named numeric vector of coefficient estimates.
Other ivreg2 methods:
confint.ivreg2(),
diagnostics(),
first_stage(),
fitted.ivreg2(),
formula.ivreg2(),
ivreg2(),
model.matrix.ivreg2(),
nobs.ivreg2(),
predict.ivreg2(),
print.ivreg2(),
print.summary.ivreg2(),
residuals.ivreg2(),
summary.ivreg2(),
terms.ivreg2(),
update.ivreg2(),
vcov.ivreg2()
Computes confidence intervals using the t distribution when small = TRUE
was used at estimation time, and the standard normal otherwise.
## S3 method for class 'ivreg2' confint(object, parm, level = 0.95, ...)## S3 method for class 'ivreg2' confint(object, parm, level = 0.95, ...)
object |
An object of class |
parm |
A specification of which parameters to give intervals for, either a numeric vector of positions or a character vector of names. If missing, all parameters are included. |
level |
The confidence level (default 0.95). |
... |
Additional arguments (ignored). |
A matrix with columns for the lower and upper confidence limits.
ivreg2(); ivreg2r-conventions for when the t vs normal distribution is used.
Other ivreg2 methods:
coef.ivreg2(),
diagnostics(),
first_stage(),
fitted.ivreg2(),
formula.ivreg2(),
ivreg2(),
model.matrix.ivreg2(),
nobs.ivreg2(),
predict.ivreg2(),
print.ivreg2(),
print.summary.ivreg2(),
residuals.ivreg2(),
summary.ivreg2(),
terms.ivreg2(),
update.ivreg2(),
vcov.ivreg2()
Flattens the IV specification tests stored on a fitted model into a single
tibble, one row per test, so they can be filtered, joined, or printed like
any other tidyverse output instead of navigated as a nested list
(x$diagnostics$overid$stat and friends).
diagnostics(x, ...) ## S3 method for class 'ivreg2' diagnostics(x, ...)diagnostics(x, ...) ## S3 method for class 'ivreg2' diagnostics(x, ...)
x |
A fitted model object. |
... |
Additional arguments (ignored). |
A tibble::tibble() with one row per diagnostic test present on
the model and the following columns:
testCharacter. A stable machine-readable key, meant for
filter(test == ...)-style selection (e.g. "overid",
"weak_id_robust", "endogeneity").
test_nameCharacter. The display name printed by
summary().
statisticDouble. The test statistic, or — for the Stock-Yogo rows — the critical value rather than a statistic.
dfInteger. Degrees of freedom, NA when not applicable.
df2Integer. Denominator degrees of freedom, NA unless the
statistic is F-distributed.
p_valueDouble. NA when not defined (e.g. Stock-Yogo
critical values, or an exactly identified overidentification row).
tested_varsCharacter. The variable(s) tested; populated only for the endogeneity, orthogonality, and redundancy rows.
noteCharacter. A Stata-parity disclosure, or NA when none
applies. A note appears when an explicit option the user set is
silently not honored inside an automatically computed diagnostic,
matching Stata's ivreg2: a non-Bartlett kernel on the
identification and redundancy tests (Stata's ranktest hard-codes
Bartlett); kiefer on the identification tests (the Kiefer VCE
structure is dropped); psd on the identification and redundancy
tests (ranktest never receives it); center on the endogeneity
test; and method = "cue" (or "liml", for orthogonality) on the
endogeneity and orthogonality C-statistics, which come from a
recursive re-estimation that does not use those estimators. When
more than one disclosure applies to the same test, the note column
joins the sentences with a space; each note is a complete sentence,
so splitting on sentence boundaries recovers the individual
disclosures programmatically.
Rows appear only for the tests actually computed on the model: an IV
fit reports underidentification, weak identification,
overidentification, and — for every endogenous regressor, unless
narrowed to a subset via endog = — the endogeneity test by default,
while orthog = and redundant = add the corresponding orthogonality
and redundancy rows only when the user requests them.
The Stock-Yogo rows (keys of the form "sy_iv_size_10") report critical
values, not test statistics, so their p_value is always NA. An OLS
fit (single-part formula) has no diagnostics at all and returns a
zero-row tibble with the columns above.
The note column is unique to this accessor: tidy() and glance()
keep their numeric-only tidy semantics and carry no disclosure text, so
diagnostics() is the surface that exposes a note programmatically. The
same notes are printed by summary() as footnotes below the diagnostics
block.
the overidentification row
(Sargan/Hansen J) and the endogeneity row (C-statistic) are never
small-sample corrected, regardless of the main model's small argument.
The first-stage F-statistics are always small-sample corrected,
regardless of small; they are not columns of this tibble but are
reached via first_stage(). All three match Stata's ivreg2. See
ivreg2r-conventions for the full statement of which corrections
small controls.
first_stage(), glance.ivreg2()
Other ivreg2 methods:
coef.ivreg2(),
confint.ivreg2(),
first_stage(),
fitted.ivreg2(),
formula.ivreg2(),
ivreg2(),
model.matrix.ivreg2(),
nobs.ivreg2(),
predict.ivreg2(),
print.ivreg2(),
print.summary.ivreg2(),
residuals.ivreg2(),
summary.ivreg2(),
terms.ivreg2(),
update.ivreg2(),
vcov.ivreg2()
data(card) fit <- ivreg2( lwage ~ exper + expersq + black + south | educ | nearc4 + nearc2, data = card, vcov = "robust" ) diagnostics(fit)data(card) fit <- ivreg2( lwage ~ exper + expersq + black + south | educ | nearc4 + nearc2, data = card, vcov = "robust" ) diagnostics(fit)
Returns a named list of ivreg2_first_stage objects, one per endogenous
variable. Each ivreg2_first_stage object supports the following
methods:
first_stage(x, ...) ## S3 method for class 'ivreg2' first_stage(x, ...)first_stage(x, ...) ## S3 method for class 'ivreg2' first_stage(x, ...)
x |
A fitted model object. |
... |
Additional arguments (ignored). |
coef()First-stage coefficient vector.
vcov()First-stage variance-covariance matrix.
residuals()First-stage residuals.
fitted()First-stage fitted values.
nobs()Number of observations used in the first stage.
confint()Confidence intervals for the first-stage coefficients.
print()Compact one-line-per-coefficient display.
summary()Full first-stage regression table: coefficients,
standard errors, t-values, p-values, the first-stage F-statistic, and
the partial R-squared (its print() method renders the table).
tidy()Broom-style tibble with one row per coefficient
(term, estimate, std.error, statistic, p.value, and,
optionally, confidence limits).
glance()Broom-style one-row tibble of first-stage fit statistics (sigma, degrees of freedom, F-statistic, partial R-squared, and related diagnostics).
A named list of ivreg2_first_stage objects.
the first-stage F-statistic (surfaced
via glance() and summary() on each ivreg2_first_stage object)
always uses small-sample degrees of freedom, regardless of the main
model's small argument. This matches Stata's ivreg2. See
ivreg2r-conventions for the full statement of which corrections
small controls.
Other ivreg2 methods:
coef.ivreg2(),
confint.ivreg2(),
diagnostics(),
fitted.ivreg2(),
formula.ivreg2(),
ivreg2(),
model.matrix.ivreg2(),
nobs.ivreg2(),
predict.ivreg2(),
print.ivreg2(),
print.summary.ivreg2(),
residuals.ivreg2(),
summary.ivreg2(),
terms.ivreg2(),
update.ivreg2(),
vcov.ivreg2()
# Mirrors the Stata `ivreg2` help-file example at line 1325, which # demonstrates the equivalence of the Kleibergen-Paap rk Wald F and the # first-stage F with a single endogenous regressor (and, in passing, # the `savefirst` option that `first_stage = TRUE` corresponds to). data(mroz) mroz_work <- subset(mroz, inlf == 1) fit <- ivreg2(lwage ~ exper + expersq | educ | age + kidslt6 + kidsge6, data = mroz_work, vcov = "robust", first_stage = TRUE) fs <- first_stage(fit) coef(fs$educ) summary(fs$educ) # KP rk Wald F = the robust first-stage F (single endogenous regressor) c(kp_rk_wald_F = fit$diagnostics$weak_id_robust$stat, first_stage_F = glance(fs$educ)$f_stat)# Mirrors the Stata `ivreg2` help-file example at line 1325, which # demonstrates the equivalence of the Kleibergen-Paap rk Wald F and the # first-stage F with a single endogenous regressor (and, in passing, # the `savefirst` option that `first_stage = TRUE` corresponds to). data(mroz) mroz_work <- subset(mroz, inlf == 1) fit <- ivreg2(lwage ~ exper + expersq | educ | age + kidslt6 + kidsge6, data = mroz_work, vcov = "robust", first_stage = TRUE) fs <- first_stage(fit) coef(fs$educ) summary(fs$educ) # KP rk Wald F = the robust first-stage F (single endogenous regressor) c(kp_rk_wald_F = fit$diagnostics$weak_id_robust$stat, first_stage_F = glance(fs$educ)$f_stat)
Respects na.action: when the model was fit with na.exclude,
NAs are reinserted at the omitted row positions so the result
aligns with the original data frame (matching base R's fitted.lm).
## S3 method for class 'ivreg2' fitted(object, ...)## S3 method for class 'ivreg2' fitted(object, ...)
object |
An object of class |
... |
Additional arguments (ignored). |
Numeric vector of fitted values.
Other ivreg2 methods:
coef.ivreg2(),
confint.ivreg2(),
diagnostics(),
first_stage(),
formula.ivreg2(),
ivreg2(),
model.matrix.ivreg2(),
nobs.ivreg2(),
predict.ivreg2(),
print.ivreg2(),
print.summary.ivreg2(),
residuals.ivreg2(),
summary.ivreg2(),
terms.ivreg2(),
update.ivreg2(),
vcov.ivreg2()
Extract formula from an ivreg2 object
## S3 method for class 'ivreg2' formula(x, ...)## S3 method for class 'ivreg2' formula(x, ...)
x |
An object of class |
... |
Additional arguments passed to |
The original model formula.
Other ivreg2 methods:
coef.ivreg2(),
confint.ivreg2(),
diagnostics(),
first_stage(),
fitted.ivreg2(),
ivreg2(),
model.matrix.ivreg2(),
nobs.ivreg2(),
predict.ivreg2(),
print.ivreg2(),
print.summary.ivreg2(),
residuals.ivreg2(),
summary.ivreg2(),
terms.ivreg2(),
update.ivreg2(),
vcov.ivreg2()
Returns a single-row tibble of model-level summary statistics and the headline IV diagnostics. The column set is deliberately compact so that table tools such as modelsummary render a sensible default.
## S3 method for class 'ivreg2' glance(x, diagnostics = TRUE, ...)## S3 method for class 'ivreg2' glance(x, diagnostics = TRUE, ...)
x |
An object of class |
diagnostics |
Logical: include the headline IV diagnostic columns?
Default |
... |
Additional arguments (ignored). |
glance() returns a fixed set of columns for a given value of
diagnostics, using NA for metrics that do not apply to the
fitted model. All diagnostic columns are NA for OLS models
(single-part formula). overid_stat and overid_p are also
NA when the model is exactly identified (the number of excluded
instruments equals the number of endogenous regressors), and
weak_id_robust_stat is NA under vcov = "iid" (the
Cragg-Donald F in weak_id_stat is reported instead of the
Kleibergen-Paap F).
Set diagnostics = FALSE for a compact goodness-of-fit summary
without the IV test columns.
For the full set of computed tests — including Stock-Yogo critical values,
Anderson-Rubin, Stock-Wright, endogeneity, orthogonality, and redundancy —
beyond these six headline columns, see diagnostics().
A single-row tibble::tibble().
Always present (9 columns): r.squared, adj.r.squared, sigma,
statistic (model F or Wald chi-squared), p.value, df (model
numerator degrees of freedom), df.residual, nobs, vcov_type.
When diagnostics = TRUE (default, 6 additional columns): the
headline IV specification tests — weak_id_stat (Cragg-Donald Wald F),
weak_id_robust_stat (Kleibergen-Paap rk Wald F), underid_stat and
underid_p (underidentification), overid_stat and overid_p
(Sargan/Hansen J overidentification).
The remaining stored quantities and configuration flags are not in
glance() — this keeps the goodness-of-fit block usable in rendered
tables. They remain available as named elements on the fitted object: the
estimation method, lambda/kclass_value/fuller_parameter, coviv,
center, psd, kernel/bw, kiefer, dkraay, sw, cluster counts,
cue_convergence, partial_ct, small, the cross-products yy/yyc,
ranks and condition numbers (rank, rankzz, condxx, condzz), the
log-likelihood ll, and the full diagnostic list x$diagnostics
(endogeneity, orthogonality, redundancy, Anderson-Rubin, Stock-Wright,
and the Cragg-Donald/Kleibergen-Paap eigenvalues).
Other broom methods:
augment.ivreg2(),
tidy.ivreg2()
data(mroz) mroz_work <- subset(mroz, inlf == 1) fit <- ivreg2(lwage ~ exper + expersq | educ | age + kidslt6 + kidsge6, data = mroz_work, vcov = "robust") # Full output with diagnostics glance(fit) # Compact output without diagnostics glance(fit, diagnostics = FALSE) # Extract specific diagnostics glance(fit)[, c("overid_stat", "overid_p")] glance(fit)[, c("weak_id_stat", "weak_id_robust_stat")] # Diagnostics dropped from glance() remain on the fitted object fit$diagnostics$endogeneity # Compare Sargan (IID) vs Hansen J (robust) fit_iid <- ivreg2(lwage ~ exper + expersq | educ | age + kidslt6 + kidsge6, data = mroz_work) data.frame( vcov = c("iid", "robust"), overid = c(glance(fit_iid)$overid_stat, glance(fit)$overid_stat), overid_p = c(glance(fit_iid)$overid_p, glance(fit)$overid_p) ) # A compact modelsummary table built from the curated glance() columns if (requireNamespace("modelsummary", quietly = TRUE)) { modelsummary::modelsummary( list("2SLS" = fit), statistic = "std.error", gof_map = c("nobs", "r.squared", "weak_id_stat", "overid_stat") ) }data(mroz) mroz_work <- subset(mroz, inlf == 1) fit <- ivreg2(lwage ~ exper + expersq | educ | age + kidslt6 + kidsge6, data = mroz_work, vcov = "robust") # Full output with diagnostics glance(fit) # Compact output without diagnostics glance(fit, diagnostics = FALSE) # Extract specific diagnostics glance(fit)[, c("overid_stat", "overid_p")] glance(fit)[, c("weak_id_stat", "weak_id_robust_stat")] # Diagnostics dropped from glance() remain on the fitted object fit$diagnostics$endogeneity # Compare Sargan (IID) vs Hansen J (robust) fit_iid <- ivreg2(lwage ~ exper + expersq | educ | age + kidslt6 + kidsge6, data = mroz_work) data.frame( vcov = c("iid", "robust"), overid = c(glance(fit_iid)$overid_stat, glance(fit)$overid_stat), overid_p = c(glance(fit_iid)$overid_p, glance(fit)$overid_p) ) # A compact modelsummary table built from the curated glance() columns if (requireNamespace("modelsummary", quietly = TRUE)) { modelsummary::modelsummary( list("2SLS" = fit), statistic = "std.error", gof_map = c("nobs", "r.squared", "weak_id_stat", "overid_stat") ) }
Wages and characteristics of young men from the National Longitudinal Survey (NLS), originally analyzed in Griliches (1976). This dataset is a standard IV example used in Hayashi (2000, Ch. 3) and Baum, Schaffer & Stillman (2007, pp. 492–494) to illustrate weak identification tests, Anderson–Rubin inference, Stock–Wright S statistics, and instrument redundancy.
grilichesgriliches
A data frame with 758 observations and 20 variables:
Residency in the South (1 = yes).
Residency in the South in 1980.
Marital status (1 = married).
Marital status in 1980.
Resides in metropolitan area (1 = urban).
Resides in metropolitan area in 1980.
Mother's education (years).
IQ score.
Score on Knowledge of the World of Work test.
Survey year (66–73 or 80).
Age at survey.
Age in 1980.
Completed years of schooling.
Completed years of schooling in 1980.
Work experience (years).
Work experience in 1980 (years).
Job tenure (years).
Job tenure in 1980 (years).
Log wage.
Log wage in 1980.
Two cross-sections are pooled (survey years 66–73 and 80). The Baum,
Schaffer & Stillman (2007) examples use year dummies via
factor(year).
Griliches, Z. (1976). Wages of very young men. Journal of Political Economy, 84(4), S69–S85.
Downloaded from http://fmwww.bc.edu/ec-p/data/hayashi/griliches76.dta.
Redistribution basis: system.file("COPYRIGHTS", package = "ivreg2r").
Hayashi, F. (2000). Econometrics. Princeton University Press. (Chapter 3, p. 255.)
Baum, C.F., Schaffer, M.E. and Stillman, S. (2007). Enhanced routines for instrumental variables/generalized method of moments estimation and testing. The Stata Journal, 7(4), 465–506. (pp. 492–494.)
Other ivreg2r datasets:
abdata,
card,
cigar,
grunfeld,
klein,
mroz,
nlswork,
phillips,
stockwatson,
wagepan
data(griliches) # Baum, Schaffer & Stillman (2007), p. 493: IV with robust SEs, weak-ID # diagnostics, redundancy test fit <- ivreg2(lw ~ s + expr + tenure + rns + smsa + factor(year) | iq | age + mrt, data = griliches, vcov = "robust", redundant = "mrt") summary(fit)data(griliches) # Baum, Schaffer & Stillman (2007), p. 493: IV with robust SEs, weak-ID # diagnostics, redundancy test fit <- ivreg2(lw ~ s + expr + tenure + rns + smsa + factor(year) | iq | age + mrt, data = griliches, vcov = "robust", redundant = "mrt") summary(fit)
Corporate investment, market value, and capital stock for 10 large U.S. firms observed annually over 1935–1954: a balanced panel of 10 firms times 20 years (200 observations). Grunfeld, Y. (1958). The Determinants of Corporate Investment. PhD dissertation, University of Chicago. See Kleiber, C. and Zeileis, A. (2010) for the definitive account of the dataset's provenance and its many circulating variants.
grunfeldgrunfeld
A data frame with 200 observations and 6 variables (10 firms times 20 years, 1935–1954):
Firm identifier (1–10). Use as ivar.
Calendar year (1935–1954). The time variable: use as
tvar.
Gross investment, current year.
Market value of the firm, prior year.
Capital stock, prior year.
Time index (1–20), a linear trend.
Grunfeld, Y. (1958). The Determinants of Corporate Investment. PhD dissertation, University of Chicago.
Kleiber, C. and Zeileis, A. (2010). The Grunfeld data at 50. German Economic Review, 11(4), 404–417.
Distributed via Stata's webuse grunfeld.
Redistribution basis: system.file("COPYRIGHTS", package = "ivreg2r").
Other ivreg2r datasets:
abdata,
card,
cigar,
griliches,
klein,
mroz,
nlswork,
phillips,
stockwatson,
wagepan
data(grunfeld) # ivreg2 help file line 1595: Driscoll-Kraay standard errors (bw = 2), # small-sample correction fit <- ivreg2( invest ~ mvalue + kstock, data = grunfeld, dkraay = 2, small = TRUE, tvar = "year", ivar = "company" ) summary(fit)data(grunfeld) # ivreg2 help file line 1595: Driscoll-Kraay standard errors (bw = 2), # small-sample correction fit <- ivreg2( invest ~ mvalue + kstock, data = grunfeld, dkraay = 2, small = TRUE, tvar = "year", ivar = "company" ) summary(fit)
Estimate models by OLS, two-stage least squares (2SLS), LIML, Fuller, or
k-class with automatic diagnostic tests. Uses a three-part formula for IV:
y ~ exog | endo | instruments.
ivreg2( formula, data, weights, subset, na.action = stats::na.omit, vcov = "iid", clusters = NULL, endog = NULL, orthog = NULL, redundant = NULL, method = "2sls", kclass = NULL, fuller = 0, coviv = FALSE, small = FALSE, dofminus = 0L, sdofminus = 0L, weight_type = "aweight", kernel = NULL, bw = NULL, tvar = NULL, ivar = NULL, kiefer = FALSE, dkraay = NULL, wmatrix = NULL, smatrix = NULL, b0 = NULL, noid = FALSE, partial = NULL, nopartialsmall = FALSE, center = FALSE, psd = NULL, sw = FALSE, reduced_form = "none", first_stage = FALSE, model = TRUE, x = FALSE, y = TRUE )ivreg2( formula, data, weights, subset, na.action = stats::na.omit, vcov = "iid", clusters = NULL, endog = NULL, orthog = NULL, redundant = NULL, method = "2sls", kclass = NULL, fuller = 0, coviv = FALSE, small = FALSE, dofminus = 0L, sdofminus = 0L, weight_type = "aweight", kernel = NULL, bw = NULL, tvar = NULL, ivar = NULL, kiefer = FALSE, dkraay = NULL, wmatrix = NULL, smatrix = NULL, b0 = NULL, noid = FALSE, partial = NULL, nopartialsmall = FALSE, center = FALSE, psd = NULL, sw = FALSE, reduced_form = "none", first_stage = FALSE, model = TRUE, x = FALSE, y = TRUE )
formula |
A formula: |
data |
A data frame containing the variables in the formula. |
weights |
Optional analytic weights expression (evaluated in |
subset |
Optional subset expression (evaluated in |
na.action |
Function for handling |
vcov |
Character: covariance type. One of |
clusters |
One-sided formula specifying one or two cluster variables
(e.g. |
endog |
Character vector of endogenous regressor names to test for
exogeneity (endogeneity test / C-statistic). If Note: Unlike Stata's |
orthog |
Character vector of instrument names to test for
orthogonality (instrument-subset C-statistic). Names must be included
or excluded instruments (not endogenous regressors or the intercept).
If |
redundant |
Character vector of excluded instrument names to test
for redundancy (zero first-stage explanatory power). The test is a
KP rk LM test of H0: rank=0 on the first-stage coefficient matrix
for the tested instruments, conditional on maintained instruments.
If |
method |
Character: estimation method. One of CUE optimizer note: This package uses R's |
kclass |
Numeric scalar: user-supplied k value for k-class
estimation. When supplied, |
fuller |
Numeric scalar: Fuller (1977) modification parameter.
Non-negative. |
coviv |
Logical: if |
small |
Logical: if |
dofminus |
Non-negative integer: large-sample degrees-of-freedom
adjustment. Subtracted from N in large-sample variance formulas
(e.g., sigma = rss/(N-dofminus)). Useful when fixed effects have been
partialled out. Equivalent to Stata's |
sdofminus |
Non-negative integer: small-sample degrees-of-freedom
adjustment. Subtracted from the residual degrees of freedom alongside K
(e.g., df.residual = N - K - dofminus - sdofminus). Useful when
partialling out regressors. Equivalent to Stata's |
weight_type |
Character: type of weights. One of aweight: Normalized to sum to N. Standard for WLS. fweight: Integer-valued; N is redefined as pweight: Normalized to sum to N. Forces robust VCE, with a warning
(overrides iweight: Not normalized; N is redefined as |
kernel |
Character: kernel function for HAC/AC standard errors.
One of Note: Kleibergen-Paap identification tests (underidentification and
weak identification) always use the Bartlett kernel internally, regardless
of the user-specified kernel. This matches a known behavior in Stata's
|
bw |
Numeric or |
tvar |
Character: name of the time variable in |
ivar |
Character: name of the panel identifier variable in |
kiefer |
Logical: if |
dkraay |
Positive numeric scalar: bandwidth for Driscoll-Kraay (1998)
VCE. When specified, clusters on the time variable and applies kernel
smoothing across time lags, producing standard errors robust to
cross-sectional dependence. Requires panel data ( |
wmatrix |
Numeric matrix: user-supplied L x L weighting matrix for
GMM estimation, where L is the number of instruments (including exogenous
regressors). When supplied without |
smatrix |
Numeric matrix: user-supplied L x L moment covariance matrix
for GMM estimation. When supplied, the GMM estimation uses this matrix
instead of computing Omega from residuals. Implies efficient GMM
( |
b0 |
Numeric vector: evaluate the CUE objective at this fixed
parameter vector without optimization. When supplied, |
noid |
Logical: if |
partial |
Character vector: exogenous regressors to partial out via Frisch-Waugh-Lovell projection before estimation. Coefficients on partialled variables are not recoverable and are not reported. Special values:
By default, Note: FWL invariance holds for OLS, 2SLS, LIML, and two-step GMM, but
not for CUE. The CUE objective recomputes the moment covariance at each
iteration, so partialled residuals produce a different optimization surface.
A warning is issued when After partialling, Equivalent to Stata's |
nopartialsmall |
Logical: if |
center |
Logical: if Note: Centering is applied to the main model's VCE and to
diagnostic tests that use the main model's S matrix (overidentification,
orthogonality). However, the endogeneity test ( The Kleibergen-Paap identification statistics (underidentification,
weak identification) and the instrument redundancy test are likewise
always computed without centering, regardless of When a user-supplied |
psd |
Character or NULL: PSD correction for the moment covariance
matrix S. Under an exactly-singular |
sw |
Logical: if Precondition: the Stock-Watson (2008) correction is derived for a
within-transformed (fixed-effects) panel regression with fixed |
reduced_form |
Character: what reduced-form output to store.
Note: the reduced-form variance-covariance matrix always applies
OLS-style small-sample degrees-of-freedom scaling, regardless of the
main model's |
first_stage |
Logical: if |
model |
Logical: if |
x |
Logical: if |
y |
Logical: if |
An object of class "ivreg2". Beyond the usual components
(coefficients, residuals, vcov, diagnostics, ...), the object
stores the estimated moment-condition covariance matrix as $S and the
GMM weighting matrix as $W, corresponding to Stata's e(S) and
e(W):
$S is present for every fit. Normalization matches Stata's
m_omega: iid sigma^2 (Z'Z)/N with sigma^2 = RSS/(N - dofminus);
robust and HAC, meat divided by N - dofminus; cluster, meat divided
by N; psd-corrected when psd is set; built from centered moments
when center = TRUE. A user-supplied smatrix is echoed, never
recomputed and never psd-corrected.
$W is NULL for method = "liml" and "kclass" (as in Stata, no
weighting matrix is defined for k-class estimators). For two-step
GMM, CUE, and b0 fits it is the inverse of the defining $S; for
one-step OLS/2SLS it is (1/sigma^2) (Z'Z/N)^{-1}; a user-supplied
wmatrix is echoed (it is the first-step weighting matrix under
method = "gmm2s").
Rows and columns are named by the R instrument columns — (Intercept)
rather than Stata's _cons, and R column order (exogenous regressors
before excluded instruments) rather than Stata's. Passing fit$S back
via smatrix reproduces the corresponding efficient-GMM fit, mirroring
the e(S) reuse workflow in Stata's ivreg2 help file.
When the model carries more instruments than regressors, ivreg2()
automatically reports an overidentification test: the Sargan (1958)
statistic under vcov = "iid", and the Hansen J statistic under robust,
cluster, or HAC errors. The test evaluates the L - K overidentifying
restrictions jointly, where L is the number of instruments and K the
number of regressors. A rejection indicates that at least one instrument
violates its orthogonality condition, without identifying which one. A
non-rejection is necessary but not sufficient for instrument validity.
The test has no power against a bias shared by every instrument, so
orthogonality conditions that fail in the same direction can still appear
jointly satisfied. The test is also uninformative about the K
exactly-identifying moment conditions, whose validity must be defended on
substantive grounds. An exactly identified model has no overidentifying
restrictions, and therefore no overidentification test.
The endogeneity test, also called the C-statistic or difference test,
asks whether regressors treated as endogenous could instead be treated
as exogenous. It is the overidentification statistic of the model that
adds the suspect regressors to the instrument set, treating them as
exogenous, minus that of the model that treats them as endogenous. Under
the null of exogeneity, this difference follows a chi-square distribution
with degrees of freedom equal to the number of regressors tested. Both
overidentification statistics are formed from the same estimated moment
covariance, which guarantees that the difference is non-negative
(Hayashi 2000).
ivreg2() computes this test automatically for every IV model, whereas
Stata computes it only when the endog() option is given explicitly.
The endog argument selects which endogenous regressors are tested. The
statistic takes the difference-in-Sargan form under iid errors and the
difference-in-Hansen-J form under robust, cluster, or HAC errors.
LIML, Fuller's modification, and the general k-class estimators are
alternatives to 2SLS motivated by weak instruments. LIML is approximately
median-unbiased, and its Stock-Yogo weak-identification thresholds are
more forgiving than those for 2SLS. LIML has no finite-sample moments of
any order, however. Its sampling distribution can therefore be dispersed,
and individual estimates can lie far from the truth. Fuller's (1977)
modification sets k = lambda - fuller / (N - L), which yields an
estimator with finite moments. The choice fuller = 1 is approximately
best-unbiased, and fuller = 4 minimizes mean squared error, both within
the standard weak-instrument framework. Weak-identification pretesting for
LIML and Fuller uses estimator-specific critical values rather than the
2SLS values. LIML coincides with 2SLS when the model is exactly
identified, because the LIML eigenvalue equals one in that case. Fuller
does not, since it subtracts fuller / (N - L) from that eigenvalue.
ivreg2r-conventions for the statistical conventions (sigma
normalization, small, weights, degrees of freedom) and how they differ
from lm(); ivreg2r-glossary for the diagnostic-output acronyms;
summary.ivreg2() and print.ivreg2() for console output;
tidy.ivreg2(), glance.ivreg2(), and augment.ivreg2() for
broom-style output; first_stage() for first-stage regressions.
The vignettes vignette("introduction", "ivreg2r"),
vignette("advanced-iv", "ivreg2r"), and
vignette("time-series-gmm", "ivreg2r") work through applied examples.
Other ivreg2 methods:
coef.ivreg2(),
confint.ivreg2(),
diagnostics(),
first_stage(),
fitted.ivreg2(),
formula.ivreg2(),
model.matrix.ivreg2(),
nobs.ivreg2(),
predict.ivreg2(),
print.ivreg2(),
print.summary.ivreg2(),
residuals.ivreg2(),
summary.ivreg2(),
terms.ivreg2(),
update.ivreg2(),
vcov.ivreg2()
data(mroz) mroz_work <- subset(mroz, inlf == 1) # --- Just-identified IV: return to schooling --- # Wooldridge (2020), Example 15.1: father's education instruments # education in a simple wage equation (replicates the published # estimates: educ = 0.059, SE = 0.035). With one instrument for one # endogenous variable, no overid test is possible; instrument validity # must be defended on substantive grounds. fit <- ivreg2(lwage ~ 1 | educ | fatheduc, data = mroz_work) summary(fit) # --- Overidentified IV: testing instrument validity --- # The Stata ivreg2 help file's illustrative baseline (line 1274): # age, kidslt6, and kidsge6 give two overidentifying restrictions, # so the Sargan test can detect misspecification. Note its weak # first stage (Cragg-Donald F ~ 4.3) -- see the LIML example below. fit_overid <- ivreg2(lwage ~ exper + expersq | educ | age + kidslt6 + kidsge6, data = mroz_work) summary(fit_overid) # --- Robust standard errors --- # With heteroskedasticity, Kleibergen-Paap diagnostics replace # Anderson/Cragg-Donald, and Hansen J replaces Sargan. fit_robust <- ivreg2(lwage ~ exper + expersq | educ | age + kidslt6 + kidsge6, data = mroz_work, vcov = "robust") summary(fit_robust) # --- LIML --- # Same baseline as above (a documented variation on the help-file # spec). Its weak first stage (Cragg-Donald F ~ 4.3) is the setting # where 2SLS bias toward OLS grows with the overidentification degree # relative to instrument strength, and LIML's approximate # median-unbiasedness -- established within the iid Stock-Yogo # framework -- is attractive. LIML equals 2SLS when just-identified. fit_liml <- ivreg2(lwage ~ exper + expersq | educ | age + kidslt6 + kidsge6, data = mroz_work, method = "liml") summary(fit_liml) # --- Endogeneity test --- # Is education actually endogenous? The C-statistic tests # H0: OLS is consistent (educ is exogenous). # ivreg2 help file line 1283: the endog(educ) example on this equation. fit_endog <- ivreg2(lwage ~ exper + expersq | educ | age + kidslt6 + kidsge6, data = mroz_work, endog = "educ") if (requireNamespace("dplyr", quietly = TRUE)) { diagnostics(fit_endog) |> dplyr::filter(test == "endogeneity") } # --- Clustering --- # Griliches (1976) wage equation, cluster on year. # Adapted from Stata `ivreg2` help-file example (line 1250): the help # command also includes year dummies (xi i.year), omitted here, and no # small option. Either way the fit warns -- 7 year clusters < the # instrument count makes the moment covariance singular, which is the # help file's own lead-in to partialling; see # vignette("time-series-gmm"). data(griliches) fit_cl <- ivreg2(lw ~ s + expr + tenure + rns + smsa | iq | med + kww + age, data = griliches, clusters = ~year, small = TRUE) summary(fit_cl) # --- Two-step efficient GMM --- # ivreg2 help file line 1154: efficient GMM with robust weighting. # The optimal weighting matrix uses the first-step robust moment # covariance; Hansen J replaces Sargan. fit_gmm <- ivreg2(lw ~ s + expr + tenure + rns + smsa + factor(year) | iq | med + kww + age + mrt, data = griliches, method = "gmm2s", vcov = "robust") summary(fit_gmm)data(mroz) mroz_work <- subset(mroz, inlf == 1) # --- Just-identified IV: return to schooling --- # Wooldridge (2020), Example 15.1: father's education instruments # education in a simple wage equation (replicates the published # estimates: educ = 0.059, SE = 0.035). With one instrument for one # endogenous variable, no overid test is possible; instrument validity # must be defended on substantive grounds. fit <- ivreg2(lwage ~ 1 | educ | fatheduc, data = mroz_work) summary(fit) # --- Overidentified IV: testing instrument validity --- # The Stata ivreg2 help file's illustrative baseline (line 1274): # age, kidslt6, and kidsge6 give two overidentifying restrictions, # so the Sargan test can detect misspecification. Note its weak # first stage (Cragg-Donald F ~ 4.3) -- see the LIML example below. fit_overid <- ivreg2(lwage ~ exper + expersq | educ | age + kidslt6 + kidsge6, data = mroz_work) summary(fit_overid) # --- Robust standard errors --- # With heteroskedasticity, Kleibergen-Paap diagnostics replace # Anderson/Cragg-Donald, and Hansen J replaces Sargan. fit_robust <- ivreg2(lwage ~ exper + expersq | educ | age + kidslt6 + kidsge6, data = mroz_work, vcov = "robust") summary(fit_robust) # --- LIML --- # Same baseline as above (a documented variation on the help-file # spec). Its weak first stage (Cragg-Donald F ~ 4.3) is the setting # where 2SLS bias toward OLS grows with the overidentification degree # relative to instrument strength, and LIML's approximate # median-unbiasedness -- established within the iid Stock-Yogo # framework -- is attractive. LIML equals 2SLS when just-identified. fit_liml <- ivreg2(lwage ~ exper + expersq | educ | age + kidslt6 + kidsge6, data = mroz_work, method = "liml") summary(fit_liml) # --- Endogeneity test --- # Is education actually endogenous? The C-statistic tests # H0: OLS is consistent (educ is exogenous). # ivreg2 help file line 1283: the endog(educ) example on this equation. fit_endog <- ivreg2(lwage ~ exper + expersq | educ | age + kidslt6 + kidsge6, data = mroz_work, endog = "educ") if (requireNamespace("dplyr", quietly = TRUE)) { diagnostics(fit_endog) |> dplyr::filter(test == "endogeneity") } # --- Clustering --- # Griliches (1976) wage equation, cluster on year. # Adapted from Stata `ivreg2` help-file example (line 1250): the help # command also includes year dummies (xi i.year), omitted here, and no # small option. Either way the fit warns -- 7 year clusters < the # instrument count makes the moment covariance singular, which is the # help file's own lead-in to partialling; see # vignette("time-series-gmm"). data(griliches) fit_cl <- ivreg2(lw ~ s + expr + tenure + rns + smsa | iq | med + kww + age, data = griliches, clusters = ~year, small = TRUE) summary(fit_cl) # --- Two-step efficient GMM --- # ivreg2 help file line 1154: efficient GMM with robust weighting. # The optimal weighting matrix uses the first-step robust moment # covariance; Hansen J replaces Sargan. fit_gmm <- ivreg2(lw ~ s + expr + tenure + rns + smsa + factor(year) | iq | med + kww + age + mrt, data = griliches, method = "gmm2s", vcov = "robust") summary(fit_gmm)
ivreg2r is a translation of Stata's ivreg2, and it follows Stata's
statistical conventions rather than those of R's lm()/vcov() ecosystem.
This topic collects those conventions in one place. The API itself is
idiomatic R (formula interface, tidyverse-friendly output); only the
statistical choices below lean on Stata. See ivreg2() for the
estimation function and ivreg2r-glossary for the diagnostic acronyms
printed by summary().
vcov defaults to "iid" (classical) and small defaults to FALSE,
matching Stata's ivreg2 defaults. With small = FALSE, inference uses
z and chi-squared statistics and the large-sample variance normalization.
Set small = TRUE for t and F statistics and the finite-sample N - K
correction, matching Stata's small option. small is the single, uniform
control for finite-sample corrections across every VCE type ("iid",
"robust", "HAC", "AC"); it is not a VCE selector. There are no
"HC0"/"HC1" values — use vcov = "robust" and toggle small.
Three statistics sit outside that uniform control, all matching Stata:
the first-stage F statistics (first_stage()) always use small-sample
degrees of freedom regardless of small; the overidentification
(Sargan/Hansen J) and endogeneity (C-statistic) tests are never
small-sample corrected, even when small = TRUE; and the stored
reduced-form variance-covariance matrix (reduced_form) always applies
OLS-style small-sample scaling regardless of the main model's small.
Under small = FALSE, . Under
small = TRUE, . This
differs from lm(), which always divides the residual sum of squares by its
residual degrees of freedom. Because ivreg2r reports the large-sample sigma
by default, its RMSE and any quantity built from sigma differ from lm()
unless small = TRUE.
Coefficients match lm() for OLS. Standard errors and the full
variance-covariance matrix match lm() only when small = TRUE; the
default small = FALSE reports Stata-convention standard errors without the
N - K finite-sample correction. Under analytic ("aweight") or
probability ("pweight") weights, sigma additionally differs from
lm(..., weights = w) by a factor of sqrt(N / sum(w)), because lm()
uses raw (unnormalized) weights while ivreg2r normalizes them (see below).
Analytic and probability weights are normalized internally to sum to N,
following Stata. This makes sigma scale-invariant for those types:
multiplying every weight by a constant leaves all coefficients, standard
errors, and test statistics unchanged. Frequency ("fweight") and
importance ("iweight") weights are not normalized; they redefine N as
sum(weights), so their scale is meaningful by construction. Probability
weights force a robust VCE. See the weight_type argument of ivreg2().
dofminus is a large-sample adjustment subtracted from N in large-sample
variance formulas (for example when fixed effects have been partialled out
upstream). sdofminus is a small-sample adjustment subtracted from the
residual degrees of freedom alongside K (for example the count of
regressors removed by partial). Both mirror Stata's dofminus() and
sdofminus() options. Stata's own source labels dofminus a large-sample
adjustment (e.g. number of fixed effects) and sdofminus a small-sample one
(e.g. number of partialled-out regressors).
confint() and the model Wald test use the standard normal and chi-squared
distributions when small = FALSE, and the t and F distributions when
small = TRUE. The reported model test is therefore a chi-squared Wald
statistic by default and an F statistic under small = TRUE.
ivreg2() for the estimation function and the full argument list;
ivreg2r-glossary for the diagnostic-output acronyms.
Other ivreg2r reference:
ivreg2r-glossary
summary() and print() report a battery of identification, weak-instrument,
and overidentification diagnostics, many named by acronym. This topic glosses
every acronym that reaches the console. The underlying statistics are stored
on the fitted object under fit$diagnostics; the headline ones are also in
glance().
Tests whether the excluded instruments
have rank high enough to identify the endogenous regressors. Reported as
the Anderson (1951) canonical-correlations LM statistic under
vcov = "iid", and the Kleibergen-Paap rk LM statistic under robust,
cluster, or HAC errors.
Gauges instrument strength against the
Stock-Yogo (2005) critical values. Reported as the Cragg-Donald (1993)
Wald F under vcov = "iid", and the Kleibergen-Paap rk Wald F under
robust, cluster, or HAC errors.
The iid weak-identification Wald F (and the underlying eigenvalue statistic); see "Weak identification test".
Rank-based LM and Wald statistics that replace the Anderson and Cragg-Donald statistics when errors are not iid.
A weak-instrument-robust test of the joint significance of the endogenous regressors: valid regardless of instrument strength.
A weak-instrument-robust statistic for the same hypothesis, the score (LM) counterpart of the Anderson-Rubin Wald test. It is distinct from the Hansen J overidentification statistic: S constrains the endogenous coefficients to zero and has degrees of freedom equal to the number of excluded instruments.
A partial R-squared for the first stage that accounts for correlation among instruments; the relevant measure with more than one endogenous regressor.
A conditional first-stage F statistic for the identification of an individual endogenous regressor, given the others.
A conditional first-stage F (or chi-squared, depending on the VCE) for an individual endogenous regressor.
The overidentification test: Sargan (1958) under
vcov = "iid", and the Hansen J statistic under robust, cluster, or HAC
errors. Tests the joint validity of the overidentifying restrictions.
A difference-of-J statistic used for the
endogeneity test (endog), the orthogonality test (orthog), and the
redundancy test (redundant).
The Kiefer (1980) VCE: autocorrelation-consistent with a Truncated kernel at bandwidth equal to the full time span.
The Driscoll-Kraay (1998) panel VCE, robust to cross-sectional dependence.
Large- and small-sample degrees-of-freedom adjustments; see ivreg2r-conventions.
Positive-semidefinite corrections for the moment
covariance matrix, zeroing (psd0) or taking the absolute value of
(psda) any negative eigenvalues.
The "covariance at the IV estimates" variance matrix for LIML and k-class estimators, robust to misspecification of the LIML model.
Cragg's (1983) heteroskedastic OLS estimator, obtained from a
no-endogenous-regressor model under method = "gmm2s" with a robust VCE.
The family of IV estimators indexed by a scalar k (2SLS at k = 1, OLS at k = 0, LIML at k equal to the LIML eigenvalue).
summary.ivreg2() for the console output; ivreg2r-conventions
for the statistical conventions; ivreg2() for the arguments that request
each test.
Other ivreg2r reference:
ivreg2r-conventions
Annual U.S. national-accounts aggregates for 1920–1941, from Klein's Model I of the U.S. economy: consumption, profits, wages, investment, capital stock, government spending, and taxes. Klein, L.R. (1950). Economic Fluctuations in the United States, 1921–1941. Cowles Commission Monograph No. 11. Wiley.
kleinklein
A data frame with 22 observations and 12 variables:
Calendar year (1920–1941). The time variable: use as
tvar with l()/d().
Consumption.
Private profits.
Private wage bill.
Investment.
Lagged value of capital stock (a primitive; no contemporaneous capital column exists to derive it from).
Total income/demand.
Government wage bill.
Government spending.
Indirect business taxes plus net exports.
Total U.S. wage bill.
Calendar year minus 1931 (a linear trend, -11 to 10),
used as an instrument – not the time variable (see yr).
Two columns both encode "year" – do not confuse them.
yr is the calendar year (1920–1941) and is the time variable to
pass as tvar when using the time-series operators l() /
d(). year is calendar year minus 1931 (a linear trend
ranging from -11 to 10) and is used as an instrument (a trend
term) in the help-file examples below – it is not a second copy of the
time index.
The upstream Stata dataset (webuse klein) also ships two
precomputed one-period lags, profits1 (= L.profits) and
totinc1 (= L.totinc). Those columns are deliberately
dropped here: this package's l() time-series operator computes
the same lags directly from profits and totinc given
tvar = "yr", so shipping precomputed lag columns would be
redundant and could drift out of sync with l(). capital1
(the lagged capital stock) is kept because it is a primitive in this
dataset – there is no contemporaneous capital column to lag it
from – and it appears directly in the instrument lists below.
Klein, L.R. (1950). Economic Fluctuations in the United States, 1921–1941. Cowles Commission Monograph No. 11. New York: Wiley.
Distributed via Stata's webuse klein.
Redistribution basis: system.file("COPYRIGHTS", package = "ivreg2r").
Other ivreg2r datasets:
abdata,
card,
cigar,
griliches,
grunfeld,
mroz,
nlswork,
phillips,
stockwatson,
wagepan
data(klein) # ivreg2 help file line 1462: LIML, consumption on lagged profits, with # profits and wagetot treated as endogenous fit <- ivreg2( consump ~ l(profits, 1) | profits + wagetot | govt + taxnetx + year + wagegovt + capital1 + l(totinc, 1), data = klein, tvar = "yr", method = "liml" ) summary(fit)data(klein) # ivreg2 help file line 1462: LIML, consumption on lagged profits, with # profits and wagetot treated as endogenous fit <- ivreg2( consump ~ l(profits, 1) | profits + wagetot | govt + taxnetx + year + wagegovt + capital1 + l(totinc, 1), data = klein, tvar = "yr", method = "liml" ) summary(fit)
Returns the regressor matrix (X), instrument matrix (Z), or projected
regressors (X_hat = P_Z X), as used in estimation. For models estimated
with partial, these are the post-partialling matrices that coef(),
residuals(), and vcov() correspond to. The returned matrices do not
depend on whether the model was fitted with x = TRUE: when the matrices
were not stored, they are reconstructed from the model frame and the same
partialling projection is re-applied.
## S3 method for class 'ivreg2' model.matrix( object, component = c("regressors", "projected", "instruments"), ... )## S3 method for class 'ivreg2' model.matrix( object, component = c("regressors", "projected", "instruments"), ... )
object |
An object of class |
component |
Character: which matrix to return. |
... |
Additional arguments (ignored). |
A numeric matrix, or NULL if component = "instruments"
for an OLS model.
Other ivreg2 methods:
coef.ivreg2(),
confint.ivreg2(),
diagnostics(),
first_stage(),
fitted.ivreg2(),
formula.ivreg2(),
ivreg2(),
nobs.ivreg2(),
predict.ivreg2(),
print.ivreg2(),
print.summary.ivreg2(),
residuals.ivreg2(),
summary.ivreg2(),
terms.ivreg2(),
update.ivreg2(),
vcov.ivreg2()
Cross-sectional data on 753 married white women from the Panel Study of
Income Dynamics (PSID), 1975. Of these, 428 were working (inlf == 1)
with observed wages. Used by Mroz (1987) to study married women's labor
force participation and hours of work. A classic IV application instruments
education with parental education (motheduc, fatheduc).
mrozmroz
A data frame with 753 observations and 22 variables:
In the labor force in 1975 (binary).
Hours worked in 1975.
Number of children younger than 6.
Number of children aged 6–18.
Age in years.
Years of education.
Estimated hourly wage (1975 dollars).
Reported hourly wage at interview (1976).
Husband's hours worked in 1975.
Husband's age.
Husband's years of education.
Husband's hourly wage (1975 dollars).
Family income (1975 dollars).
Federal marginal tax rate facing the woman.
Mother's years of education.
Father's years of education.
Unemployment rate in county of residence.
Lives in SMSA (binary).
Years of labor market experience.
Non-wife household income (faminc - wage * hours,
in thousands of 1975 dollars).
Log estimated hourly wage.
Experience squared (exper^2).
Mroz, T.A. (1987). "The Sensitivity of an Empirical Model of Married Women's Hours of Work to Economic and Statistical Assumptions." Econometrica, 55(4), 765–799.
Obtained from Stata's bcuse archive (Boston College),
bcuse mroz.
Redistribution basis: system.file("COPYRIGHTS", package = "ivreg2r").
Other ivreg2r datasets:
abdata,
card,
cigar,
griliches,
grunfeld,
klein,
nlswork,
phillips,
stockwatson,
wagepan
data(mroz) # Restrict to working women (observed wages) mroz_work <- subset(mroz, inlf == 1) # IV regression: instrument education with parental education (Example 15.5, # "Return to Education for Working Women", in Wooldridge (2020), # Introductory Econometrics). # These instruments (both parents' education) differ from the specification # in ?ivreg2, which instruments educ with fatheduc alone (just-identified) # and with age + kidslt6 + kidsge6 (overidentified). fit <- ivreg2(lwage ~ exper + expersq | educ | motheduc + fatheduc, data = mroz_work) summary(fit)data(mroz) # Restrict to working women (observed wages) mroz_work <- subset(mroz, inlf == 1) # IV regression: instrument education with parental education (Example 15.5, # "Return to Education for Working Women", in Wooldridge (2020), # Introductory Econometrics). # These instruments (both parents' education) differ from the specification # in ?ivreg2, which instruments educ with fatheduc alone (just-identified) # and with age + kidslt6 + kidsge6 (overidentified). fit <- ivreg2(lwage ~ exper + expersq | educ | motheduc + fatheduc, data = mroz_work) summary(fit)
[XT] Manual Extract)Panel data from the U.S. Bureau of Labor Statistics' National
Longitudinal Survey of Young Women, 14–24 years of age in 1968,
interviewed in survey years 1968–1988. This is the extract distributed
with Stata's [XT] manual (webuse nlswork): 28,534
person-year observations.
nlsworknlswork
A data frame with 28,534 observations and 21 variables:
Person identifier. Use as ivar.
Interview year (two-digit, e.g. 70 = 1970). The time
variable: use as tvar.
Birth year (two-digit).
Age in current year.
Race: 1 = White, 2 = Black, 3 = Other.
1 if married, spouse present.
1 if never married.
Current grade completed.
1 if college graduate.
1 if not in an SMSA (metropolitan area).
1 if central city.
1 if in the South.
Industry of employment (code).
Occupation (code).
1 if union member.
Weeks unemployed, last year.
Total work experience (years).
Job tenure (years).
Usual hours worked.
Weeks worked, last year.
Log wage (deflated by the GNP deflator).
race is coded 1 = White, 2 = Black, 3 = Other (faithful to the
upstream numeric coding; not converted to a factor). Many columns
contain missing values, consistent with the source survey.
U.S. Bureau of Labor Statistics. National Longitudinal Survey of Young Women, 14–24 years old in 1968. Center for Human Resource Research.
Distributed via Stata's webuse nlswork.
Redistribution basis: system.file("COPYRIGHTS", package = "ivreg2r").
Other ivreg2r datasets:
abdata,
card,
cigar,
griliches,
grunfeld,
klein,
mroz,
phillips,
stockwatson,
wagepan
data(nlswork) # ivreg2 help file line 1618: one-way cluster on person id fit <- ivreg2(ln_wage ~ grade + age + ttl_exp + tenure, data = nlswork, clusters = ~idcode) summary(fit) # ivreg2 help file line 1628: two-way cluster on person id and year fit2 <- ivreg2(ln_wage ~ grade + age + ttl_exp + tenure, data = nlswork, clusters = ~idcode + year) summary(fit2)data(nlswork) # ivreg2 help file line 1618: one-way cluster on person id fit <- ivreg2(ln_wage ~ grade + age + ttl_exp + tenure, data = nlswork, clusters = ~idcode) summary(fit) # ivreg2 help file line 1628: two-way cluster on person id and year fit2 <- ivreg2(ln_wage ~ grade + age + ttl_exp + tenure, data = nlswork, clusters = ~idcode + year) summary(fit2)
Extract number of observations from an ivreg2 object
## S3 method for class 'ivreg2' nobs(object, ...)## S3 method for class 'ivreg2' nobs(object, ...)
object |
An object of class |
... |
Additional arguments (ignored). |
Integer: number of observations.
Other ivreg2 methods:
coef.ivreg2(),
confint.ivreg2(),
diagnostics(),
first_stage(),
fitted.ivreg2(),
formula.ivreg2(),
ivreg2(),
model.matrix.ivreg2(),
predict.ivreg2(),
print.ivreg2(),
print.summary.ivreg2(),
residuals.ivreg2(),
summary.ivreg2(),
terms.ivreg2(),
update.ivreg2(),
vcov.ivreg2()
U.S. macroeconomic time series (1948–1996) with inflation and unemployment
rates plus lags and first differences. This is the same dataset used in
Stata's ivreg2 help file for HAC and AC examples, originally from
Wooldridge (2020).
phillipsphillips
A data frame with 49 observations and 11 variables:
Calendar year (1948–1996).
Inflation rate (percent).
Unemployment rate (percent).
Change in inflation (inf - inf_1).
Change in unemployment (unem - unem_1).
Lagged unemployment (one year).
Lagged inflation (one year).
Lagged unemployment (two years).
Lagged inflation (two years).
Lagged change in inflation.
Lagged change in unemployment.
Wooldridge, J.M. (2020). Introductory Econometrics: A Modern Approach, 7th ed. Cengage Learning. The underlying series are from the Economic Report of the President (a U.S. government work).
Downloaded from http://fmwww.bc.edu/ec-p/data/wooldridge/phillips.dta.
Redistribution basis: system.file("COPYRIGHTS", package = "ivreg2r").
Other ivreg2r datasets:
abdata,
card,
cigar,
griliches,
grunfeld,
klein,
mroz,
nlswork,
stockwatson,
wagepan
data(phillips) # OLS Phillips curve with AC standard errors: exact replication of the # Stata ivreg2 help-file example at line 1501 (`ivreg2 cinf unem, bw(3)`; # Bartlett is Stata's default kernel). Without vcov = "robust", a kernel # gives AC (autocorrelation-consistent) inference, not HAC. fit_ac <- ivreg2(cinf ~ unem, data = phillips, kernel = "bartlett", bw = 3, tvar = "year") summary(fit_ac) # Adding vcov = "robust" gives HAC (Newey-West), replicating the # help-file example at line 1511. fit_hac <- ivreg2(cinf ~ unem, data = phillips, vcov = "robust", kernel = "bartlett", bw = 3, tvar = "year", small = TRUE) summary(fit_hac)data(phillips) # OLS Phillips curve with AC standard errors: exact replication of the # Stata ivreg2 help-file example at line 1501 (`ivreg2 cinf unem, bw(3)`; # Bartlett is Stata's default kernel). Without vcov = "robust", a kernel # gives AC (autocorrelation-consistent) inference, not HAC. fit_ac <- ivreg2(cinf ~ unem, data = phillips, kernel = "bartlett", bw = 3, tvar = "year") summary(fit_ac) # Adding vcov = "robust" gives HAC (Newey-West), replicating the # help-file example at line 1511. fit_hac <- ivreg2(cinf ~ unem, data = phillips, vcov = "robust", kernel = "bartlett", bw = 3, tvar = "year", small = TRUE) summary(fit_hac)
Predict from an ivreg2 model
## S3 method for class 'ivreg2' predict(object, newdata, se.fit = FALSE, na.action = stats::na.pass, ...)## S3 method for class 'ivreg2' predict(object, newdata, se.fit = FALSE, na.action = stats::na.pass, ...)
object |
An object of class |
newdata |
An optional data frame for prediction. If omitted, fitted
values from the original data are returned. If the model uses
time-series operators (see |
se.fit |
Logical: if |
na.action |
Function for handling |
... |
Additional arguments (ignored). |
When se.fit = FALSE (default), a numeric vector of predicted
values. When se.fit = TRUE, a list with components fit (predicted
values) and se.fit (standard errors of prediction).
Other ivreg2 methods:
coef.ivreg2(),
confint.ivreg2(),
diagnostics(),
first_stage(),
fitted.ivreg2(),
formula.ivreg2(),
ivreg2(),
model.matrix.ivreg2(),
nobs.ivreg2(),
print.ivreg2(),
print.summary.ivreg2(),
residuals.ivreg2(),
summary.ivreg2(),
terms.ivreg2(),
update.ivreg2(),
vcov.ivreg2()
fit <- ivreg2(lwage ~ exper | educ | nearc4, data = card) # Fitted values on the estimation sample head(predict(fit)) # Predictions with standard errors for new data nd <- data.frame(exper = c(5, 10), educ = c(12, 16), nearc4 = c(0, 1)) predict(fit, newdata = nd, se.fit = TRUE)fit <- ivreg2(lwage ~ exper | educ | nearc4, data = card) # Fitted values on the estimation sample head(predict(fit)) # Predictions with standard errors for new data nd <- data.frame(exper = c(5, 10), educ = c(12, 16), nearc4 = c(0, 1)) predict(fit, newdata = nd, se.fit = TRUE)
Print an ivreg2 object
## S3 method for class 'ivreg2' print(x, digits = max(3L, getOption("digits") - 3L), ...)## S3 method for class 'ivreg2' print(x, digits = max(3L, getOption("digits") - 3L), ...)
x |
An object of class |
digits |
Minimum number of significant digits to print. |
... |
Additional arguments (ignored). |
x, invisibly.
Other ivreg2 methods:
coef.ivreg2(),
confint.ivreg2(),
diagnostics(),
first_stage(),
fitted.ivreg2(),
formula.ivreg2(),
ivreg2(),
model.matrix.ivreg2(),
nobs.ivreg2(),
predict.ivreg2(),
print.summary.ivreg2(),
residuals.ivreg2(),
summary.ivreg2(),
terms.ivreg2(),
update.ivreg2(),
vcov.ivreg2()
Formats and displays the full estimation output, including coefficient table, fit statistics, and IV diagnostic tests.
## S3 method for class 'summary.ivreg2' print( x, digits = max(3L, getOption("digits") - 3L), signif.stars = getOption("show.signif.stars", TRUE), ... )## S3 method for class 'summary.ivreg2' print( x, digits = max(3L, getOption("digits") - 3L), signif.stars = getOption("show.signif.stars", TRUE), ... )
x |
An object of class |
digits |
Minimum number of significant digits. |
signif.stars |
Logical: print significance stars? Default |
... |
Additional arguments passed to |
x, invisibly.
Other ivreg2 methods:
coef.ivreg2(),
confint.ivreg2(),
diagnostics(),
first_stage(),
fitted.ivreg2(),
formula.ivreg2(),
ivreg2(),
model.matrix.ivreg2(),
nobs.ivreg2(),
predict.ivreg2(),
print.ivreg2(),
residuals.ivreg2(),
summary.ivreg2(),
terms.ivreg2(),
update.ivreg2(),
vcov.ivreg2()
Respects na.action: when the model was fit with na.exclude,
NAs are reinserted at the omitted row positions so the result
aligns with the original data frame (matching base R's residuals.lm).
## S3 method for class 'ivreg2' residuals(object, ...)## S3 method for class 'ivreg2' residuals(object, ...)
object |
An object of class |
... |
Additional arguments (ignored). |
Numeric vector of residuals.
Other ivreg2 methods:
coef.ivreg2(),
confint.ivreg2(),
diagnostics(),
first_stage(),
fitted.ivreg2(),
formula.ivreg2(),
ivreg2(),
model.matrix.ivreg2(),
nobs.ivreg2(),
predict.ivreg2(),
print.ivreg2(),
print.summary.ivreg2(),
summary.ivreg2(),
terms.ivreg2(),
update.ivreg2(),
vcov.ivreg2()
Quarterly U.S. macroeconomic time series (1959Q1–2000Q4) used in Baum, Schaffer & Stillman (2007) to illustrate HAC standard errors, two-step GMM, and CUE estimation. Original source: Stock and Watson (2003).
stockwatsonstockwatson
A data frame with 168 observations and 17 variables:
Calendar year.
Quarter (1–4).
Stata quarterly date (0 = 1960Q1).
Unemployment rate (percent).
Consumer Price Index.
Federal funds interest rate.
Treasury bill rate.
Treasury bond rate.
Trade-weighted exchange rate.
Nominal GDP (billions of dollars).
Annualized CPI inflation: 100 * log(CPI / L4.CPI).
NA for the first 4 observations.
Annualized GDP growth: 100 * log(GDP / L4.GDP).
NA for the first 4 observations.
First difference of inflation (inf - L.inf).
NA for the first 5 observations.
Second lag of GDP growth (L2.ggdp).
First lag of Treasury bill rate (L.TBILL).
First lag of exchange rate (L.ER).
First lag of Treasury bond rate (L.TBON).
The derived variables inf, ggdp, dinf, and the lagged
instrument columns are pre-computed following Baum, Schaffer & Stillman
(2007, p. 474) so that
users can replicate their examples directly without time-series operators.
Stock, J.H. and Watson, M.W. (2003). Introduction to Econometrics. Addison-Wesley.
Downloaded from http://fmwww.bc.edu/ec-p/data/stockwatson/macrodat.dta.
Redistribution basis: system.file("COPYRIGHTS", package = "ivreg2r").
Baum, C.F., Schaffer, M.E. and Stillman, S. (2007). Enhanced routines for instrumental variables/generalized method of moments estimation and testing. The Stata Journal, 7(4), 465–506.
Other ivreg2r datasets:
abdata,
card,
cigar,
griliches,
grunfeld,
klein,
mroz,
nlswork,
phillips,
wagepan
data(stockwatson) # Baum, Schaffer & Stillman (2007), p. 475: 2SLS with IID errors fit_iv <- ivreg2(dinf ~ 1 | UR | ggdp_2 + TBILL_1 + ER_1 + TBON_1, data = stockwatson) summary(fit_iv) # Baum, Schaffer & Stillman (2007), p. 476: two-step GMM with HAC (Bartlett, bw=5) fit_gmm <- ivreg2(dinf ~ 1 | UR | ggdp_2 + TBILL_1 + ER_1 + TBON_1, data = stockwatson, method = "gmm2s", vcov = "robust", kernel = "bartlett", bw = 5, tvar = "date") summary(fit_gmm)data(stockwatson) # Baum, Schaffer & Stillman (2007), p. 475: 2SLS with IID errors fit_iv <- ivreg2(dinf ~ 1 | UR | ggdp_2 + TBILL_1 + ER_1 + TBON_1, data = stockwatson) summary(fit_iv) # Baum, Schaffer & Stillman (2007), p. 476: two-step GMM with HAC (Bartlett, bw=5) fit_gmm <- ivreg2(dinf ~ 1 | UR | ggdp_2 + TBILL_1 + ER_1 + TBON_1, data = stockwatson, method = "gmm2s", vcov = "robust", kernel = "bartlett", bw = 5, tvar = "date") summary(fit_gmm)
Builds a coefficient table (estimates, standard errors, test statistics,
p-values) and collects model diagnostics for display by
print.summary.ivreg2().
## S3 method for class 'ivreg2' summary(object, ...)## S3 method for class 'ivreg2' summary(object, ...)
object |
An object of class |
... |
Additional arguments (ignored). |
An object of class "summary.ivreg2".
ivreg2(); ivreg2r-glossary for the diagnostic acronyms printed
here; ivreg2r-conventions for the statistical conventions.
Other ivreg2 methods:
coef.ivreg2(),
confint.ivreg2(),
diagnostics(),
first_stage(),
fitted.ivreg2(),
formula.ivreg2(),
ivreg2(),
model.matrix.ivreg2(),
nobs.ivreg2(),
predict.ivreg2(),
print.ivreg2(),
print.summary.ivreg2(),
residuals.ivreg2(),
terms.ivreg2(),
update.ivreg2(),
vcov.ivreg2()
Extract terms object from an ivreg2 model
## S3 method for class 'ivreg2' terms(x, component = c("regressors", "instruments", "full"), ...)## S3 method for class 'ivreg2' terms(x, component = c("regressors", "instruments", "full"), ...)
x |
An object of class |
component |
Character: which terms object to return.
|
... |
Additional arguments (ignored). |
A terms object, or NULL if component = "instruments" for
an OLS model.
Other ivreg2 methods:
coef.ivreg2(),
confint.ivreg2(),
diagnostics(),
first_stage(),
fitted.ivreg2(),
formula.ivreg2(),
ivreg2(),
model.matrix.ivreg2(),
nobs.ivreg2(),
predict.ivreg2(),
print.ivreg2(),
print.summary.ivreg2(),
residuals.ivreg2(),
summary.ivreg2(),
update.ivreg2(),
vcov.ivreg2()
Constructs a tibble summarizing coefficient estimates, standard errors, test statistics, and p-values.
## S3 method for class 'ivreg2' tidy(x, conf.int = TRUE, conf.level = 0.95, exponentiate = FALSE, ...)## S3 method for class 'ivreg2' tidy(x, conf.int = TRUE, conf.level = 0.95, exponentiate = FALSE, ...)
x |
An object of class |
conf.int |
Logical: include confidence intervals? Default |
conf.level |
Confidence level for intervals. Default |
exponentiate |
Logical: exponentiate the coefficient estimates and
confidence interval bounds? Default |
... |
Additional arguments (ignored). |
A tibble::tibble() with columns term, estimate, std.error,
statistic, p.value, and optionally conf.low, conf.high.
Other broom methods:
augment.ivreg2(),
glance.ivreg2()
data(mroz) mroz_work <- subset(mroz, inlf == 1) fit <- ivreg2(lwage ~ exper + expersq | educ | age + kidslt6 + kidsge6, data = mroz_work, vcov = "robust") tidy(fit) tidy(fit, conf.int = FALSE) tidy(fit, exponentiate = TRUE) # Compare 2SLS and LIML side-by-side on the help-file baseline spec # (weak first stage; see the LIML example in ?ivreg2 for the framing) fit_liml <- ivreg2(lwage ~ exper + expersq | educ | age + kidslt6 + kidsge6, data = mroz_work, method = "liml") comparison <- rbind( cbind(method = "2SLS", tidy(fit)), cbind(method = "LIML", tidy(fit_liml)) ) comparison[comparison$term == "educ", c("method", "estimate", "std.error")]data(mroz) mroz_work <- subset(mroz, inlf == 1) fit <- ivreg2(lwage ~ exper + expersq | educ | age + kidslt6 + kidsge6, data = mroz_work, vcov = "robust") tidy(fit) tidy(fit, conf.int = FALSE) tidy(fit, exponentiate = TRUE) # Compare 2SLS and LIML side-by-side on the help-file baseline spec # (weak first stage; see the LIML example in ?ivreg2 for the framing) fit_liml <- ivreg2(lwage ~ exper + expersq | educ | age + kidslt6 + kidsge6, data = mroz_work, method = "liml") comparison <- rbind( cbind(method = "2SLS", tidy(fit)), cbind(method = "LIML", tidy(fit_liml)) ) comparison[comparison$term == "educ", c("method", "estimate", "std.error")]
l() (lag) and d() (difference) may be used inside an ivreg2() formula
to create lags and differences of a variable on the fly, resolved against
the time variable tvar (and panel variable ivar for panel data). They
mirror Stata's tsset-aware L. and D. operators:
l(x, k = 1) d(x, k = 1)l(x, k = 1) d(x, k = 1)
x |
A numeric variable in the model data. |
k |
Lag order(s) for |
| R syntax | Meaning | Stata equivalent |
l(x), l(x, 1) |
lag 1 | L.x |
l(x, 1:3) |
lags 1, 2, 3 (three terms) | L(1/3).x |
l(x, 0) |
x itself |
L0.x |
d(x), d(x, 1) |
first difference x - l(x, 1) |
D.x |
d(x, 2) |
second-order difference x - 2 l(x, 1) + l(x, 2) |
D2.x
|
When used inside an ivreg2() formula: a numeric vector aligned
to the model data. Calling these functions anywhere else is an error.
Lags are computed by time value, not row position: l(x, k) at time
t is the value of x at time t - k within the same panel unit. If no
observation exists at t - k (start of the series, or a gap in the time
variable), the lag is NA and the row is dropped from the estimation
sample — exactly Stata's behavior. Lags never cross panel-unit boundaries.
The data does not need to be sorted.
Following Stata (not fixest), d(x, k) is the k-th order (iterated)
difference (1-L)^k x, matching Stata's Dk.x; fixest's d(x, k) is the
distance-k difference x - l(x, k). The two agree for k = 1.
Operators require tvar (and ivar for panel data) to be passed to
ivreg2(); l() and d() are not standalone lag utilities and signal an
error when called outside an ivreg2() formula (use, e.g.,
dplyr::lag() with a consecutive-periods check, or fixest/collapse/
plm, for general-purpose panel lagging). The time variable must be
integer-valued (greater than , at most ), like
Stata's tsset — lag arithmetic on fractional or astronomically large
time values is not exact in floating point. The lag/difference order k
must be a constant non-negative integer (or integer vector for ranges);
leads (negative k), nested operators (l(d(x))), and ranges on the
left-hand side (the model has a single dependent variable) are not
supported. When operators appear among the regressors,
predict(fit, newdata) recomputes them within newdata, so newdata
must contain the history rows needed for the lags; rows whose lags are
missing get NA predictions (again matching Stata). Operators confined
to the instrument part impose no requirement on newdata.
data(phillips) # Stata: ivreg2 cinf (unem = l(1/3).unem), bw(3) fit <- ivreg2(cinf ~ 1 | unem | l(unem, 1:3), data = phillips, tvar = "year", vcov = "AC", kernel = "bartlett", bw = 3) coef(fit)data(phillips) # Stata: ivreg2 cinf (unem = l(1/3).unem), bw(3) fit <- ivreg2(cinf ~ 1 | unem | l(unem, 1:3), data = phillips, tvar = "year", vcov = "AC", kernel = "bartlett", bw = 3) coef(fit)
Updates the formula and/or other arguments of an ivreg2 call and
(optionally) re-fits the model.
## S3 method for class 'ivreg2' update(object, formula., ..., evaluate = TRUE)## S3 method for class 'ivreg2' update(object, formula., ..., evaluate = TRUE)
object |
An object of class |
formula. |
A formula to update the model formula (see update.formula). Multi-part formula updates are supported. |
... |
Additional arguments to update in the call (e.g.,
|
evaluate |
Logical: if |
If evaluate = TRUE, a new ivreg2 object. If evaluate = FALSE,
the unevaluated call.
Other ivreg2 methods:
coef.ivreg2(),
confint.ivreg2(),
diagnostics(),
first_stage(),
fitted.ivreg2(),
formula.ivreg2(),
ivreg2(),
model.matrix.ivreg2(),
nobs.ivreg2(),
predict.ivreg2(),
print.ivreg2(),
print.summary.ivreg2(),
residuals.ivreg2(),
summary.ivreg2(),
terms.ivreg2(),
vcov.ivreg2()
Extract variance-covariance matrix from an ivreg2 object
## S3 method for class 'ivreg2' vcov(object, ...)## S3 method for class 'ivreg2' vcov(object, ...)
object |
An object of class |
... |
Additional arguments (ignored). |
The variance-covariance matrix of the coefficient estimates.
Other ivreg2 methods:
coef.ivreg2(),
confint.ivreg2(),
diagnostics(),
first_stage(),
fitted.ivreg2(),
formula.ivreg2(),
ivreg2(),
model.matrix.ivreg2(),
nobs.ivreg2(),
predict.ivreg2(),
print.ivreg2(),
print.summary.ivreg2(),
residuals.ivreg2(),
summary.ivreg2(),
terms.ivreg2(),
update.ivreg2()
Balanced panel data from the National Longitudinal Survey of Youth (NLSY), 1980–1987. Contains 4,360 observations on 545 young men observed over 8 years (the panel is balanced: every man contributes exactly one observation per year). Useful for demonstrating panel methods, including two-way clustering by individual and year.
wagepanwagepan
A data frame with 4,360 observations and 11 variables:
Person identifier.
Calendar year (1980–1987).
Log hourly wage.
Years of education.
Black (binary).
Hispanic (binary).
Years of labor market experience.
Experience squared (exper^2).
Married (binary).
Union member (binary).
Annual hours worked.
The bundled data are in raw levels, not within-transformed. Fixed-effects
use (e.g. the Stock-Watson panel-robust VCE, sw = TRUE) requires
demeaning each variable by panel unit before fitting; see the worked
example in the "Fixed-effects panels: the Stock-Watson correction"
section of vignette("time-series-gmm").
Vella, F. and Verbeek, M. (1998). "Whose Wages Do Unions Raise? A Dynamic Model of Unionism and Wage Rate Determination for Young Men." Journal of Applied Econometrics, 13(2), 163–183.
Wooldridge, J.M. (2010). Econometric Analysis of Cross Section and Panel Data, 2nd ed. MIT Press.
Obtained from Stata's bcuse archive (Boston College),
bcuse wagepan.
Redistribution basis: system.file("COPYRIGHTS", package = "ivreg2r").
Other ivreg2r datasets:
abdata,
card,
cigar,
griliches,
grunfeld,
klein,
mroz,
nlswork,
phillips,
stockwatson
data(wagepan) # OLS with two-way clustering by person and year # The canonical two-way clustering example from the ivreg2 help file lives # in ?nlswork; this block illustrates the same VCE on a different panel. fit <- ivreg2(lwage ~ educ + black + hisp + exper + expersq + married + union, data = wagepan, clusters = ~ nr + year, small = TRUE) summary(fit)data(wagepan) # OLS with two-way clustering by person and year # The canonical two-way clustering example from the ivreg2 help file lives # in ?nlswork; this block illustrates the same VCE on a different panel. fit <- ivreg2(lwage ~ educ + black + hisp + exper + expersq + married + union, data = wagepan, clusters = ~ nr + year, small = TRUE) summary(fit)