gtsummary

Using mutate to swap columns renders a negative Difference output


I have used the gtsummary package (great package btw) since last month on my reports.

Now I am building a cohort table that will show pre-test value, post-test value, difference (p.p) and a t-test p-value.

I'm trying to build the same table as I have built it under Arsenal with pre-test being the first column and post-test being in the second column and so on, but the difference column shows a negative output when it isn't supposed to be.

I used mutate() to swap both columns, as when I don't use it it shows the post-test as the first column. I also tried swapping the post-test columns at first rows in the dataset itself as what I read in some posts. But to no avail.

homesurvey %>%
  select(period, CB2.Textbooks, CB2.Magazines, CB2.Newspapers, CB2.Religious_books, CB2.Coloring_books, CB2.Comics) %>%
  mutate(period = forcats::fct_rev(period)) %>%
  tbl_summary(by = period,
              statistic = all_continuous() ~ "{n} ({sd})",
              label = list (CB2.Textbooks ~ "Textbooks",
                            CB2.Magazines ~ "Magazines",
                            CB2.Newspapers ~ "Newspapers",
                            CB2.Religious_books ~ "Religious books",
                            CB2.Coloring_books ~ "Coloring books",
                            CB2.Comics ~ "Comics")
              )%>%
  add_difference() %>%
  modify_column_hide(ci)

It shows a negative difference even if it isn't supposed to be.

Output


Solution

  • I am looking at your example output (thanks for including it). The first row is showing 82% in pre-assessment and 96% in the post-assessment. 82 - 96 = -15%, so the difference should indeed be negative.

    You can, however, flip the estimate by multiplying it by -1. Example below!

    library(gtsummary)
    packageVersion("gtsummary")
    #> [1] '1.5.0'
    
    tbl <- 
      trial %>%
      select(response, death, trt) %>%
      tbl_summary(by = trt, missing = "no") %>%
      add_difference() %>%
      modify_column_hide(ci) %>%
      # you can flip the difference estimate by multiplying it by -1
      modify_table_body(
        ~.x %>%
          dplyr::mutate(estimate = -1 * estimate)
      )
    

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