# Tailor Your Tables with stargazer: New Features for LaTeX and Text Output

Guest post by Marek Hlavac

Since its first introduction on this blog, stargazer, a package for turning R statistical output into beautiful LaTeX and ASCII text tables, has made a great deal of progress. Compared to available alternatives (such as apsrtable or texreg), the latest version (4.0) of stargazer supports the broadest range of model objects. In particular, it can create side-by-side regression tables from statistical model objects created by packages AER, betareg, dynlm, eha, ergm, gee, gmm, lme4, MASS, mgcv, nlme, nnet, ordinal, plm, pscl, quantreg, relevent, rms, robustbase, spdep, stats, survey, survival and Zelig.  You can install stargazer from CRAN in the usual way:

install.packages(“stargazer”)


### New Features: Text Output and Confidence Intervals

In this blog post, I would like to draw attention to two new features of stargazer that make the package even more useful:

• stargazer can now produce ASCII text output, in addition to LaTeX code. As a result, users can now create beautiful tables that can easily be inserted into Microsoft Word documents, published on websites, or sent via e-mail. Sharing your regression results has never been easier. Users can also use this feature to preview their LaTeX tables before they use the stargazer-generated code in their .tex documents.
• In addition to standard errors, stargazer can now report confidence intervals at user-specified confidence levels (with a default of 95 percent). This possibility might be especially appealing to researchers in public health and biostatistics, as the reporting of confidence intervals is very common in these disciplines.

In the reproducible example presented below, I demonstrate these two new features in action.

### Reproducible Example

I begin by creating model objects for two Ordinary Least Squares (OLS) models (using the lm() command) and a probit model (using glm() ). Note that I use data from attitude, one of the standard data frames that should be provided with your installation of R.

## 2 OLS models

linear.1 <- lm(rating ~ complaints + privileges + learning + raises + critical, data=attitude)
linear.2 <- lm(rating ~ complaints + privileges + learning, data=attitude)

## create an indicator dependent variable, and run a probit model

attitude$high.rating <- (attitude$rating > 70)
probit.model <- glm(high.rating ~ learning + critical + advance, data=attitude, family = binomial(link = "probit"))


I then use stargazer to create a ‘traditional’ LaTeX table with standard errors. With the sole exception of the argument no.space – which I use to save space by removing all empty lines in the table – both the command call and the resulting table should look familiar from earlier versions of the package:

stargazer(linear.1, linear.2, probit.model, title="Regression Results", align=TRUE, dep.var.labels=c("Overall Rating","High Rating"), covariate.labels=c("Handling of Complaints","No Special Privileges", "Opportunity to Learn","Performance-Based Raises","Too Critical","Advancement"), omit.stat=c("LL","ser","f"), no.space=TRUE)


In the next table, I limit myself to the two linear models, and report 90 percent confidence intervals (using the ci and ci.level arguments). In addition, I use the argument single.row to report the coefficients and confidence intervals on the same row.

stargazer(linear.1, linear.2, title="Regression Results",
dep.var.labels=c("Overall Rating","High Rating"),
covariate.labels=c("Handling of Complaints","No Special Privileges",
"Opportunity to Learn","Performance-Based Raises","Too Critical","Advancement"), omit.stat=c("LL","ser","f"), ci=TRUE, ci.level=0.90, single.row=TRUE)


To produce ASCII text output, rather than LaTeX code, I can simply set the argument type to “text”:

stargazer(linear.1, linear.2, type="text", title="Regression Results",
dep.var.labels=c("Overall Rating","High Rating"),
covariate.labels=c("Handling of Complaints","No Special Privileges",
"Opportunity to Learn","Performance-Based Raises","Too Critical","Advancement"), omit.stat=c("LL","ser","f"), ci=TRUE, ci.level=0.90, single.row=TRUE)


### What Else is New?

The two new features that I have focused on in this blog post, of course, do not exhaust the range of innovations that the new stargazer brings. The package can now output beautiful LaTeX and ASCII text tables directly into .tex and.txt files, respectively, using the out argument.

