Search code examples
rgtsummarygt

Specifying order of tbl_regression tables when merging them using tbl_merge {gtsummary}


Sometimes, when you merge tables created by tbl_regression using tbl_merge, it doesn't merge tables in the order you specified. For example;

  t1 <- trial %>%
  na.exclude() %>%
  lm(marker ~ age + ttdeath, .) %>%
  tbl_regression()
t2 <- trial %>%
  na.exclude() %>%
  lm(marker ~ age + response + death, .) %>%
  tbl_regression()
t3 <- trial %>%
  na.exclude() %>%
  lm(marker ~ age + stage + death, .) %>%
  tbl_regression()
t4 <- trial %>%
  na.exclude() %>%
  lm(marker ~ stage + grade + death, .) %>%
  tbl_regression()

tbl_merge(list(t2, t4, t3, t1))

merged table not in the order you specified

I specified in order of 2, 4, 3, 1, but the created table is in the order of 1, 3, 4, 2. As such, I would like to change the order of "columns" or merged tables in the way I originally specified.

I have tried to

as_gt() %>% move_cols() 

but with no avail.

Is there a way to solve this problem? Any help would be appreciated. Thank you in advance.


Solution

  • The ordering should be more predictable than this! I think you've found a bug in the column ordering that I'll correct in the next release.

    In the meantime, the code below will re-order the columns correctly.

    library(gtsummary)
    packageVersion("gtsummary")
    #> [1] '1.5.0'
    
    t1 <- lm(marker ~ age + ttdeath, trial) %>% tbl_regression()
    t2 <- lm(marker ~ age + response + death, trial) %>% tbl_regression()
    t3 <- lm(marker ~ age + stage + death, trial) %>% tbl_regression()
    t4 <- lm(marker ~ stage + grade + death, trial) %>% tbl_regression()
    
    tbl <- 
      tbl_merge(list(t2, t4, t3, t1)) %>%
      modify_table_body(
        ~.x %>%
          dplyr::relocate(
            c(ends_with("_1"), ends_with("_2"), ends_with("_3"), ends_with("_4")), 
            .after = label
          )
      )
    

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