Written and maintained by CASRAI Editorial Board
Published
On this page
The stargazer package in R generates publication-ready regression tables and descriptive summary statistics formatted directly in LaTeX code, HTML markup, or plain ASCII text. Created by political scientist and statistician Marek Hlavac, the package solves a ubiquitous empirical workflow bottleneck by consolidating outputs from multiple statistical models side by side into standardized academic layouts with automatic significance asterisks, customizable variable labels, and user-supplied robust standard errors.
In empirical economics, political science, sociology, and quantitative research, investigators routinely estimate dozens of competing model specifications—varying covariates, interaction terms, fixed effects, and estimation techniques. Hand-transcribing regression coefficients, standard errors, test statistics, and sample sizes into presentation tables is not only tedious but also introduces severe risks of human transcription error. By linking directly into R statistical objects, stargazer automates this reporting pipeline, producing publication-quality typesetting that integrates smoothly into LaTeX manuscripts, web reports, and Microsoft Word documents.
What it is used for in research
Academic peer review demands transparent, comparative reporting across empirical models. Quantitative manuscripts rarely present a single regression specification; researchers must demonstrate how coefficients respond as control variables are introduced, alternative functional forms are evaluated, or sub-samples are inspected. The stargazer package fulfills three vital research functions across disciplines:
Multi-Model Comparative Reporting
The primary research application of stargazer is aligning multiple regression estimates in adjacent columns under a unified header. In traditional journals, empirical papers report baseline bivariate models in Column 1, expanded multivariate specifications in Column 2, fixed-effects or instrumental-variable estimates in Column 3, and sensitivity checks in subsequent columns. Stargazer automatically extracts model coefficients, identifies identical regressors across distinct objects, aligns corresponding estimates across rows, and places standard errors or t-statistics in parentheses underneath. This side-by-side architecture lets reviewers and readers instantly evaluate parameter stability, sign changes, and shifts in statistical significance across specifications.
Native Support for Diverse Statistical Estimators
Unlike basic formatting functions limited to ordinary least squares, stargazer provides out-of-the-box compatibility with an extensive library of R modeling classes. The package natively parses linear models from lm(), generalized linear models from glm function in R, panel data regressions from plm, instrumental variable specifications from AER::ivreg, multinomial logit models from nnet::multinom, quantile regressions from quantreg::rq, ordered probit and logit from MASS::polr, and survival models from survival::survreg and survival::coxph. Investigators working on binary outcomes such as logistic regression in R can present odds ratios or log-odds coefficients alongside linear benchmarks without changing their reporting pipeline.
Automated Descriptive Summary Tables
Before presenting inferential findings, quantitative manuscripts require descriptive overview tables—often termed ‘Table 1’—summarizing the central tendency and dispersion of key variables. When supplied with a raw data frame rather than fitted model objects, stargazer computes variable-level summary statistics including sample sizes (N), means, standard deviations, minimum values, maximum values, and specified percentiles (such as the 25th and 75th percentiles). Researchers can customize the exact set of descriptive statistics displayed, suppress non-numeric factors, and export the resulting table directly to their manuscript build pipeline.
Install or access
The stargazer package is distributed through the Comprehensive R Archive Network (CRAN) as an open-source library under the GNU General Public License (GPL version 2 or later). Researchers can install and verify the package using standard library management procedures in any active R console or RStudio session.
Official CRAN Installation
To install the stable release of stargazer from CRAN, execute the standard installation command without external binary downloads:
# Install stargazer from official CRAN mirrors
install.packages("stargazer")
For detailed guidance on mirror selection, local library paths, and troubleshooting network dependencies during package installation, consult our dedicated guide on how to install libraries in R.
Loading the Library and Verifying Version
After installation completes, load the package into your active R environment. Upon loading, stargazer outputs a short startup banner identifying the author, package version, and official citation metadata:
# Load the library
library(stargazer)
# Verify package version
packageVersion("stargazer")
# Expected output: [1] '5.2.3'
If you prefer to silence the package startup message in automated reporting scripts, render pipelines, or R Markdown headers, wrap the library call with suppressPackageStartupMessages(library(stargazer)).
Step-by-step task
This worked example walks through estimating multiple regression specifications on standard empirical data, extracting robust covariance structures, formatting variable labels, and exporting publication-ready tables in ASCII, LaTeX, and HTML. We use the built-in Swiss fertility and socioeconomic dataset (swiss) to demonstrate a complete academic analysis.
Step 1: Prepare Data and Fit Competing Regression Models
First, load your dataset and estimate several nested linear models. Here we model the standardized fertility measure against education, agricultural employment, Catholic demographic proportion, and infant mortality:
# Load datasets and ensure data is a standard data.frame
data(swiss)
df = as.data.frame(swiss)
# Model 1: Bivariate baseline
m1 = lm(Fertility ~ Education, data = df)
# Model 2: Multivariate economic model
m2 = lm(Fertility ~ Education + Agriculture, data = df)
# Model 3: Full structural specification
m3 = lm(Fertility ~ Education + Agriculture + Catholic + Infant.Mortality, data = df)
Step 2: Generate an ASCII Console Preview Table
During exploratory data analysis, researchers need immediate console previews without compiling LaTeX documents or rendering web browsers. Setting type = 'text' renders a clean ASCII table directly in the R console:
# Preview side-by-side models in console
stargazer(m1, m2, m3, type = "text", title = "Regression Analysis: Swiss Fertility")
Stargazer inspects all three models, recognizes that Education is common to all three specifications while Catholic and Infant.Mortality are unique to Model 3, aligns the coefficients vertically, calculates standard errors, and appends model fit metrics at the bottom.
Step 3: Customize Labels, Omit Statistics, and Set Digits
Raw variable names from statistical code (such as Infant.Mortality) look unprofessional in journal submissions. Use covariate.labels to provide formal typography and dep.var.labels to name the outcome variable. Furthermore, academic journals frequently request that authors omit superfluous test statistics like the F-statistic or Residual Standard Error to preserve horizontal space:
# Refine table presentation and variable labels
stargazer(
m1, m2, m3,
type = "text",
title = "Table 2: Determinants of Fertility in 19th Century Switzerland",
dep.var.labels = "Standardized Fertility Index",
covariate.labels = c(
"Education (% Beyond Primary)",
"Agriculture (% Men in Agriculture)",
"Catholic (% Catholic Population)",
"Infant Mortality (% Live Births)",
"Constant"
),
omit.stat = c("ser", "f"),
digits = 3,
star.cutoffs = c(0.05, 0.01, 0.001)
)
Notice that covariate.labels must match the exact number and order of independent variables displayed in the table, including the constant term if the intercept is reported. If you wish to exclude the intercept from the table entirely, add intercept.bottom = FALSE or filter it using regular expressions via omit = "Constant".
Step 4: Incorporate Heteroskedasticity-Robust Standard Errors
Cross-sectional econometric models frequently violate homoskedasticity assumptions. Standard OLS standard errors underestimate variance under heteroskedasticity, leading to inflated t-statistics and spurious significance. Rather than re-fitting models with complex wrappers, stargazer allows authors to inject robust covariance vectors directly via the se argument:
# Compute White-Huber robust standard errors using the sandwich package
library(sandwich)
# Extract square root of variance-covariance diagonal (HC1)
se_m1 = sqrt(diag(vcovHC(m1, type = "HC1")))
se_m2 = sqrt(diag(vcovHC(m2, type = "HC1")))
se_m3 = sqrt(diag(vcovHC(m3, type = "HC1")))
# Supply robust standard errors as a list matching the model sequence
stargazer(
m1, m2, m3,
type = "text",
se = list(se_m1, se_m2, se_m3),
title = "Regression Results with HC1 Robust Standard Errors",
dep.var.labels = "Fertility Index",
omit.stat = c("ser", "f")
)
Supplying the se parameter automatically updates both the parenthesized numbers beneath each coefficient and the significance stars, ensuring that hypothesis tests conform exactly to robust econometric standards.
Step 5: Export to LaTeX and HTML Files
For publication workflows, tables must be written to external files rather than printed to the console. The out parameter redirects output directly to disk:
# Export to standalone LaTeX fragment for inclusion via input{table1.tex}
stargazer(
m1, m2, m3,
type = "latex",
out = "tables/regression_table.tex",
title = "Determinants of Swiss Fertility",
label = "tab:fertility_regressions",
align = TRUE,
no.space = TRUE
)
# Export to HTML for direct import into Microsoft Word or web publishing
stargazer(
m1, m2, m3,
type = "html",
out = "tables/regression_table.html",
title = "Determinants of Swiss Fertility"
)
Setting align = TRUE in LaTeX mode enables alignment around the decimal point via the LaTeX dcolumn package, producing crisp, professional typesetting. The resulting .html file can be opened in any web browser, copied with standard clipboard operations, and pasted directly into Microsoft Word while preserving column structure and cell borders.
Output and how to read it
Stargazer structures its regression output into three distinct horizontal panels: the header block, the coefficient block, and the summary statistics block. Understanding the exact information conveyed in each section ensures accurate manuscript interpretation.
The Header Block
The top section displays the overall table title, the dependent variable label, and numbered column headers corresponding to each model object passed into the function (such as (1), (2), and (3)). Above the column numbers, stargazer indicates the estimation model type (such as OLS for lm or logistic for binary GLMs). If multiple dependent variables are evaluated across different columns, stargazer groups columns under separate multi-column headers automatically.
The Coefficient and Standard Error Block
The middle panel contains the estimated parameters for each covariate:
- Point Estimate: The top number in each variable block represents the point coefficient (slope or intercept). By default, stargazer reports coefficients rounded to three decimal places (modifiable via the
digitsargument). - Standard Error or Confidence Interval: The number in parentheses immediately beneath the point estimate represents the standard error of the coefficient. By passing
ci = TRUE, researchers can replace standard errors with bracketed confidence intervals (for example,[-0.412, -0.108]). - Significance Stars: Asterisks placed to the right of point estimates denote two-tailed p-value thresholds. By default, stargazer follows conventional social science standards:
*p ≤ 0.10,**p ≤ 0.05, and***p ≤ 0.01. These thresholds can be adjusted using thestar.cutoffsparameter.
The Summary Statistics Block
The bottom panel compiles model diagnostic statistics across specifications. Common reported metrics include:
- Observations (N): The total number of observations utilized in model estimation, accounting for listwise deletion of missing values.
- R-Squared and Adjusted R-Squared: The proportion of variance explained by model regressors, along with the degree-of-freedom penalized adjusted metric.
- Residual Standard Error: The estimated standard deviation of the error term, accompanied by residual degrees of freedom.
- F-Statistic: The overall test of joint explanatory significance against an intercept-only null model.
- Log-Likelihood, AIC, and BIC: For maximum likelihood and generalized linear models, information criteria allow quantitative model selection.
At the very bottom of the table, stargazer prints an explanatory notes footer defining the significance threshold symbols. Custom notes can be appended using notes = "Standard errors clustered at the district level in parentheses." and formatted with notes.append = FALSE to replace default verbiage.
Rendering in R Markdown and Quarto Documents
When compiling reproducible reports using knitr, R Markdown, or Quarto, stargazer generates raw markup (LaTeX or HTML) rather than graphical plots. If a code chunk is run with default parameters, knitr treats the markup as literal text, causing code tags like begin{table} to appear verbatim in the compiled document.
To render tables correctly, you must specify results = 'asis' in the code chunk header:
```{r, echo = FALSE, results = 'asis'}
# Chunk header with results = 'asis' ensures raw markup is rendered as a table
stargazer(m1, m2, m3, type = ifelse(knitr::is_latex_output(), "latex", "html"))
```
Troubleshooting
Because stargazer was designed during earlier iterations of the R ecosystem, modern data manipulation practices—particularly those relying on the tidyverse—can occasionally trigger unexpected errors or formatting failures. Below are proven solutions to the most common operational challenges.
Tibble Compatibility and ‘argument is of length zero’ Errors
When analysts pass modern tidyverse data structures (tibble or tbl_df) directly into stargazer() for summary statistics, the function often fails with cryptic messages such as Error in if (is.na(s)) {: argument is of length zero or index subsetting exceptions. This occurs because stargazer relies internally on legacy base R data.frame subsetting mechanics where single-bracket indexing drops dimensions down to a vector. In contrast, tibbles preserve their two-dimensional structure upon subsetting.
Resolution: Always explicitly convert tibbles or data tables to standard base R data frames before passing them to stargazer:
library(dplyr)
# Data manipulation pipeline using dplyr
clean_data = swiss %>%
filter(Education >= 5) %>%
mutate(High_Fertility = ifelse(Fertility >= 70, 1, 0))
# Convert tibble to standard base data.frame before calling stargazer
stargazer(as.data.frame(clean_data), type = "text", summary = TRUE)
For comprehensive data frame filtering, variable creation, and pipeline best practices, see our guide to the dplyr package in R.
Vector Length Mismatch in Covariate Labels
Another frequent error is Error in covariate.labels: number of labels does not match number of covariates. Stargazer requires that the character vector provided to covariate.labels matches the exact count of unique independent variables appearing across all models, in the order they are introduced.
Resolution: Check the raw order of variables by running a baseline preview without custom labels first. If your models include an intercept and intercept.bottom = TRUE (the default), remember to provide a label for the constant term at the end of the vector. If specific variables are omitted using omit = c(...), reduce the length of covariate.labels accordingly.
LaTeX Compilation Failures: Missing dcolumn Package
When exporting LaTeX tables with decimal alignment enabled (align = TRUE), compiling the master document with pdflatex or xelatex may fail with errors such as LaTeX Error: File 'dcolumn.sty' not found or syntax errors around column specifiers.
Resolution: Ensure your LaTeX document preamble includes the dcolumn package:
% Add to your LaTeX document preamble
usepackage{dcolumn}
Alternatively, if you cannot modify the LaTeX preamble or are writing for a journal template that restricts external style files, set align = FALSE in the stargazer() function call to format numbers using standard text column specifiers.
Robust Standard Error Vector Misalignment
When injecting custom standard errors using se = list(...), authors sometimes encounter misaligned significance stars or subscript errors. This occurs when the length of the extracted standard error vector does not match the number of coefficients in that specific model.
Resolution: Ensure that your standard error extraction vector preserves coefficient names and order. Always verify that length(se_vector) == length(coef(model)). If one of your models drops a collinear regressor, the variance-covariance matrix returned by vcovHC() will exclude that parameter, necessitating careful verification of vector lengths before building the list.
Free alternatives
While stargazer remains a widely used benchmark in quantitative social science, several modern open-source R packages offer compelling alternative approaches to regression presentation and tabular reporting. The table below outlines leading free alternatives available on CRAN, their design paradigms, and optimal research use cases.
| Package | Primary Focus | Supported Output Formats | Robust Standard Error Syntax | Best Research Use Case |
|---|---|---|---|---|
| modelsummary | Modern statistical tables and data summaries | LaTeX, HTML, Microsoft Word, Typst, Markdown, PDF | Native vcov = 'HC1' argument |
Complex econometric modeling, Quarto publishing, multi-format manuscripts |
| gtsummary | Publication-ready summary and regression tables | HTML, LaTeX, Word, RTF | Integrated via tbl_regression() and survey weighting |
Biomedical research, clinical trial baseline tables, epidemiology |
| texreg | Conversion of statistical models to LaTeX/HTML | LaTeX, HTML, ASCII, Word | Custom override via override.se |
Network analysis, political science, custom model classes |
| flextable | Precision tabular layout and formatting | Word, PowerPoint, HTML, PDF | Pairs with tidy model output (broom) | Regulatory reporting, corporate analytics, corporate presentations |
| kableExtra | Extended knitr table formatting | HTML, LaTeX | Requires external model summarization | Direct R Markdown document styling, customized table headers |
For clinical trial investigators and biostatisticians requiring automated p-values and patient demographic overviews, our dedicated guide to gtsummary in R demonstrates how to construct reproducible Table 1 summaries. Researchers needing pixel-perfect formatting for executive slide decks and Microsoft Word documents can explore the flextable in R framework.
The data table below compares the technical specifications, formatting capabilities, and model compatibility across standard R statistical table packages.
Frequently asked questions
How do you export a stargazer table to Microsoft Word?
To export a stargazer table to Microsoft Word, set type = 'html' and provide a file path via the out parameter (for example, stargazer(model1, model2, type = 'html', out = 'table1.html')). Open the resulting .html file in any modern web browser, press Ctrl+A (or Cmd+A) to select the table, copy it, and paste it directly into your Microsoft Word manuscript. Alternatively, you can open the .html file directly within Microsoft Word by selecting File → Open and choosing HTML Document; Word converts the table into native Word table formatting with editable cells and borders.
Why does stargazer output raw code instead of a formatted table in R Markdown?
Stargazer outputs raw LaTeX or HTML markup rather than rendered graphical widgets. By default, knitr escapes character output from R code chunks so that markup characters display as plain text. To instruct knitr to pass the raw markup directly to the markdown parser without escaping, add results = 'asis' to the R code chunk header (such as ```{r, results = 'asis'}). When compiling to PDF, set type = 'latex'; when compiling to HTML or Word documents, set type = 'html'.
How do you pass clustered or robust standard errors into stargazer?
Extract the square root of the diagonal from a robust variance-covariance matrix (computed using packages such as sandwich or clubSandwich) and pass the resulting standard error vectors as a list to the se argument. For example, with two models, compute se1 = sqrt(diag(vcovHC(m1, type = 'HC1'))) and se2 = sqrt(diag(vcovHC(m2, type = 'HC1'))), then execute stargazer(m1, m2, se = list(se1, se2)). Stargazer replaces the default OLS standard errors and recalculates significance asterisks automatically.
Can stargazer format tidyverse tibbles directly?
No, stargazer does not natively support tidyverse tibbles (objects of class tbl_df) when generating summary statistics tables. Tibbles handle column indexing differently than standard base R data frames, causing stargazer to throw errors such as argument is of length zero. To summarize a tibble with stargazer, wrap the object in as.data.frame() before passing it to the function: stargazer(as.data.frame(my_tibble), type = 'text').
How do you omit control variables or fixed effects in stargazer?
Use the omit argument with a regular expression matching the variable names you wish to suppress from the table. For example, setting omit = c('factor\(year\)', 'factor\(state\)') hides all dummy coefficients for year and state fixed effects. Stargazer automatically adds an informational line at the bottom of the table indicating that year and state controls were included. You can customize the omission labels using omit.labels = c('Year Fixed Effects', 'State Fixed Effects') and set omit.yes.no = c('Yes', 'No').
How do you modify the significance star thresholds in stargazer?
By default, stargazer assigns stars at p-value thresholds of 0.10 (*), 0.05 (**), and 0.01 (***). To adopt alternative conventions—such as two-star thresholds or stricter significance boundaries—supply a numeric vector of length three in descending order to star.cutoffs. For example, to set thresholds at 0.05, 0.01, and 0.001, specify star.cutoffs = c(0.05, 0.01, 0.001). Stargazer updates the coefficients and modifies the table footer text to reflect your chosen alpha levels.
Sources
- Marek Hlavac. (2022). stargazer: Well-Formatted Regression and Summary Statistics Tables. R package version 5.2.3. https://cran.r-project.org/package=stargazer (Accessed 2026-11-15).
- Comprehensive R Archive Network (CRAN). (2022). Package ‘stargazer’ Reference Manual. https://cran.r-project.org/web/packages/stargazer/stargazer.pdf (Accessed 2026-11-15).
- Vincent Arel-Bundock. (2024). modelsummary: Data and Model Summaries in R. Journal of Statistical Software, 103(1), 1-23. https://modelsummary.com (Accessed 2026-11-15).
- Daniel D. Sjoberg, Karissa Whiting, Michael Curry, Jessica A. Lavery, Joseph Larmarange. (2021). Reproducible Summary Tables with the gtsummary Package. The R Journal, 13(1), 570-580. https://journal.r-project.org/archive/2021/RJ-2021-053/index.html (Accessed 2026-11-15).
- Philip Leifeld. (2013). texreg: Conversion of Statistical Model Output in R to LaTeX and HTML Tables. Journal of Statistical Software, 55(8), 1-24. https://www.jstatsoft.org/article/view/v055i08 (Accessed 2026-11-15).
- Achim Zeileis. (2004). Econometric Computing with HC and HAC Covariance Matrix Estimators. Journal of Statistical Software, 11(10), 1-17. https://www.jstatsoft.org/article/view/v011i10 (Accessed 2026-11-15).
Data: Comparison of R Statistical Table Packages for Academic Research
Comparative technical specifications and feature support for R academic reporting packages compiled from CRAN package manuals and peer-reviewed documentation.
| Package | Latest Version | Output Formats | Direct vcov Argument | Tibble Compatibility | Summary Statistics Mode | Primary Academic Domains |
|---|---|---|---|---|---|---|
| stargazer | 5.2.3 | LaTeX, HTML, ASCII text | No (requires manual se vector in list) | Partial (requires as.data.frame for summary tables) | Yes | Economics, Political Science, Empirical Finance |
| modelsummary | 2.2.0 | LaTeX, HTML, Word, Typst, Markdown, PDF | Yes (native sandwich and clubSandwich support) | Full (native tidyverse support) | Yes (datasummary module) | Social Sciences, Econometrics, Biostatistics |
| gtsummary | 2.0.2 | HTML, LaTeX, Word, RTF | Yes (via tbl_regression and survey) | Full (built on tidyverse and gt) | Yes (tbl_summary module) | Clinical Trials, Medicine, Epidemiology |
| texreg | 1.39.4 | LaTeX, HTML, ASCII text, Microsoft Word | Yes (custom override via override.se) | Full (standard data structures) | No (model output only) | Sociology, Political Science, Network Analysis |
| flextable | 0.9.6 | Word, PowerPoint, HTML, PDF | No (tabular formatting engine, pairs with broom) | Full (native data frame and tibble formatting) | Yes (via descriptive helper workflows) | Pharmaceutical Reporting, Regulatory Submissions |
Sources
- CRAN stargazer package repository (accessed 2026-11-15)
- modelsummary documentation (accessed 2026-11-15)
- gtsummary R Journal publication (accessed 2026-11-15)
- texreg Journal of Statistical Software article (accessed 2026-11-15)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







