how to use gt table move groups to column?

31 views Asked by At

I am making summary tables using the gt package. I want to simplify the output a little and make the time points displayed as columns instead of rows. Right now I have each point as a separate row like:

Label estimate p value
case time 1 xx xx
control time 1 xx xx
case time 2 xx xx
control time 2 xx xx

I am hoping to organize it more like this:

Label time 1 time 2
estimate p-value estimate p-value
case xx xx xx xx
control xx xx xx xx

I have variables 'case_control' which is just the case and control assignment and 'time' which is the time points

rbind(H_LG3, W_LG3) %>%
gt()%>%
  fmt_number(
    columns = everything(),
    decimals = 3)%>%
    tab_row_group(group = md('**H**'), rows = 1:nrow(H_LG3)) %>%
    tab_row_group(group = md('**W**'), rows = (nrow(H_LG3) + 1):(nrow(H_LG3) + nrow(W_LG3))%>%
  cols_label(
    label=md("**Label**"),
    estimate_ci=md("**Estimate(CI)**"),
    formatted_p_value=md("**P Value**")
  )%>%
  tab_header(md("**Table 4**"))

I am also merging two tables in this step but they are just being stacked vertically and labelled. The columns are 'label' 'estimate_ci' 'p_val' 'time' and 'case_control'

1

There are 1 answers

0
Carl On

Here's a possible approach:

library(tidyverse)
library(tidyselect)
library(gt)

df <- tribble(
  ~label, ~estimate, ~p_value,
  "case time 1", 4, 21,
  "control time 1", 5, 22,
  "case time 2", 6, 23,
  "control time 2", 7, 24
)

df %>%
  separate_wider_delim(label, delim = " time ", names = c("label", "time")) %>%
  pivot_wider(
    names_from = time,
    values_from = c(estimate, p_value),
    names_glue = "time{time},{.value}"
  ) %>%
  select(sort(peek_vars())) %>%
  gt() %>%
  tab_spanner_delim(delim = ",")

enter image description here

Created on 2024-03-28 with reprex v2.1.0