Wei Qi Loh
Wei Qi Loh

Reputation: 23

how to do ordered sorting with by = argument in tbl_summary?

I am creating a table 1 from a dataset which consist of two groups "Case" and "Control" using the tbl_summary function.

As it naturally sorts into two columns with "Case" on the left and "Control" on the right, I get this table:

table obtained from tbl_summary

However, I would like to have the "Control" group appearing on the left. I have tried to re-order the factors, placing "Control" first before "Case". However, "Case" still appears on the left - I'm assuming this is because it's following alphanumeric order.

How could I get around this? It's a simple adjustment but I am clueless.

Upvotes: 2

Views: 1768

Answers (1)

Daniel D. Sjoberg
Daniel D. Sjoberg

Reputation: 11774

The easiest way to reverse the ordering of the the variable in tbl_summary(by=) is using the forcats::fct_rev() function before you pipe a data frame to tbl_summary().

Example below. Happy Programming!

library(gtsummary)

trial %>%
  select(trt, age, marker) %>%
  mutate(trt = forcats::fct_rev(trt)) %>%   # reverse the ordering of trt variable
  tbl_summary(by = trt)

enter image description here

Upvotes: 1

Related Questions