plm: panel regression (spreg, linearmodels, R)¶
The user guide of this module: plm.
- class apatools.plm.PanelData(y, x, ent, tim, w, N, T, entities, times)[source]¶
Bases:
objectBalanced panel in the long layout used by spreg:
Tconsecutive blocks (periods) ofNrows (entities), the entities in the order of the rows of the weightsw.Usually created by
make_panel()(called byplm(), which stores the instance on every fitted model asplm_panel).- y¶
Dependent variable (float),
MultiIndex(entity, time)with level names"entity"and"time", sorted by period first and then by entity.- Type:
- x¶
Predictors (float, without constant), same index.
- Type:
- ent, tim
Entity / period position (0..N-1 / 0..T-1) of every row.
- Type:
- w¶
Weights aligned with the entities (
w.n == N), or None.- Type:
libpysal.weights.W or None
- N, T
Number of entities and of periods;
len(y) == N * T.- Type:
- entities, times
Labels of the entities (in layout order) and of the periods (sorted).
- Type:
- subset(keep)[source]¶
Panel restricted to the rows
keep(boolean mask). Must remove whole entities and/or whole periods so that the panel stays balanced;wis restricted accordingly.- Parameters:
keep (array-like of bool) – Mask with one element per row of the panel.
- Returns:
PanelData – New panel (the positions
ent/timare renumbered from 0;wis restricted with the original weight values kept, and the original transformation re-applied).- Raises:
ValueError – If the kept rows do not form a balanced rectangle (entities x periods).
- apatools.plm.make_panel(data, y=None, x=None, entity=None, time=None, w=None, formula=None, dropna=True, balance='error', w_ids=None)[source]¶
Convert a long DataFrame into a
PanelDatain the layout needed by spreg.The rows are sorted by period first and then by entity; the entities are ordered like the rows of
w(withw) or sorted (withoutw; in order of appearance if they cannot be sorted). Rows with a missing entity or period label are dropped.- Parameters:
data (pandas.DataFrame) – Long data. The index must be unique if
formulais used.y (str) – Dependent variable (ignored if
formulais given).x (list of str) – Predictors, without constant (ignored if
formulais given).entity (str, optional) – Columns (or index levels) identifying entity and period. Pass both or none; if both are None, the index must be a two-level
(entity, time)MultiIndex.time (str, optional) – Columns (or index levels) identifying entity and period. Pass both or none; if both are None, the index must be a two-level
(entity, time)MultiIndex.w (libpysal.weights.W, optional) – Spatial weights. The entity values must be the ids
w.id_order(orw_ids); entities missing in the data are removed fromw(with aUserWarning).formula (str, optional) – patsy formula (
"y ~ x1 + x2"); the intercept is dropped (spreg and linearmodels handle constants themselves). Rows with NAs are always dropped by patsy.dropna (bool, default True) – Drop rows with missing values in
y/x(not used withformula).balance ({"error", "drop"}, default "error") – What to do with entities that are not observed in every period: raise a
ValueErroror drop these entities (with aUserWarning).w_ids (sequence, optional) – Entity labels in the row order of
w. Default:w.id_order.
- Returns:
PanelData – The balanced panel (
Nentities,Tperiods,N * Trows).- Raises:
ValueError – For an invalid
balance/entity/timecombination, a MultiIndex of the wrong shape, duplicated(entity, time)pairs, an unbalanced panel withbalance="error", entities that are not ids ofw, or missingy/x.KeyError – If
entity/timeis neither a column nor an index level.
- apatools.plm.base_metrics(r, panel=None)[source]¶
Fit metrics of a fitted panel model of either backend.
Keys (where available):
model,backend,r_sqandr_sq_type("ols": pooled R²,"within": R² of the within-transformed data of an FE model,"overall": R² of a RE model with linearmodels,"pseudo": spreg pseudo R², the squared correlation of observed and predicted y),r_sq_adj,f_stat,f_pvalue,df_model,df_resid(FE:N·T - N - k),aic,bic,llf(spreg: they do not count theNfixed effects),n_obs(= N·T),n_entities,n_periods,n_params(slope coefficients),maeandmad(median absolute deviation of the residuals).Residuals (
mae,mad) follow the estimator: for non-spatial FE models (both backends) they are the residuals of the within model, i.e. they include the estimated entity effects; for pooled and RE models they arey - x·β(spreg) or the backend’s residuals (linearmodels). spreg’s ownPanelFEreportsy - x·βand a pseudo R² that ignore the effects, so the within R² and the residuals are recomputed here. spreg’s FE standard errors useN·T - Ninstead ofN·T - N - kdegrees of freedom (slightly too small), and its confidence intervals / p-values are normal-based.- Parameters:
- Returns:
dict – See above.
f_stat/f_pvalue/df_model/df_residare missing for spatial and random-effects models (and for the linearmodels random-effects model);r_sq_adjexists for pooled OLS and non-spatial FE models only;aic/bicexist only for spreg models that report them,llfif the backend provides a finite log-likelihood.
Notes
The F test of an FE model compares the within R² with
df_model = kanddf_resid = N·T - N - k. With period effects (effects="time"or"twoway"ofplm(), both backends) R² is the within R² after removing all effects anddf_resid = N·T - A - kwithAthe number of effects estimated away (N + T - 1for two-way,Tfor time effects with the constant). The linearmodels F statistic follows the covariance type of the fit (robust version if the covariance is not"Unadjusted").
- apatools.plm.pred_metrics(results, panel, backend='spreg', group='entity', exclude_neighbors=False, **kwargs)[source]¶
Leave-one-group-out prediction metrics (R²pred, MAEpred, MADpred) for panel models.
Leave-one-observation-out is not meaningful for panels: the other periods of the same entity leak into the training sample. Instead whole groups are held out in turn, the model (and the weights) are refitted without them and their rows are predicted:
group="entity": one entity at a time (all its periods). Predicts a new entity, so it is not possible for fixed-effects models (an entity effect cannot be estimated); their metrics arenanwith a warning.group="time": one period at a time (all entities). Works for every model; fixed effects are estimated from the remaining periods.
Predictions are
x·βplus the constant, plusρ·(Wy)for spatial lag models (observedyof the neighbours in the same period, original weights) and plus the entity effect for FE models. Random-effects models use the population-average predictor (no entity effect). Models withslx_lagsare not supported.Warning
With spatial data the neighbours of a held-out entity stay in the training sample, which makes
group="entity"optimistic (seeapatools.slm.pred_metrics()).exclude_neighbors=Trueadditionally removes the neighbours of the held-out entity from the training sample (only forgroup="entity"; needsw).Cost: one refit per group and model.
- Parameters:
results (list) – Fitted models (from
plm()), whose type determines the model names.panel (PanelData) – The panel the models were fitted on (
results[i].plm_panel).backend ({"spreg", "linearmodels"}, default "spreg") – Estimation package used to refit the models.
group ({"entity", "time"}, default "entity") – Which groups are held out in turn.
exclude_neighbors (bool, default False) – Also remove the neighbours (according to
panel.w) of the held-out entity from the training sample; needsgroup="entity"and weights (ValueErrorotherwise).**kwargs – The model arguments passed to
plm()(<model>_model_<argument>etc.).slx_lags > 0raisesNotImplementedError.
- Returns:
list of dict – One dict per model with
pred_loo_r_sq(clipped to [-1, 1]),pred_loo_maeandpred_loo_mad(median absolute deviation of the prediction errors); allnanfor models that could not be refitted (FE models withgroup="entity", or every refit failed). Refits that fail are skipped and reported in aUserWarning; another warning reports training weights with islands.
Notes
A cross-validation-style metric (leave-one-group-out). With
ethe prediction errors of all held-out rows,pred_loo_r_sq = 1 - Σ e² / Σ (y - ȳ)²(ȳ: mean of ally, the sums run over the predicted rows),pred_loo_mae = mean(|e|)andpred_loo_mad = median(|e - median(e)|).References
Roberts, D. R., Bahn, V., Ciuti, S., Boyce, M. S., Elith, J., Guillera-Arroita, G., Hauenstein, S., Lahoz-Monfort, J. J., Schröder, B., Thuiller, W., Warton, D. I., Wintle, B. A., Hartig, F., & Dormann, C. F. (2017). Cross-validation strategies for data with temporal, spatial, hierarchical, or phylogenetic structure. Ecography, 40(8), 913-929. https://doi.org/10.1111/ecog.02881
- apatools.plm.plm(data, y=None, x=None, w=None, entity=None, time=None, model='fe', formula=None, backend='spreg', **kwargs)[source]¶
Fit panel regressions (pooled, fixed effects, random effects, optionally spatial).
The data are converted with
make_panel()(balanced panel in the layout of spreg) and every requested model is fitted on it. Spatial models: spatial lag with fixed or random effects (Elhorst, 2003, 2014), spatial error with pooled, fixed or random effects by maximum likelihood (Anselin, 1988) or the generalized-moments estimator of Kapoor, Kelejian and Prucha (2007).- Parameters:
data (pandas.DataFrame) – Long panel data with an entity and a time column (or an
(entity, time)index).y (str) – Dependent variable; ignored if
formulais given.x (list of str) – Predictors (no constant); ignored if
formulais given.w (libpysal.weights.W, optional) – Spatial weights (required for the
slm_*/sem_*models). The entity values must be its ids (w.id_order), or passw_ids. Seemake_panel().entity (str, optional) – Entity and period columns (or index levels). Both None: use the two-level index.
time (str, optional) – Entity and period columns (or index levels). Both None: use the two-level index.
model (str or list of str) – Any of
pooled, fe, re, slm_fe, slm_re, sem_pooled, sem_fe, sem_re, sem_pooled_gm, sem_re_gm(see the module docstring); linearmodels supportspooled, fe, re.formula (str, optional) – patsy formula; overrides
y/x.backend ({"spreg", "linearmodels", "splm"}) – Estimation package.
"linearmodels"is an optional dependency and allows e.g.fe_fit_cov_type="clustered"orfe_fit_cluster_entity=True, and time or two-way fixed effects (effects)."splm"uses R (packages plm, splm, spdep) throughRscript; the results areapatools.r.splm.SplmFitobjects instead of spreg or linearmodels results.**kwargs – Function options (below) and arguments for the backend named
<model>_model_<argument>(passed to the model class, e.g.slm_fe_model_method="LU"; with"splm"toplm::plm/splm::spml, e.g.slm_fe_model_zero.policy=True) or<model>_fit_<argument>(passed to.fit(), linearmodels only), where<model>is one of the names above.effects ({"entity", "time", "twoway"}, default "entity") –
Effects of the fixed-effects models (
fe,slm_fe,sem_fe): entity (the usual within model), time (period) or both (two-way fixed effects); the other models ignore it. Where each is available:model
spreg
linearmodels
splm (R)
feentity, time, twoway
entity, time, twoway
entity, time, twoway
slm_feentity, twoway
not available
entity, time, twoway
sem_feentity, time, twoway
not available
entity, time, twoway
all other models
ignored
ignored
ignored
linearmodels: sets its arguments
entity_effectsandtime_effects(fe_model_entity_effects/fe_model_time_effectsstill work and take precedence). splm: sets the argumenteffectof R’splm/spml(fe_model_effecttakes precedence). spreg has no such option, so the period effects are period dummies added to the regressors (time[<period>]inr.summary; hidden byplm_report()), valid for any spatial weights;"time"is then the pooled model with the dummies (feandsem_fe; there is no pooled spatial lag model, so notslm_fe), andslx_lagsis not available.plm_tests()compares models with period effects by F / likelihood-ratio tests (no Hausman test), and they have nopred_*metrics. The standard errors of spreg’s entity-effects models useN·T - Ndegrees of freedom (seebase_metrics()), so with"twoway"they are slightly too small. The standard errors ofrho/lambdacome from spreg’s analytic information matrix and understate the sampling spread somewhat in small panels (the within ML estimator is biased towards zero).rscript (str, optional) –
backend="splm": path ofRscript(default: the environment variableAPATOOLS_RSCRIPT, thePATHand the usual install locations).r_timeoutlimits the time of every R run (seconds).verbose (bool, default True) – Print the panel dimensions and the model summaries.
dropna (bool, default True) – Drop rows with missing values.
balance ({"error", "drop"}, default "error") – Entities not observed in all periods: raise an error or drop them.
w_ids (sequence, optional) – Entity labels in the row order of
w(defaultw.id_order).slx_lags (int, default 0) – Number of spatial lags of the predictors (spreg models that support it; not with linearmodels).
base_metrics (bool, default True) – Compute
base_metrics().pred_metrics (bool, default False) – Add leave-one-group-out prediction metrics, see
pred_metrics().pred_group ({"entity", "time"}, default "entity") – Group that is held out.
pred_exclude_neighbors (bool, default False) – Also hold out the neighbours of the held-out entity (needs
w).
- Returns:
results (list) – One fitted model per entry of
model(spreg or linearmodels objects, orSplmFitfor R). Each has the attributesplm_panel(thePanelDataused) andplm_spec(backend and fitting options), whichmundlak()andplm_tests()need.metrics (list of dict) – See
base_metrics()(pluspred_loo_*if requested). Empty if neitherbase_metricsnorpred_metricsis requested.
- Raises:
ValueError – For an unknown
backendor spatial model withoutw(and the errors ofmake_panel()).NotImplementedError – For an unknown model name, a spatial model /
slx_lagswithbackend="linearmodels",slx_lagsor a GMM model withbackend="splm".ImportError – If
backend="linearmodels"and linearmodels is not installed, or an R package is missing withbackend="splm".RuntimeError – If R is not found or fails (
backend="splm").
References
Anselin, L. (1988). Spatial econometrics: Methods and models. Kluwer Academic. https://doi.org/10.1007/978-94-015-7799-1
Elhorst, J. P. (2003). Specification and estimation of spatial panel data models. International Regional Science Review, 26(3), 244-268. https://doi.org/10.1177/0160017603253791
Elhorst, J. P. (2014). Spatial econometrics: From cross-sectional data to spatial panels. Springer. https://doi.org/10.1007/978-3-642-40340-8
Kapoor, M., Kelejian, H. H., & Prucha, I. R. (2007). Panel data models with spatially correlated error components. Journal of Econometrics, 140(1), 97-130. https://doi.org/10.1016/j.jeconom.2006.09.004
Baltagi, B. H. (2021). Econometric analysis of panel data (6th ed.). Springer. https://doi.org/10.1007/978-3-030-53953-5
Examples
>>> results, metrics = plm( ... df, "y", ["x1", "x2"], w=w, entity="county", time="year", ... model=["pooled", "fe", "re", "slm_fe"], ... verbose=True, balance="error", slx_lags=0, ... base_metrics=True, pred_metrics=True, pred_group="time", ... slm_fe_model_method="LU", ... )
- apatools.plm.plm_report(results, metrics=None, format_pval=True, add_stars=True, decimal=3, add_ftest=True, add_aic=True, add_bic=True, add_llf=True, add_mae=True, add_mad=True, add_pred_loo_mae=True, add_pred_loo_mad=True, add_n_obs=True, add_panel_dims=True, intercept_name='Intercept')[source]¶
Build one APA-style coefficient table per model from
plm()output.Columns: coef, se, z (or t), p-value, cil, cir (95% CI), optional
sigstars. The first row’smodelcolumn holds a fit summary such asR²within = .36, R²adj = .34, F(2, 123) = 35.1, p < .001, MAE = ..., N = 150, n = 25, T = 6; R²pred, MAEpred and MADpred appear ifplm()was run withpred_metrics=True.R²withinis the R² of the within-transformed data (FE),R²overallthe overall R² of a random-effects model (linearmodels),R²pseudothe squared correlation of observed and predicted y (spreg, spatial and RE models) and a plainR²is the pooled OLS R². The spatial parameters (rho= ρ of the lag models,lambda= λ of the error models) and the variance parameters of spreg (e.g.phi,sigma2_v) are rows of the table.- Parameters:
results (list) – Fitted models (first value returned by
plm()).metrics (list of dict, optional) – Metrics (second value returned by
plm()), matched withresultsby position; without them the tables have nomodelcolumn.format_pval (bool or callable, default True) –
Falsekeeps the numeric p-values.Truereplaces them by APA strings without thep =prefix (".009","<.001";apatools.format.format_p()). A callable is applied to every p-value and its return value is used. The stars are always computed from the numeric p-values.add_stars (bool or callable, default True) –
False: nosigcolumn.True: add asigcolumn with significance stars (***p < .001,**p < .01,*p < .05,⁺p < .10, otherwise an empty string;apatools.format.get_stars()). A callable maps one p-value to the marker.decimal (int or None, default 3) – Round the columns
coef,se,cilandcirto this many decimals (the statistic and the p-values are not rounded here).Noneor 0: no rounding.add_ftest (bool, default True) – Include the corresponding part (F test, AIC, BIC,
LL,MAE,MAD,MAEpred,MADpred,N) in the fit summary string if the metric is available. R² (with its type, see above), R²adj and R²pred are always shown when available.add_aic (bool, default True) – Include the corresponding part (F test, AIC, BIC,
LL,MAE,MAD,MAEpred,MADpred,N) in the fit summary string if the metric is available. R² (with its type, see above), R²adj and R²pred are always shown when available.add_bic (bool, default True) – Include the corresponding part (F test, AIC, BIC,
LL,MAE,MAD,MAEpred,MADpred,N) in the fit summary string if the metric is available. R² (with its type, see above), R²adj and R²pred are always shown when available.add_llf (bool, default True) – Include the corresponding part (F test, AIC, BIC,
LL,MAE,MAD,MAEpred,MADpred,N) in the fit summary string if the metric is available. R² (with its type, see above), R²adj and R²pred are always shown when available.add_mae (bool, default True) – Include the corresponding part (F test, AIC, BIC,
LL,MAE,MAD,MAEpred,MADpred,N) in the fit summary string if the metric is available. R² (with its type, see above), R²adj and R²pred are always shown when available.add_mad (bool, default True) – Include the corresponding part (F test, AIC, BIC,
LL,MAE,MAD,MAEpred,MADpred,N) in the fit summary string if the metric is available. R² (with its type, see above), R²adj and R²pred are always shown when available.add_pred_loo_mae (bool, default True) – Include the corresponding part (F test, AIC, BIC,
LL,MAE,MAD,MAEpred,MADpred,N) in the fit summary string if the metric is available. R² (with its type, see above), R²adj and R²pred are always shown when available.add_pred_loo_mad (bool, default True) – Include the corresponding part (F test, AIC, BIC,
LL,MAE,MAD,MAEpred,MADpred,N) in the fit summary string if the metric is available. R² (with its type, see above), R²adj and R²pred are always shown when available.add_n_obs (bool, default True) – Include the corresponding part (F test, AIC, BIC,
LL,MAE,MAD,MAEpred,MADpred,N) in the fit summary string if the metric is available. R² (with its type, see above), R²adj and R²pred are always shown when available.add_panel_dims (bool, default True) – Append the number of entities and periods,
n = ..., T = ....intercept_name (str, default "Intercept") – Row label of the constant (
CONSTANTof spreg,constof linearmodels); other labels are unchanged.
- Returns:
list of pandas.DataFrame – One table per model, indexed by the coefficient names, with the columns
coef,se,z(spreg models other than pooled OLS) ort(pooled OLS and linearmodels),p-value,cil/cir(limits of the 95% confidence interval, confidence level 0.95: normal approximationcoef ∓ 1.96 · sefor spreg, the interval of linearmodels otherwise),sig(ifadd_stars) andmodel(fit summary, first row only, if metrics are given). Fixed effects are not listed as coefficients.
- apatools.plm.plm_effects(results, w=None, inference='simulation', n_draws=1000, seed=13, conf_level=0.95, traces='auto', n_probes=50, format_pval=False, add_stars=False, decimal=None)[source]¶
Direct, indirect and total effects of the regressors of the spatial lag panel models fitted with
plm().In a spatial lag model (
slm_fe,slm_re; every backend that fits them: spreg and splm; with spreg also the Durbin model ofslx_lags) the coefficient of a regressor is not its effect: a change in one entity also changes its neighbours throughρWy, and their neighbours in turn. LeSage & Pace (2009) summarize the effect matrix by three averages, which Elhorst (2014) uses for panels as well (the weightsWof the entities apply in every period): the direct effect (the change of an entity caused by a change of its own regressor, including the feedback through its neighbours), the total effect (the change of an entity caused by a unit change of the regressor in all entities) and the indirect effect, their difference (the spillover). The averages are computed from the traces of the powers ofW, without invertingI - ρW; for the Durbin model the effect matrix is(I - ρW)⁻¹ (β_k I + θ_k W).- Parameters:
results (list) – Fitted models from
plm(). Only the spatial lag models have these effects; the others are skipped with a warning (the coefficients of the spatial error models already are the direct and total effects).w (libpysal.weights.W, optional) – The weights of the entities; by default those stored with the results (the panel’s).
inference ({"simulation", "analytic"}, default "simulation") – How the standard errors, z values, p-values and confidence intervals are obtained.
"simulation": LeSage & Pace’s simulation,n_drawsdraws of the coefficients andρfrom their estimated joint normal distribution; the standard error is the standard deviation of the effects of the draws and the confidence interval is made of their percentiles (so it can be asymmetric)."analytic": the delta method with the gradient of the trace series (the interval is estimate ± z · se).n_draws – As in
apatools.slm.slm_effects().seed – As in
apatools.slm.slm_effects().conf_level – As in
apatools.slm.slm_effects().traces – As in
apatools.slm.slm_effects().n_probes – As in
apatools.slm.slm_effects().format_pval – As in
apatools.slm.slm_effects().add_stars – As in
apatools.slm.slm_effects().decimal – As in
apatools.slm.slm_effects().
- Returns:
pandas.DataFrame – One row per model, regressor and effect: the columns
model(the model name; a repeated one gets the suffix_2, …),variable,effect("Direct","Indirect","Total"),estimate,se,z,p-value,cil,cirand optionallysig.
Notes
The constant has no effect and is left out, as are the period effects of
effects="time"/"twoway"(they are not regressors). The standard errors use the covariance matrix of the coefficients andρof the backend: spreg’s covers the coefficients andρjointly, that of splm treatsρas uncorrelated with the coefficients, so the standard errors of the indirect and total effects differ somewhat between the backends. spreg’s estimates of an entity-effects model are those of the within estimator.The delta method (
inference="analytic") treats the effects as linear in the estimates. That holds whenρis estimated precisely; with few units and a largeρthe standard errors of the indirect and total effects can be far too small (in a 64-unit example with ρ = 0.6 the analytic standard error of an indirect effect was 0.44, against 1.48 by simulation with 100,000 draws and 1.43 in R’simpacts), so prefer the simulation then. The direct effect is much less sensitive. The simulated standard errors of the indirect and total effects are noisy in the same situation, because a few draws ofρnear its bound give huge effects: in that example the standard error of the indirect effect was 1.03 with 5000 draws and 1.48 with 100,000 (R’s own simulation behaves the same way). Raisen_drawsand check that the result is stable with anotherseed.References
LeSage, J., & Pace, R. K. (2009). Introduction to spatial econometrics. CRC Press. https://doi.org/10.1201/9781420064254 https://doi.org/10.1201/9781420064254
Elhorst, J. P. (2014). Spatial econometrics: From cross-sectional data to spatial panels. Springer. https://doi.org/10.1007/978-3-642-40340-8 https://doi.org/10.1007/978-3-642-40340-8
Examples
>>> results, metrics = plm(df, "y", ["x1", "x2"], w=w, entity="county", time="year", model="slm_fe") >>> plm_effects(results, inference="analytic", decimal=3)
- apatools.plm.hausman(r_fe, r_re)[source]¶
Hausman test of a fixed- against a random-effects model with the same spatial structure.
Compares the common slope coefficients:
H = d' (V_fe - V_re)⁻¹ d~ χ²(k). Works for both backends. Returns(statistic, df, p-value); statistic and p-value arenan(with a warning) ifV_fe - V_reis not positive definite. This is common when the effects are correlated with the predictors (the random-effects variance is then too large), i.e. exactly when the test should reject; usemundlak()in that case.- Parameters:
r_fe (fitted models) – Fixed- and random-effects results from
plm()of the same backend and spatial structure (e.g.feandre, orslm_feandslm_re). The statistic uses the slope coefficients (not the constant,rho,lambdaor variance parameters) present in both.r_re (fitted models) – Fixed- and random-effects results from
plm()of the same backend and spatial structure (e.g.feandre, orslm_feandslm_re). The statistic uses the slope coefficients (not the constant,rho,lambdaor variance parameters) present in both.
- Returns:
statistic (float) – The Hausman statistic
H.df (int) – Degrees of freedom, the number of compared slope coefficients.
p_value (float) –
P(χ²(df) > H).
- Raises:
ValueError – If there is no common slope coefficient.
References
Hausman, J. A. (1978). Specification tests in econometrics. Econometrica, 46(6), 1251-1271. https://doi.org/10.2307/1913827
- apatools.plm.mundlak(r_re)[source]¶
Mundlak test of correlated entity effects for a random-effects model.
The model is refitted with the entity means of the (time-varying) predictors added; a Wald test checks that their coefficients are jointly zero. Under the null the random-effects estimator is consistent. The test is the regression-based equivalent of the Hausman test for the slope coefficients, but it stays defined when
V_fe - V_reis not positive definite, which is typical when the effects are correlated with the predictors (the random-effects variance is then inflated), and it works for all random-effects models.- Parameters:
r_re (fitted random-effects model (
re,slm_re,sem_re_gm, …)) – Must come fromplm(), which stores the panel and the fitting options on it.- Returns:
statistic (float) – Wald statistic
b' V⁻¹ bof the coefficientsb(covarianceV) of the added<x>_meanregressors; only predictors that vary within entities get a mean.df (int) – Number of added regressors.
p_value (float) –
P(χ²(df) > statistic).
- Raises:
ValueError – If the model does not come from
plm()or no predictor varies over time.
References
Mundlak, Y. (1978). On the pooling of time series and cross section data. Econometrica, 46(1), 69-85. https://doi.org/10.2307/1913646
- apatools.plm.plm_tests(results, w=None, format_pval=False, add_stars=False, decimal=None)[source]¶
Specification tests for the models fitted with
plm(), as a tidy DataFrame.Computed where the required models are among
results:Hausman FE vs RE (
fe/re,slm_fe/slm_re,sem_fe/sem_re) for the common slope coefficients. Null: random effects are consistent. Omitted (with a warning) whenV_fe - V_reis not positive definite, seehausman().Mundlak test for every random-effects model, see
mundlak(). Null: the effects are uncorrelated with the predictors (random effects are consistent).F test of entity effects (
fevspooled, non-spatial, same backend). Null: no entity effects.Models with period effects (
effects="time"/"twoway"; Hausman and Mundlak need random-effects models with period effects, which are not available): F tests of period effects (twowayvsfe,timevspooled), of entity effects given period effects (twowayvstime) and of both (twowayvspooled), for the non-spatial models of the same backend that are amongresults; likelihood-ratio test of period effects (slm_fe/sem_fewithtwowayvs without,T - 1degrees of freedom). The Baltagi-Song-Koh and Anselin LM tests are available for the pooled model only. The likelihood-ratio statistic is multiplied by the residual degrees of freedom overN·T(the within likelihood countsN·Tobservations; unscaled it rejects 12-16 % of the time at the 5 % level in simulations withN= 36-100 andT= 6, scaled 6-7 %). Note: the F test of time effects againstpooledis conservative when the data have strong entity effects, because they inflate the pooled residuals (in simulations withN= 36,T= 6: 0 % rejections of true nulls at the 5 % level and 87 % power for time effects with an SD of half the error SD, against 7 % and 97 % fortwowayvsfe); with entity effects in the data prefer that entity-conditional test.Baltagi-Song-Koh LM tests (spreg, from
pooled; need weights): marginal random effects (LM1), marginal spatial error (LM2) and their joint test (LMJ), and the Anselin LM tests for a spatial lag / error (and their robust versions).
- Parameters:
w (libpysal.weights.W, optional) – Weights for the LM tests; by default those stored with the results.
format_pval (bool or callable, optional) –
Trueturns the p-values into APA strings (.633,<.001); a callable is used to format each p-value;False(default) keeps the numeric p-values.add_stars (bool or callable, optional) –
Trueadds asigcolumn with significance stars; a callable maps a p-value to the marker;False(default) adds no column. Computed from the numeric p-values.decimal (int, optional) – Rounds the
statisticcolumn to this many decimals;Noneor 0 (default) keeps the full precision. Thereportstrings are not affected.
- Returns:
pandas.DataFrame – Columns
test,model,statistic,df,df_denom,p-value(strings unlessformat_pval=False), optionallysig, and an APA-style stringreport. The table is empty (with these columns) if none of the tests applies toresults. Useformat_pval=False, add_stars=False, decimal=Nonefor the raw numbers.
Notes
The
modelcolumn holds the compared models ("fe vs re") or the model name.dfis None for the LM tests with one degree of freedom reported asLM;df_denomis set only for the F test. The Baltagi-Song-Koh and Anselin LM tests need spreg andw. The Baltagi-Song-Koh tests come from spreg (spreg.diagnostics_panel); the Anselin tests are computed here for the stacked pooled model (spreg’s panel versions differ from the textbook statistics). Both agree with R (plmtest,splm::slmtest).References
Hausman, J. A. (1978). Specification tests in econometrics. Econometrica, 46(6), 1251-1271. https://doi.org/10.2307/1913827
Mundlak, Y. (1978). On the pooling of time series and cross section data. Econometrica, 46(1), 69-85. https://doi.org/10.2307/1913646
Baltagi, B. H., Song, S. H., & Koh, W. (2003). Testing panel data regression models with spatial error correlation. Journal of Econometrics, 117(1), 123-150. https://doi.org/10.1016/s0304-4076(03)00120-9
Breusch, T. S., & Pagan, A. R. (1980). The Lagrange multiplier test and its applications to model specification in econometrics. The Review of Economic Studies, 47(1), 239-253. https://doi.org/10.2307/2297111
Anselin, L., Le Gallo, J., & Jayet, H. (2008). Spatial panel econometrics. In L. Mátyás & P. Sevestre (Eds.), The econometrics of panel data (pp. 625-660). Springer. https://doi.org/10.1007/978-3-540-75892-1_19