Additionally, users have a greater scope for making changes to the table’s formatting. A much-demanded addition to version 4.0 concerns column labels. Using arguments column.labels and column.separate, users can now add a label to each of the columns in their regression table. Such labels can be used to indicate, among other things, the sub-sample or research hypothesis that a particular column refers to. In addition, users can also change the caption above the names of the dependent variables (argument dep.var.caption), as well as tinker with the font size in the resulting table (argument font.size).

More advanced users can now choose whether the LaTeX table should be enclosed within a floating environment (arguments float and float.env), and where the resulting table should be placed within the LaTeX document (argument table.placement). In this way, they might, for example, create a LaTeX table  that is rotated by 90 degrees (when float.env = “sidewaystable”).

Marek Hlavac is a doctoral student in the Political Economy and Government program at Harvard Unviersity. If you have any suggestions for future versions of the stargazer package, please contact him at [email protected] .

## 28 thoughts on “Tailor Your Tables with stargazer: New Features for LaTeX and Text Output”

1. Maxim K says:

I wonder what is the best way to render a table with just a single regression model. Two column table (var. names and coefficients) feels a bit too narrow for the page. It seems more feasible to make the output conform to the summary(lm.model) output, only with with the traditional stargazer formatting. Is that possible in any easy way?

2. Ricardo Pietrobon says:

really cool, but any plans to support markdown?

1. Marek says:

Will consider. Thanks!

3. Raj S says:

Sorry for the basic question but I don’t understand what part of the code indicates that linear.1 and linear.2 should be grouped together – or does stargazer just group objects of the same class (lm in this case)? (I think that is the case since when I added a third lm it grouped that as well.)
Also does the dep variable have to the firts column in data frame?

1. Marek says:

Hi Raj,

You can include the model objects in any order you like. If two neighboring columns share the same dependent variable and/or object class (“model type”, so to speak), stargazer will intelligently adjust table output so that all headings span the appropriate columns.

As for your second question, columns can be in any order in a data frame.

The best thing for you to do might be to install ‘stargazer’, and experiment with it a little bit. I think you’ll find what it does quite intuitive – the package tries to reduce the user’s work as much as possible.

Sorry for another basic question. But I haven’t found stargazer to be too intuition yet.

When I try:

> stargazer(attitude)

I just get this:

% Table created by stargazer v.4.0 by Marek Hlavac, Harvard University. E-mail: hlavac at fas.harvard.edu

% Date and time: Fri, Jul 19, 2013 – 10:54:38

begin{table}[!htbp] centering

caption{}

label{}

begin{tabular}{@{extracolsep{5pt}}lccccc}

[-1.8ex]hline

hline [-1.8ex]

Statistic & multicolumn{1}{c}{N} & multicolumn{1}{c}{Mean} & multicolumn{1}{c}{St. Dev.} & multicolumn{1}{c}{Min} & multicolumn{1}{c}{Max}

hline [-1.8ex]

rating & 30 & 64.633 & 12.173 & 40 & 85

complaints & 30 & 66.600 & 13.315 & 37 & 90

privileges & 30 & 53.133 & 12.235 & 30 & 83

learning & 30 & 56.367 & 11.737 & 34 & 75

raises & 30 & 64.633 & 10.397 & 43 & 88

critical & 30 & 74.767 & 9.895 & 49 & 92

advance & 30 & 42.933 & 10.289 & 25 & 72

hline [-1.8ex]

normalsize

end{tabular}

end{table}

Does anyone know how to turn this output into an actual table? Any help would be great appreciate.

1. Marek says:

You need to copy and paste into a TeX source file. It might be useful to ask someone who has experience with LaTeX. If you’re happy with a text-based table (rather than LaTeX), you can use the type=”text” argument.

Thank you so much for the quick response!

For some reason when I type what you suggested, I get an error:

> stargazer(attitude, type=”text”)
Error in objects[[i]]$zelig.call :$ operator is invalid for atomic vectors

Do you by any chance have any suggestions for what I can do to generate a text-based tabel? Any tips would be much appreciated.

1. Marek says:

