Postestimation and diagnostics
Start with the expanded example for each command. Open the variants for options and alternative R approaches. Read the qualifications before adapting the code.
brier
Calculate the overall Brier mean probability score
Stata
brier b pR Package:stats
mean((data$b-data$p)^2)Differs from Stata Returns the overall score only; Stata brier also reports decomposition components.
dfbeta
Obtain standardized deletion influence on one slope
Stata
dfbeta xR Package:stats
stats::dfbetas(fit)[,"x"]Differs from Stata Returns standardized coefficient-deletion diagnostics from dfbetas for x; coefficient ordering, missing rows and diagnostic naming must be aligned with the Stata model.
estat
Test heteroskedasticity against one predictor using a studentized statistic
Stata
estat hettest x, iidR Package:lmtest
lmtest::bptest(fit,varformula=~x,data=data,studentize=TRUE)Differs from Stata Uses the studentized Koenker version of the Breusch-Pagan test, corresponding to the iid variant shown. Match the auxiliary regressors and estimation sample; the default bptest differs from default Stata hettest.
9 more examples and alternatives
Run the classical Breusch-Pagan heteroskedasticity test
Stata
estat hettest, rhsR Package:lmtest
lmtest::bptest(fit,studentize=FALSE)Differs from Stata studentize=FALSE selects the normal-theory version; default bptest uses the Koenker version.
Compare penalized-likelihood model criteria
Stata
estat icR Package:stats
c(AIC=stats::AIC(fit),BIC=stats::BIC(fit))R keeps fitted model objects; model names are fixed workflow labels.
Run a White-style auxiliary-regression heteroskedasticity test
Stata
estat imtest, whiteR Package:lmtest
lmtest::bptest(fit,varformula=~x+z+I(x^2)+I(z^2)+x:z,data=data,studentize=TRUE)This covers the White heteroskedasticity component, not the complete information-matrix decomposition.
Run Ramsey RESET using powers of fitted values
Stata
estat ovtestR Package:lmtest
lmtest::resettest(fit,power=2:4,type="fitted")Differs from Stata Uses RESET powers two through four of the fitted values or regressors as shown. Regressor-factor expansion and rank-deficient auxiliary terms may differ from Stata.
Run RESET using powers of regressors
Stata
estat ovtest, rhsR Package:lmtest
lmtest::resettest(fit,power=2:4,type="regressor")Differs from Stata Uses RESET powers two through four of the fitted values or regressors as shown. Regressor-factor expansion and rank-deficient auxiliary terms may differ from Stata.
Summarize variables in the actual estimation sample
Stata
estat summarizeR Package:stats
summary(stats::model.frame(fit))R keeps fitted model objects; model names are fixed workflow labels.
Extract the coefficient covariance matrix
Stata
estat vceR Package:stats
stats::vcov(fit)R keeps fitted model objects; model names are fixed workflow labels.
Extract correlations among coefficient estimates
Stata
estat vce, correlationR Package:stats
stats::cov2cor(stats::vcov(fit))R keeps fitted model objects; model names are fixed workflow labels.
Compute variance inflation factors after OLS
Stata
estat vifR Package:car
car::vif(fit)Differs from Stata car returns ordinary VIFs for one-degree-of-freedom terms and generalized VIFs for multi-parameter terms. Stata estat vif reports column-level VIFs, so factor-term output is not directly interchangeable.
estimates
List stored model names
Stata
estimates dirR Package:stats
names(models)R keeps fitted model objects; model names are fixed workflow labels.
6 more examples and alternatives
Redisplay a fitted linear model summary
Stata
estimates replayR Package:stats
summary(fit)R keeps fitted model objects; model names are fixed workflow labels.
Restore one model from a model collection
Stata
estimates restore model1R Package:stats
fit <- models[["model1"]]R keeps fitted model objects; model names are fixed workflow labels.
Save and reload a fitted model object
Stata
estimates save model1R Package:base
{ path <- tempfile(fileext=".rds"); saveRDS(fit,path); readRDS(path) }Writes to an R temporary file; choose an explicit project path for persistent storage.
Compare AIC across stored model objects
Stata
estimates stats model1 model2R Package:stats
do.call(stats::AIC,unname(models))R keeps fitted model objects; model names are fixed workflow labels.
Store a fitted model under a name
Stata
estimates store model1R Package:stats
model1 <- fitR keeps fitted model objects; model names are fixed workflow labels.
Compare coefficients and standard errors across models
Stata
estimates table model1 model2, b seR Package:stats
lapply(models,function(m) summary(m)$coefficients[,1:2,drop=FALSE])R keeps fitted model objects; model names are fixed workflow labels.
lincom
Estimate the sum of two slopes with its standard error
Stata
lincom x + zR Package:stats
{ L <- c(0,1,1); c(estimate=sum(L*stats::coef(fit)),se=sqrt(drop(t(L)%*%stats::vcov(fit)%*%L))) }Differs from Stata The contrast vector assumes coefficient order intercept, x, z. Returns the estimate and its covariance-based standard error only; Stata also prints tests and confidence limits.
1 more examples and alternatives
Estimate a difference of slopes with its standard error
Stata
lincom x - zR Package:stats
{ L <- c(0,1,-1); c(estimate=sum(L*stats::coef(fit)),se=sqrt(drop(t(L)%*%stats::vcov(fit)%*%L))) }Differs from Stata The contrast vector assumes coefficient order intercept, x, z. Returns the estimate and its covariance-based standard error only; Stata also prints tests and confidence limits.
linktest
Regress an outcome on fitted values and their square
Stata
linktestR Package:stats
{ data$hat <- stats::fitted(fit); stats::lm(y ~ hat+I(hat^2),data=data) }Shown for OLS; link tests after other model families must refit the appropriate family.
lrtest
Compare nested maximum-likelihood models
Stata
lrtest reduced fullR Package:lmtest
lmtest::lrtest(reduced,full)Differs from Stata Fixed workflow.
margins
Predict at specified covariate values
Stata
margins, at(x=(2 3 4))R Package:stats
vapply(c(2,3,4),function(value) { newdata <- data; newdata$x <- value; mean(stats::predict(fit,newdata=newdata,type="response")) },numeric(1))Differs from Stata At each x value, predictions are averaged over the observed distribution of z.
3 more examples and alternatives
Average a continuous-predictor marginal effect
Stata
margins, dydx(x)R Package:stats
{ X <- stats::model.matrix(fit); beta <- stats::coef(fit); p <- stats::fitted(fit); gradient <- beta["x"]*colMeans(X*as.vector(p*(1-p)*(1-2*p))); gradient["x"] <- gradient["x"]+mean(p*(1-p)); c(estimate=unname(beta["x"]*mean(p*(1-p))),se=sqrt(drop(t(gradient)%*%stats::vcov(fit)%*%gradient))) }Differs from Stata Uses the fitted GLM and its estimation data; reference grids and averaging rules should be chosen explicitly.
Evaluate a marginal effect at mean covariates
Stata
margins, dydx(x) atmeansR Package:stats
{ X <- colMeans(stats::model.matrix(fit)); beta <- stats::coef(fit); p <- stats::plogis(sum(X*beta)); c(estimate=unname(beta["x"]*p*(1-p))) }Differs from Stata Returns the derivative at means; use a delta-method gradient if standard errors are needed.
Average predictions on the linear-index scale
Stata
margins, expression(predict(xb))R Package:stats
{ L <- colMeans(stats::model.matrix(fit)); c(estimate=sum(L*stats::coef(fit)),se=sqrt(drop(t(L)%*%stats::vcov(fit)%*%L))) }Differs from Stata Uses the fitted GLM and its estimation data; reference grids and averaging rules should be chosen explicitly.
nlcom
Use the delta method for a ratio of slopes
Stata
nlcom _b[x]/_b[z]R Package:car
car::deltaMethod(fit,"x / z")Differs from Stata Uses the first-order delta method on named fitted coefficients. Returns the transformed estimate and standard error; Stata also prints reference tests and confidence limits.
1 more examples and alternatives
Use the delta method for an exponentiated slope
Stata
nlcom exp(_b[x])R Package:car
car::deltaMethod(fit,"exp(x)")Differs from Stata Uses the first-order delta method on named fitted coefficients. Returns the transformed estimate and standard error; Stata also prints reference tests and confidence limits.
predict
Obtain Cook influence distances
Stata
predict result, cooksdR Package:stats
data$result <- stats::cooks.distance(fit)Differs from Stata Run after fit <- lm(y ~ x + z, data=data).
12 more examples and alternatives
Compute binary-model deviance residuals
Stata
predict result, devianceR Package:stats
data$result <- stats::residuals(fit,type="deviance")Differs from Stata After fitting a binary-response GLM. Prediction options are model-specific.
Obtain DFFITS influence statistics
Stata
predict result, dfitsR Package:stats
data$result <- stats::dffits(fit)Differs from Stata Run after fit <- lm(y ~ x + z, data=data).
Obtain leverage values
Stata
predict result, hatR Package:stats
data$result <- stats::hatvalues(fit)Differs from Stata Run after fit <- lm(y ~ x + z, data=data).
Compute binary-model Pearson residuals
Stata
predict result, pearsonR Package:stats
data$result <- stats::residuals(fit,type="pearson")Differs from Stata After fitting a binary-response GLM. Prediction options are model-specific.
Predict logistic probabilities
Stata
predict result, prR Package:stats
data$result <- stats::predict(fit,type="response")Differs from Stata After fitting a binary-response GLM. Prediction options are model-specific.
Obtain raw OLS residuals
Stata
predict result, residualsR Package:stats
data$result <- stats::residuals(fit)Differs from Stata Run after fit <- lm(y ~ x + z, data=data).
Obtain internally standardized residuals
Stata
predict result, rstandardR Package:stats
data$result <- stats::rstandard(fit)Differs from Stata Run after fit <- lm(y ~ x + z, data=data).
Obtain externally studentized residuals
Stata
predict result, rstudentR Package:stats
data$result <- stats::rstudent(fit)Differs from Stata Run after fit <- lm(y ~ x + z, data=data).
Obtain forecast standard errors including residual variance
Stata
predict result, stdfR Package:stats
data$result <- sqrt(stats::predict(fit,se.fit=TRUE)$se.fit^2+summary(fit)$sigma^2)Differs from Stata Adds residual variance to the squared standard error of the fitted OLS mean. This is a standard error for a new individual prediction, not the fitted mean; assumes homoskedastic errors and matching model sample.
Obtain standard errors of fitted means
Stata
predict result, stdpR Package:stats
data$result <- stats::predict(fit,se.fit=TRUE)$se.fitDiffers from Stata Run after fit <- lm(y ~ x + z, data=data).
Obtain linear fitted values
Stata
predict result, xbR Package:stats
data$result <- stats::predict(fit)Differs from Stata Run after fit <- lm(y ~ x + z, data=data).
Predict logistic linear indices
Stata
predict result, xbR Package:stats
data$result <- stats::predict(fit,type="link")Differs from Stata After fitting a binary-response GLM. Prediction options are model-specific.
roccomp
Compare paired marker ROC areas using DeLong inference
Stata
roccomp b x zR Package:pROC
pROC::roc.test(pROC::roc(data$b,data$x,levels=c(0,1),direction="<",quiet=TRUE),pROC::roc(data$b,data$z,levels=c(0,1),direction="<",quiet=TRUE),paired=TRUE,method="delong")Differs from Stata Both markers must be measured on the same complete-case subjects for paired inference.
roctab
Estimate a nonparametric ROC area for a marker
Stata
roctab b xR Package:pROC
pROC::roc(data$b,data$x,levels=c(0,1),direction="<",quiet=TRUE)Differs from Stata Explicit direction means larger markers indicate cases; fixing direction prevents data-driven reversal.
Tabulate sensitivity and specificity across ROC thresholds
Stata
roctab b x, detailR Package:pROC
pROC::coords(pROC::roc(data$b,data$x,levels=c(0,1),direction="<",quiet=TRUE),x="all",ret=c("threshold","sensitivity","specificity"))Differs from Stata Returns all pROC thresholds with sensitivity and specificity for explicit event direction. Threshold locations and endpoint conventions differ from Stata roctab detail cutpoints.
test
Test a single regression coefficient
Stata
test x = 0R Package:car
car::linearHypothesis(fit,"x = 0")Differs from Stata Tests the specified coefficient restriction on the existing fit. car selects its reference statistic from the model class; a GLM chi-square test differs from the OLS F test used by Stata regress postestimation.
2 more examples and alternatives
Test equality of two regression slopes
Stata
test x = zR Package:car
car::linearHypothesis(fit,"x = z")Differs from Stata Tests the specified coefficient restriction on the existing fit. car selects its reference statistic from the model class; a GLM chi-square test differs from the OLS F test used by Stata regress postestimation.
Jointly test two regression coefficients
Stata
test x zR Package:car
car::linearHypothesis(fit,c("x = 0","z = 0"))Differs from Stata Tests the specified coefficient restriction on the existing fit. car selects its reference statistic from the model class; a GLM chi-square test differs from the OLS F test used by Stata regress postestimation.
testnl
Test an exponentiated coefficient with a nonlinear Wald test
Stata
testnl exp(_b[x]) = 1R Package:car
{ d <- car::deltaMethod(fit,"exp(x)"); w <- ((d$Estimate-1)/d$SE)^2; c(chisq=w,p.value=stats::pchisq(w,df=1,lower.tail=FALSE)) }Differs from Stata Forms a one-degree-of-freedom Wald chi-square from a first-order delta-method standard error. The R vector omits Stata coefficient and confidence-interval output.
testparm
Jointly test a categorical predictor
Stata
testparm i.gR Package:car
car::linearHypothesis(fit,c("g6 = 0","g8 = 0"))Differs from Stata The restrictions name the fitted factor coefficients explicitly. Different reference levels or contrasts require different coefficient names; this is not an automatic expansion of any Stata factor-variable expression.