4
votes

I would like to introduce a subscript in a variable name for a regression summary table generated using tbl_regression in the R package gtsummary. Can anyone provide guidance as to how to do this? Code used to generate a table and the resulting table are presented below. I would like the label "NO2" to appear as "NO2".

library(tidyverse)
library(gtsummary)

case <- c(0,1,0,0,0,0)
no2 <- c(17, 14, 8, 9, 9, 7)
df <- data.frame(case, no2)

mod_adj <- glm(case~no2,data=df, family="binomial")

regression_table_adj <- mod_adj %>% 
  tbl_regression(exponentiate = TRUE,  label = list(no2~"NO2"))

regression_table_adj

Created on 2020-03-04 by the reprex package (v0.3.0)

A table produced using tbl_regression in the R package gtsummary showing a coefficient name that I want to contain a numeric subscript

2

2 Answers

1
votes

The gtsummary package uses the gt package to print tables by default. I looked through their documentation, and I didn't see a way to include subscript in the body of a table.

The good news is that gtsummary also supports printing tables with knitr::kable() via the as_kable() function. You can wrap text between two tildas to make it a subscript (e.g. label = list(no2 ~ "NO~2~")). Use the code below in a R markdown file and you should get the subscript. The downside to using kable is that it does not support footnotes, indentation, and spanning header. Happy Coding!

library(gtsummary)

case <- c(0,1,0,0,0,0)
no2 <- c(17, 14, 8, 9, 9, 7)
df <- data.frame(case, no2)

mod_adj <- glm(case~no2,data=df, family="binomial")

mod_adj %>% 
  tbl_regression(
    exponentiate = TRUE,  
    label = list(no2 ~ "NO~2~")
  ) %>% 
  as_kable()

enter image description here

Created on 2020-03-04 by the reprex package (v0.3.0)

2
votes

This is not mine, but I found an answer here and adapted it. https://community.rstudio.com/t/subscripts-to-annotate-gt-table/87089

Essentially you'll convert it to a gt object and hack the label so it prints as subscript.

library(tidyverse)
library(gtsummary)
library(gt)

case <- c(0,1,0,0,0,0)
no2 <- c(17, 14, 8, 9, 9, 7)
df <- data.frame(case, no2)

mod_adj <- glm(case~no2,data=df, family="binomial")

regression_table_adj <- mod_adj %>% 
  tbl_regression(exponentiate = TRUE,  label = list(no2 = "NO@2~")) %>%
  as_gt() %>%
  text_transform(
    locations = cells_body(),
    fn = function(x) {
      str_replace_all(x,
                      pattern = "@",
                      replacement = "<sub>") %>% 
        str_replace_all("~",
                        "</sub>") }
  )

Image of Table

Yes, the symbols can easily be replaced. I think it would be better to use something other than '~' since it can easily mean something else.