Multi-panel regression tables in R

Viewed 939

I am trying to create a regression table that has two panels with overlapping but not identical dependent variables. For each panel, I want a title indicating the name of each panel as well as the dependent variables for each regression.

# rm(list = ls())

data("mtcars")

# Regressions for panel 1
reg1 <- lm(mpg ~ cyl + disp, data = mtcars)
reg2 <- lm(cyl ~ cyl + disp, data = mtcars)

# Regressions for panel 2
reg3 <- lm(mpg ~ hp + drat, data = mtcars)
reg4 <- lm(cyl ~ hp + drat, data = mtcars)
reg5 <- lm(disp ~ hp + qsec, data = mtcars)

# Panel 1 output
panel1 <- stargazer::stargazer(
  reg1, reg2,
  float = TRUE,
  header = FALSE,
  model.numbers = FALSE,
  omit.table.layout = "n",
  multicolumn = FALSE,
  dep.var.caption = "",
  type = "latex",
  align = TRUE, 
  digits = 2,
  df = FALSE, 
  digits.extra = 2,
  nobs = TRUE,
  omit.stat = c("rsq", "adj.rsq", "ser") 
)

# Panel 2 output
panel2 <- 
  stargazer::stargazer(
  reg3, reg4, reg5,
  float = TRUE,
  header = FALSE,
  model.numbers = FALSE,
  omit.table.layout = "n",
  multicolumn = FALSE,
  dep.var.caption = "",
  type = "latex",
  align = TRUE, 
  digits = 2,
  df = FALSE, 
  digits.extra = 2,
  nobs = TRUE,
  omit.stat = c("rsq", "adj.rsq", "ser")
)

# Plot panels together
table <- 
  starpolishr::star_panel(
  panel1, 
  panel2,
  panel.names = c(
    "Panel 1", 
    "Panel 2"
  ), 
  same.summary.stats = FALSE, 
  same.lhs.vars = FALSE )

# Save as a .tex file
starpolishr::star_tex_write(
  starlist = table, 
  file = paste0(here::here(), "/panel_mwes.tex"), 
  headers = FALSE
)

This code produces the following output:

What I need to change is 1) Move "Panel A: Panel 1" above the dependent variable names; and 2) add dependent variable names below "Panel B: Panel 2". Is there any good way of implementing this (in stargazer/starpolishr or otherwise) without being super hacky?

1 Answers

So here is my hacky way of doing things (I won't accept this as the answer as there must be a better way of doing this).

# 1. Flip the panel name and column names around
col_names  <- table[8]
panel_name <- table[10]

table[8]  <- panel_name
table[10] <- col_names

# 2. Insert custom column names below panel 2 header
table <- 
  starpolishr::star_insert_row(
    table, 
    c("\\hline \\\\[-1.8ex] & \\multicolumn{1}{c}{mpg} & \\multicolumn{1}{c}{cyl} & \\multicolumn{1}{c}{disp} \\\\ \\hline \\\\[-1.8ex]"),
    insert.after = c(24)
  )

# Save output
starpolishr::star_tex_write(
  starlist = table, 
  file = paste0(here::here(), "/panel_mwe2.tex"), 
  headers = FALSE
)

The following output is roughly what I am trying to achieve:

enter image description here

Related