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 )
Asked
Active
Viewed 6,655 times
9

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

Aleksei Ponomarenko
- 93
- 1
- 3
1 Answers
9
There are 3 ways to control the order levels of categorical variables appear in the tbl_summary()
output.
Use the default alphanumeric sorting (factors are sorted by their factor level)
Sort the output by frequency using the
tbl_summary(sort=)
argument.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)
# sorting by frequency using the `sort=` argument
trial[c("trt", "stage")] %>%
tbl_summary(by = trt, sort = all_categorical() ~ "frequency")
# 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)

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
-
1The 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