How to add a text line to your regression table above one coefficient using the modelsummary function?

1.2k views Asked by At

I am new to R and i am formatting my regression tables for the first time. I would like to add a line above "Working class" in the table below. This line should show "Reference category: Upper-class". Could someone please guide me a bit and maybe suggests some interesting examples/links where i can find formatted tables using the modelsummary function?

Here is my code:

results <-list("Pooled OLS" = Pooled.ols, "Fixed effects" = fixed.effects)
# Coefficients
cm <- c( 'age' = 'Age', 'I(age^2)' = 'Age square', 'wc' = 'Working class','mc' = 'Lower-middle class')
# Output Table
modelsummary(results, stars = TRUE,statistic = 'std.error', type= "html", 
             fmt= '%.4f',coef_map=cm
)

enter image description here

1

There are 1 answers

0
Vincent On BEST ANSWER

You can use the add_rows argument as follows:

library(modelsummary)

mod <- lm(hp ~ mpg + vs + drat, mtcars)

row <- data.frame("Coefficients" = "Reference category: Upper-class",
                  "Model 1" = "")
attr(row, "position") <- 5
modelsummary(mod, add_rows=row)

enter image description here

Edit: I initially misunderstood the question and thought you wanted to add a horizontal line to separate rows. Since this can often be useful when we want to add custom rows to a table, I leave my (wrong but relevant) answer below.

As of today (2020-12-03), modelsummary can produce model objects compatible with four table-drawing packages: kableExtra (default), gt, flextable and huxtable. Each of those packages allows you to customize the look of your tables, but they each have different approaches.

For example, if you want to customize the default HTML table produced by kableExtra, you could feed custom CSS to the row_spec function:

library(modelsummary)

mod <- lm(hp ~ mpg + vs + drat, mtcars)

library(kableExtra)
modelsummary(mod, gof_omit=".*") %>%
  row_spec(2, extra_css = "border-bottom: 3px solid")

enter image description here

Note that kableExtra uses a slightly different approach for LaTeX/PDF output. See the package documentation.

If you would rather use the gt package, you can set the output argument and then use gt's tab_style function:

library(gt)
modelsummary(mod, output="gt", gof_omit=".*") %>%
  tab_style(style = cell_borders(sides="bottom", weight=px(4)), 
            locations = cells_body(rows = 2))

enter image description here