Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort or change rows order in a сharacteristic table column in the gtsummary package?

Tags:

r

gtsummary

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 )

like image 607
Aleksei Ponomarenko Avatar asked Jun 09 '20 18:06

Aleksei Ponomarenko


1 Answers

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

like image 89
Daniel D. Sjoberg Avatar answered Nov 13 '22 14:11

Daniel D. Sjoberg