Search code examples
rgt

In R package gt, can you merge columns and format results at same time?


Suppose I have two columns representing upper and lower confidence bounds

df <- tibble(upper_bounds = c(0.00000123, 0.2323223),
             lower_bounds = c(0.12334455, 0.1234556))

Is there a way to both merge those columns and format them using the gt package?

As independent columns I can format them:

tab <- df %>%
 gt() %>%
 fmt_number( columns = c(upper_bounds, lower_bounds), decimals = 3)

and I can combine them

tab <- df %>%
 gt() %>%
  cols_merge(
    columns = c(lower_bounds, upper_bounds),
    pattern = "({1}, {2})"
  ) 

But I can't figure out how to both merge and format at the same time. Is it possible? I could, alternatively, go back to my original dataset and format upper/lower bounds there, but I'm curious if I can do it within gt.


Solution

  • Perhaps I'm misunderstanding your request, but you can just feed the result of your fmt_number() call to the cols_merge() call:

    tab <- df %>%
      gt() %>%
      fmt_number( columns = c(upper_bounds, lower_bounds), decimals = 3) %>% 
      cols_merge(
        columns = c(lower_bounds, upper_bounds),
        pattern = "({1}, {2})"
      )