logit
Explains a yes/no outcome.
What we have
- the same factor notation as
regress - coefficients on the log-odds scale
Coming later
or, to print odds ratios instead of coefficientspredictandmarginsafterwards
How you write it
logit depvar indepvars [if]
Square brackets mean optional. A vertical bar means choose one.
What it does
When the column you are explaining is 0 or 1 — left or stayed, poor or not poor, passed or failed — a straight line is the wrong shape, because it will happily predict a probability of 1.4. Logistic regression fits an S-shaped curve that cannot leave the range 0 to 1.
The coefficients are on the log-odds scale, which is hard to read directly. What is easy to read is the sign (does this raise or lower the chance?) and, after exponentiating, the odds ratio: a value of 1.5 means the odds are half again as high.
Watch out. Odds ratios are not risk ratios. When the outcome is common, an odds ratio of 2 is a good deal less than twice the risk.
Try it
Every example below was run after sysuse vira.sample02, clear.
. generate poor = mpce < 2500
The same thing in pandas and in R
pandas
import numpy as np
import pandas as pd
def stata_missing(value):
"""Stata counts a missing value as larger than any number."""
if isinstance(value, pd.Series):
if pd.api.types.is_numeric_dtype(value):
return value.astype("float64").fillna(np.inf)
return value.fillna("")
if value is None or (isinstance(value, float) and np.isnan(value)):
return np.inf
return value
df["poor"] = (stata_missing(df["mpce"]) < 2500)
R
library(dplyr)
stata_missing <- function(x)
if (is.numeric(x)) ifelse(is.na(x), Inf, x) else ifelse(is.na(x), "", x)
df <- df %>% mutate(poor = (stata_missing(mpce) < 2500))
# This R was run in a real R (4.6.1) and gave the same numbers.
. logit poor age i.sector
Logistic regression Number of obs = 6,000
LR chi2 = 281.73
Prob > chi2 = 0.0000
Pseudo R2 = 0.0466
------------------------------------------------------------------------------
poor | Coefficient Std. err. z P>|z| [95% conf. interval]
-------------+----------------------------------------------------------------
sector=Urban | -1.266807 .08599801 -14.73 0.000 -1.43536 -1.098254
age | -.0074517 .00175454 -4.25 0.000 -.0108905 -.0040128
_cons | -.7060428 .08813655 -8.01 0.000 -.8787873 -.5332984
------------------------------------------------------------------------------
The same thing in pandas and in R
pandas
import statsmodels.formula.api as smf
model = smf.logit("poor ~ age + C(sector)", data=df).fit()
R
model <- glm(poor ~ age + factor(sector),
family = binomial(link = "logit"), data = df)
summary(model)
# This R was run in a real R (4.6.1) and gave the same numbers.