Search code examples
rformattingtidyversestargazer

Removing table components in stargazer


I am putting together tables using stargazer and presenting them in a HTML file using RMarkdown. Reproducible code to create the image is pasted below.

I would like to remove the stars and standard errors associated with the constant ("Alpha" in the image below).

I understand that I can manually overwrite the table components but is there a way that I can automatically retain stars and SE for everything but the alpha row? To re-write everything into character vectors seems a little cumbersome.

Code:

library(tidyverse)
library(stargazer) 

mdl1 <- lm(mpg~wt, mtcars)
mdl2 <- lm(mpg~disp, mtcars)

mdls <- list(mdl1,mdl2)

column.labels <- c('model 1',
                   'model 2')

covariate.labels <- c('Beta 1',
                      'Beta 2',
                      'Alpha')

keep.stat <- c('n')

stargazer(mdls, type = 'html',
          column.labels = column.labels,
          covariate.labels = covariate.labels,
          column.sep.width = "10pt",
          dep.var.labels.include = F,
          keep.stat = keep.stat) 

current output


Solution

  • In a comment you asked if an alternative to stargazer could help you with this. The answer is “yes”, the modelsummary package can do this relatively easily. (Disclaimer: I am the maintainer.)

    I say “relatively” because what you are asking is very idiosyncratic, so I don’t think you should expect it to work out of the box in any package. But here’s an example.

    First, we start with a basic table with nice labels:

    library(modelsummary)
    library(broom)
    
    models <- list(
        lm(mpg ~ wt + hp, mtcars),
        lm(mpg ~ disp + hp, mtcars))
    
    coef_map <- c(
        "wt" = "Weight",
        "disp" = "Displacement",
        "hp" = "Horse Power")
    
    modelsummary(models, stars = TRUE, coef_map = coef_map)
    

    enter image description here

    The Customizing Existing Models section of the documentation explains that modelsummary allows you to overwrite any estimate (coef, standard error, p value, etc.) by defining a new function called tidy_custom.CLASSNAME, where CLASSNAME refers to the type of model object you are trying to summarize.

    In our example above, we summarize lm models:

    class(models[[1]])
    
    ## [1] "lm"
    

    Therefore, our customizing function will be called tidy_custom.lm. Say your goal is to remove the standard errors, stars, and p values from the table, but only for the variable hp. What we can do is overwrite the estimates with NA (please refer to the docs linked above for a detailed explanation):

    tidy_custom.lm <- function(model) {
      out <- tidy(model)
      out$p.value[out$term == "hp"] <- NA
      out$std.error[out$term == "hp"] <- NA
      return(out)
    }
        
    modelsummary(models, stars = TRUE, coef_map = coef_map)
    

    enter image description here