You might be using an old version of stargazer. The current version does not produce an error in the scenario you described. Please make sure you have installed the latest one (4.0). If you have trouble installing 4.0, you may also need to update R to a more recent version.

You’re absolutely right. I had the current version of stargazer but old version of R. Once R was updated, problem was fixed. Thanks for all your help!

2. Marek says:

Great! Glad everything worked out for you.

3. Devon Sampson says:

Hi, I’m getting the same error, but I’m running stargazer 4.5.3 in R 3.0.2. Stargazer works fine until I try to add labels using covariate.labels and column.labels, in which case it returns:

Error in objects[[i]]$zelig.call :$ operator is invalid for atomic vectors

so, this works:

stargazer(fit.fs.S.J, fit.reduced, fit.labor.hhsize.CP, fit.div,
type=”text”,
title=”Regression Results”,
dep.var.labels=c(“Food Security”))

but this doesn’t:

stargazer(fit.fs.S.J, fit.reduced, fit.labor.hhsize.CP, fit.div,
type=”text”,
title=”Regression Results”,
dep.var.labels=c(“Food Security”),
covariate.lables=c(“Richness”, “J'”, “Off-farm income”, “Off-farm laborers”, “Head of Household Age”,
“Head of Household Education”, “Household Size”, “Homegarden Size”, “Homegarden Age”,
“Consumer:Producer Ratio”, “Income Sources”))

any ideas? Thank you.

4. Skedasticity says:

Devon, I’m finding the same issue. Everything is peachy until I try to add custom covariate names. I have the latest versions of R and stargazer. Did you ever figure out a fix?

5. Devon Sampson says:

No– Still on fix. Im using current versions of both R and Stargazer. I’m working around it by not trying to add custom covariate names in the R code, and doing it later in the LaTex code. Anyone out there have a better way of doing it?

6. ram says:

Marek, may I ask a question about stargazer? I have a long data.frame (nrow = 70, ncol = 2) – all data are characters, I fold it in matrix/table/like frame (ncol=14, nrow=10), but when I try to stargazer it like text table I get the following:

Error in if (nchar(text.matrix[r, c]) > max.length[real.c]) { : missing value where TRUE/FALSE needed

Please, what is going on there??

5. Rodrigo Belo says:

Is there a way to report clustered standard errors? Thanks.

6. mielniczuk says:

Elegant solution to creating visually friendlier tables, thanks. I use markdown via knitr and copy/paste output into code chunk using the eval=FALSE option. Outputs nicely in HTML (and print of web page).

7. Skedasticity says:

Marek, I’m trying to run your code (above, and from your package writeup) in TeXstudio. When I cut and paste the summary stats code it compiles beautifully. When I try the multi-model regression output tables I get errors and it doesn’t compile (i.e. “Illegal character in array arg…” and/or “! Missing } inserted…”). When I specify type=”text” it prints fine in ASCII. Any thoughts? Many thanks for all of your hard work!

8. Omar Doria says:

Hello, I am trying to use it with the lagsarlm command, but I have this message instead:
“Error in eval(expr, envir, enclos) : object ‘form’ not found”. What can I do to make the table with a sarlm class? Thanks for your help!

9. MagnusMetz says:

Is it possible to use stargazer in combination with booktabs?

10. Hello, Marek! Do you have any plans to add support for SEM packages any time soon? In particular, for objects, produced by ‘lavaan’, ‘OpenMx’, ‘plspm’ and others.

11. Andrew Uhl says:

When I use the dep.var.labels argument on Linux, all works fine. When I use it on WIndows, dep.var.labels does not get used. Instead, the first string in dep.var.labels appears above the row of column headers (1), (2), … In fact, one of your examples on this blog shows exactly this issue: https://www.r-statistics.com/wp-content/uploads/2013/07/table_example_2.bmp

Even though dep.var.labels=c(“Overall Rating”,”High Rating”) is set, only “Overall Rating” is used.

