table_example_3

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)

table_example_1

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)

table_example_2

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)

table_example_3

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 hlavac@fas.harvard.edu .

  • Maxim K

    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?

  • Ricardo Pietrobon

    really cool, but any plans to support markdown?

    • Marek

      Will consider. Thanks!

  • Raj S

    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?

    • Marek

      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.

  • Arkadiy

    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.

    • Marek

      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.

      • Arkadiy

        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.

        • Marek

          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.

          • Arkadiy

            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!

            • Marek

              Great! Glad everything worked out for you.

          • Devon Sampson

            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.

            • Skedasticity

              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?

              • Devon Sampson

                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?

  • Rodrigo Belo

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

  • mielniczuk

    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).

  • Skedasticity

    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!

  • Omar Doria

    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!