Reputation: 123
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 )
Upvotes: 12
Views: 12211
Reputation: 11679
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)
Upvotes: 15