1
votes

I would like to put the number of observations included in set of regression models at the bottom of a gtsummary table, in the same columns as the coefficient estimates. It is straightforward to put the numbers of observations in columns:

library(dplyr)
library(gtsummary)

df <- mtcars %>% 
  mutate(cyl_miss = if_else(
    cyl == 6,
    NA_real_,
    cyl
  ))
  
model_1 <- lm(
  data = df,
  formula = mpg ~ cyl + disp
)

model_2 <- lm(
  data = df,
  formula = mpg ~ cyl_miss + disp
)

table_1 <- tbl_regression(model_1) %>% 
  add_significance_stars(
    pattern = "{estimate}{stars}",
    thresholds = c(0.001, 0.01, 0.05),
    hide_ci = TRUE,
    hide_p = TRUE,
    hide_se = FALSE
  ) %>% 
  add_n()


table_2 <- tbl_regression(model_2) %>% 
  add_significance_stars(
    pattern = "{estimate}{stars}",
    thresholds = c(0.001, 0.01, 0.05),
    hide_ci = TRUE,
    hide_p = TRUE,
    hide_se = FALSE
  ) %>% 
  add_n()

tbl_merge(
  list(table_1, table_2)
)  

How can I put the numbers (here 32 and 25) in the Beta columns, in a row labelled "N"?

1

1 Answers

1
votes

To add the N to a new row of the table, you'll want to use the add_glance_table() function. Example below!

library(gtsummary)
packageVersion("gtsummary")
#> [1] '1.4.2'
df <- 
  mtcars %>% 
  dplyr::mutate(
    cyl_miss = ifelse(cyl == 6, NA_real_, cyl)
  )

model_1 <- lm(data = df, formula = mpg ~ cyl + disp)
model_2 <- lm(data = df, formula = mpg ~ cyl_miss + disp)

table_1 <- 
  tbl_regression(model_1) %>% 
  add_significance_stars() %>%
  add_glance_table(include = nobs)

table_2 <- 
  tbl_regression(model_2) %>% 
  add_significance_stars() %>%
  add_glance_table(include = nobs)

table_final <- 
  tbl_merge(list(table_1, table_2)) %>%
  # ensure the glance statistics are at the bottom of table
  modify_table_body(~.x %>% dplyr::arrange(row_type == "glance_statistic"))

enter image description here Created on 2021-09-14 by the reprex package (v2.0.1)