reghdfe

repository·master·Indexed 42 days ago

https://github.com/sergiocorreia/reghdfe

A high-performance Stata package for estimating linear regressions with multiple levels of fixed effects. It generalizes built-in commands like areg and xtreg, offering support for multi-way clustering, instrumental variables (via ivreghdfe), and robust variance estimators. Version 6.x introduces experimental support for Driscoll-Kraay standard errors and individual fixed effects through indiv(), group(), and aggregation() options.

Tokens
5.6K
Snippets
12
Records
29
Agent score
54%

What's inside reghdfe

  1. What is reghdfe?

    master

    reghdfe is a Stata package designed to estimate linear regressions with multiple levels of fixed effects. It serves as a high-performance generalization of Stata's built-in areg, xtreg,fe, and xtivreg,fe commands.

    Key capabilities include:

    • Efficient Fixed Effect Absorption: Uses a robust algorithm to handle multiple fixed effects, performing well even in 'hard cases' where other algorithms fail to converge.
    • High Speed: Significantly faster than alternatives like reg2hdfe, a2reg, felsdvreg, and res2fe, especially when dealing with multiple fixed effects.
    • Advanced Clustering: Supports two-way and multi-way clustering of standard errors.
    • Robust Estimators: Integrates with the avar package for an extensive list of robust variance estimators.
    • IV and GMM Support: Works with instrumental-variable and GMM estimators (e.g., two-step-GMM, LIML) via the ivreg2 routine.
    • Flexible Modeling: Supports multiple heterogeneous slopes, frequency/probability/analytic weights, and time-series/factor variables.
    • Convenience Features: Allows expressing fixed effects and clusters as factor interactions (e.g., state#year) and supports postestimation commands like predict and test.
    • Optimization: Includes a cache() option to precompute results for faster subsequent regressions.
  2. What is reghdfe and when to use it

    master

    reghdfe is a Stata package designed for running linear and instrumental-variable (IV) regressions with multiple sets of fixed effects. It is a generalization of Stata's built-in areg and xtreg commands.

    Use reghdfe when your model requires:

    • Multiple Fixed Effects: Any number of absorbed variables or fixed effects.
    • Fixed Slopes: Support for fixed slopes in addition to fixed intercepts.
    • Instrumental Variables: Two-stage least squares (2SLS) support via ivreg2 and ivregress integration.
    • Multi-way Clustering: Clustering standard errors across two or more cluster variables.
    • Advanced Standard Errors: Sophisticated error computation using the avar command.
    • Complex Degrees of Freedom: Accurate estimation of degrees of freedom that accounts for nesting of fixed effects within clusters and collinearity within fixed effects.
  3. Avoid pitfalls with the constant term in reghdfe

    master

    The constant term in reghdfe can be problematic and often provides little useful information. Keep the following in mind:

    • Interpretation: The constant is the expected value when all independent variables are zero, not the average of the dependent variable.
    • Singleton Groups: Using the dropsingleton option will change the estimated value of the constant.
    • Conflicts: The constant can conflict with the over() option and may mess up Variance-Covariance Matrix (VCV) calculations, specifically when using ivreg2 or avar with clustering.
    • Dropping the constant: To disable the automatic addition of the constant term after partialling-out fixed effects, use the noconstant option. Note that by construction, all reghdfe regressions include a constant through the absorb() terms.
    • ivreg2 behavior: When using ivreg2, the constant is always omitted to prevent errors regarding orthogonality conditions (where S is not of full rank) when using clustered standard errors.
  4. Key features and Stata compatibility of reghdfe

    master

    reghdfe is designed to follow standard Stata conventions, making it easy to integrate into existing workflows:

    • Notation Support: Works with time series and factor variable notation, even when used within absorbing variables or cluster variables.
    • Weight Support: Supports frequency weights, analytic weights, and probability weights.
    • Post-estimation: Compatible with most standard Stata post-estimation commands such as test, estat summarize, and predict.
    • Performance: Includes multicore support via the -parallel- suite and can cache results to speed up repeated regressions on the same data or regressions across different categories.
  5. Understanding the Kaczmarz algorithm sketch for solving alphas

    master

    The Kaczmarz algorithm is a sketch for iteratively solving for fixed effects (alphas) in a linear system $Ax=b$.

    Given a system where $A$ is $N imes M$, the process starts with an initial guess $p=0$ (an $M imes 1$ vector). The algorithm iterates through every observation $i$ until convergence. For each observation, it calculates a residual $s$ by subtracting the current estimated effects (intercepts and slopes) from the target value $b[i]$, then updates the effects using a denominator term to ensure convergence.

    Key components:

    • Residual calculation ($s$): For each observation $i$, $s$ is initialized to $b[i]$ and adjusted by subtracting the current alphas for each fixed effect group $g$ where the observation belongs to a specific level.
    • Denominator (denom[i]): This term scales the update. If only intercepts are used, denom[i] = G (the number of groups). If slopes are included, denom[i] = num_intercepts + cvar[i]'cvar[i] (where cvar represents the covariance of the slopes).
    s = b[i]
    for g=1:G
    	level = F[g].levels[i]
    	if has_intercept[g]: s -= F[g].alphas[level, 1]
    	// if has_slope: iterate for every slope; don't forget to add back stdev
    next
    s = s / denom[i]
    for g=1:G
    	F[g].alphas[level, 1] += s
    	// also update slopes
    next
  6. Why you should exclude singletons from HDFE regressions

    master

    A singleton is an individual that appears in only one observation. In regressions with fixed effects, singletons do not contribute useful information for estimating regressors because the fixed effect perfectly explains the dependent variable for that individual.

    Excluding singletons is recommended for three reasons:

    1. Correcting Standard Errors: When using clustered standard errors with fixed effects (especially in High-Dimensional Fixed Effects/HDFE settings), including singletons can lead to underestimated standard errors and overestimated P-values. This is because singletons can artificially inflate the sample size $N$ without increasing the effective number of clusters $M$ or providing within-cluster variability.
    2. Identifying Effective Cluster Size: Removing singletons reveals the effective number of clusters, which is critical for determining if the cluster count is large enough for asymptotic theory to apply.
    3. Computational Efficiency: Excluding singletons speeds up HDFE computations by reducing the number of ancillary parameters that need to be estimated.
  7. How singletons bias clustered standard errors

    master

    Singletons do not affect coefficient estimates, but they significantly bias standard error estimates.

    In a regression with clustered standard errors, the variance-covariance matrix $V$ is adjusted by a finite-sample factor $q$:

    $$q = \frac{M}{M-1} \times \frac{N-1}{N-K-L}$$

    Where:

    • $M$ is the number of clusters.
    • $N$ is the number of observations.
    • $K$ is the number of regressors (excluding the constant).
    • $L$ is the number of fixed effects.

    When fixed effects are nested within clusters, singletons cause the 'meat' and 'bread' of the variance (the residuals and score matrix) to remain unchanged, but they change the $q$ factor (the 'wooden stick'). Because $L$ is often excluded from the denominator of $q$ when nested, the denominator does not adjust for the loss of information, leading to biased results.

    Mitigation: A common solution is to remove singleton clusters from $M$ (using $M_S$ as the number of singleton clusters) to calculate a corrected $q^*$:

    $$q^* = \frac{M-M_S}{M-M_S-1} \times \frac{N-M_S-1}{N-M_S-K-L^*}$$

    Alternatively, excluding singletons or using bootstrapped standard errors can ameliorate this bias.

  8. Acceleration Techniques for MAP convergence

    master

    To improve the convergence speed of the Method of Alternating Projections, the following acceleration schemes are discussed:

    • Steep Descent: A technique closely related to the algorithms used in lfe, reg2hdfe, and older versions of reghdfe.
    • Conjugate Gradient (CG): Requires a symmetric operator to guarantee convergence (which rules out the standard Kaczmarz scheme).
    • Aitken's delta-squared formula variant: A third scheme where the scalar t (which determines acceleration) is computed using a variant of this formula. Note that this method may require additional tuning in each iteration as it can get stuck or fail to converge under certain conditions.
  9. Projection Schemes in MAP

    master

    The Method of Alternating Projections utilizes three primary alternating projection schemes to converge toward the joint projection. In all cases, the limit of the transformation $T^k y$ as $k$ approaches infinity is $My$, meaning $My$ is the fixed point of the $Ty$ transformation.

    1. Kaczmarz: $T = M_G M_{G-1} ... M_1$
    2. Cimmino: $T = (M_G + M_{G-1} + ... + M_1) / G$
    3. Symmetric Kaczmarz: $T = M_G M_{G-1} ... M_1 M_2 ... M_G$

    Note that only the Cimmino and Symmetric Kaczmarz schemes result in symmetric operators. Convergence speed may be affected by conditions related to the second eigenvalue of the underlying graph.

  10. Avoid overstated significance caused by singleton groups in nested fixed effects

    master

    When performing regressions where fixed effects are nested within clusters (e.g., firm fixed effects nested within industry clusters), keeping singleton groups (groups with only one observation) can lead to incorrect statistical inference.

    The Problem

    If singletons are not dropped, the finite-sample adjustment factor ($q$) converges toward 1. This causes:

    1. Underestimated standard errors: Statistical significance will be overstated.
    2. Overstated cluster counts: The reported number of clusters may be higher than the actual number of informative clusters.
    3. Slower estimation: More ancillary parameters are estimated than necessary.

    Note that coefficient estimates and the asymptotic part of the variance estimator remain unchanged; the issue is strictly with the finite-sample adjustment used for robust and cluster-robust standard errors.

    The Solution

    You can mitigate this by either:

    • Removing singleton groups from the dataset before estimation.
    • Excluding singleton counts from the number of clusters ($M$) and observations ($N$) used in the variance calculation.

    Note: Future versions of reghdfe will automatically drop singletons to prevent this issue.

  11. How the Method of Alternating Projections (MAP) works in reghdfe

    master

    The reghdfe package can compute least square residuals of a variable y with respect to groups of regressors $X_1, ..., X_G$ (denoted as $M$) using the Method of Alternating Projections (MAP).

    Instead of direct methods like computing inv(X'X)X'y, MAP uses iterated methods to find the joint projection. To transform the least-squares problem into a standard linear system form ($Ax=b$), the system is premultiplied by $X'$, resulting in the form $X'Xb = X'y$. Under the least-squares solution, $X'e=0$ and $X'Xb = y$.

  12. Important dependencies and compatibility notes

    master

    When using reghdfe, be aware of the following:

    • Dependencies: reghdfe requires the ftools package. For Stata 12 and older, it also requires boottest.
    • IV/GMM Support: reghdfe does not perform IV/GMM directly. Instead, use the ivreghdfe package, which adds an absorb() option to ivreg2.
    • Poisson Models: If you are running regressions with log(y) on the left-hand side (Poisson models), use the ppmlhdfe package instead of reghdfe.
    • Version Check: You can check your currently installed version by typing reghdfe, version in Stata.