9

I'm trying to change rows order in a сharacteristic table column using function sort = list (stage ~ "alphanumeric ") in the tbl_summary () trial[c("trt", "age", "stage", "grade")] %>% tbl_summary(by = trt, sort = list (grade ~ "alphanumeric")). This does not work. I would like to see (for example: stage T3, T 4, T1, T2 and grade III -> I )

Daniel D. Sjoberg
  • 8,820
  • 2
  • 12
  • 28

1 Answers1

9

There are 3 ways to control the order levels of categorical variables appear in the tbl_summary() output.

  1. Use the default alphanumeric sorting (factors are sorted by their factor level)

  2. Sort the output by frequency using the tbl_summary(sort=) argument.

  3. Change the order by defining a factor variable and specifying the order you'd like the output to appear.

The examples below are for each of these cases. I hope this answers your question! Happy Coding!

library(tidyverse)
library(gtsummary)

# sorting by alphanumeric is the default
trial[c("trt", "stage")] %>% 
  tbl_summary(by = trt)

enter image description here

# sorting by frequency using the `sort=` argument
trial[c("trt", "stage")] %>% 
  tbl_summary(by = trt, sort = all_categorical() ~ "frequency")

enter image description here

# manually change the order in the dataset, before passing to `tbl_summary`
trial[c("trt", "stage")] %>% 
  mutate(stage = factor(stage, levels = c("T4", "T3", "T2", "T1"))) %>% 
  tbl_summary(by = trt)

enter image description here

Daniel D. Sjoberg
  • 8,820
  • 2
  • 12
  • 28
  • Do these also work to change the order of the variables (as a block with the levels)? – user257566 Sep 08 '20 at 17:13
  • 1
    The variables are printed in the table in the order they appear in the data frame. Select the columns in the order you prefer before piping the data frame to tbl_summary. – Daniel D. Sjoberg Sep 08 '20 at 23:20