stargazer(linear.1, linear.2, title=”Regression Results”,
dep.var.labels=c(“Overall Rating”,”High Rating”),
covariate.labels=c(“Handling of Complaints”,”No Special Privileges”,
“Opportunity to Learn”,”Performance-Based Raises”,”Too Critical”,”Advancement”), omit.stat=c(“LL”,”ser”,”f”), ci=TRUE, ci.level=0.90, single.row=TRUE)

12. isabella says:

Hi, i used the stargazer library for regression and it seems nice, but I need also the degrees of freedom , the standard errors , deviance , in general the information that gives the summary of the model. Do you know how to achieve that? I saw that there is “report” in the stargazer that possibly gives you this opportunity, does anyone knows how to use it? Thank you in advance.

13. Alejandro Colaneri says:

Hi, I am trying to create some pdf file with a formated table for publication. I started with a table.csv that i read with R.
I created an object called Table1
Then I used stargazer to create the Latex table

stargazer(Table1, summary=FALSE, float = TRUE, out=”output2.tex”,type=”latex”)

After that I used Tex in the macterminal to compile the Latex table and produce a pdf. I used this command

pdflatex output2.tex

but I got the following error:

wire152019016055:TablesRNAseqPaper ACCpdflatex output2.tex This is pdfTeX, Version 3.14159265-2.6-1.40.17 (TeX Live 2016) (preloaded format=pdflatex) restricted \write18 enabled. entering extended mode (./output2.tex LaTeX2e Babel and hyphenation patterns for 83 language(s) loaded. ! LaTeX Error: Environment table undefined. See the LaTeX manual or LaTeX Companion for explanation. Type H for immediate help. l.4 \begin{table} [!htbp] \centering ? Can someone tell me what is going on? I will appreciate the help 14. Marcos Santos says: Hello Marek, I have installed stargazer and it is really a great package! To get the tables, I use the “text” option and I find it just fine. However, either I get CIs + stars for p-values, or I get p-values but no CIs. I really wish to have both p-values and CIs in the same table of, say, a logistic regression, such as presenting OR, CI and p-value for each predictor. Is there a way to tackle this issue? Thank you in advance. 15. Erez Yerushalmi says: Hi I’m new to r and stargazer. Any help would be really appreciated. I ran a simple regression. linear.1 <- lm(IntRating ~ llevrg, data=data) stargazer(linear.2, align=TRUE) The output from stargazer is copy/pasted into overleaf or LyX (for example). Both give the same error message. LaTeX Error: Illegal character in array arg. See the LaTeX manual or LaTeX Companion for explanation. Type H for immediate help. l.9 …tabular}{@{\extracolsep{5pt}}lD{.}{.}{-3} } I’m wondering what I’m doing wrong. HERE IS THE OUTPUT FROM STARGAZER \begin{table}[!htbp] \centering \caption{} \label{} \begin{tabular}{@{\extracolsep{5pt}}lD{.}{.}{-3} } \\[-1.8ex]\hline \hline \\[-1.8ex] & \multicolumn{1}{c}{\textit{Dependent variable:}} \\ \cline{2-2} \\[-1.8ex] & \multicolumn{1}{c}{IntRating} \\ \hline \\[-1.8ex] llevrg & 0.852^{***} \\ & (0.309) \\ & \\ lgdp & -2.116^{***} \\ & (0.427) \\ & \\ Constant & 20.349^{***} \\ & (2.404) \\ & \\ \hline \\[-1.8ex] Observations & \multicolumn{1}{c}{63} \\ R^{2}$& \multicolumn{1}{c}{0.346} \\ Adjusted R$^{2}$& \multicolumn{1}{c}{0.324} \\ Residual Std. Error & \multicolumn{1}{c}{3.835 (df = 60)} \\ F Statistic & \multicolumn{1}{c}{15.879$^{***}$(df = 2; 60)} \\ \hline \hline \\[-1.8ex] \textit{Note:} & \multicolumn{1}{r}{$^{*}$p$<$0.1;$^{**}$p$<$0.05;$^{***}$p$<\$0.01} \\
\end{tabular}
\end{table}

This site uses Akismet to reduce spam. Learn how your comment data is processed.