简体   繁体   中英

how to alphanumerically sort levels of a categorical variable to pass to gtsummary table in R

I want the levels of grade to be ordered as 1- 2- 10.
I know if inside case_when I use numbers (ie 1 instead of "1", ... ) this will solve the problem but in my actual case I have to keep the values as characters.
in gtsummary manual, it used sort attribute. I set it to alphanumeric but I still can not get what I want.
is there any other way to order the levels of an alphanumeric-ish variable?

library(gtsummary)
trial2 <- trial %>% 
    dplyr::select(trt, age, grade) %>%
mutate(grade = case_when(grade == "I" ~ "1",
                         grade == "II" ~ "10",
                         TRUE ~ "2"))

trial2 %>%
    tbl_summary(by = trt,
                sort = list(
                           grade ~ "alphanumeric")) %>%
    add_p() %>%
    modify_footnote(update = everything() ~ NA) %>%
     bold_labels()

在此处输入图像描述

can you factor the character variable to get the order you want like so:

library(gtsummary)
library(dplyr)

trial2 <- trial %>% 
  dplyr::select(trt, age, grade) %>%
  mutate(grade = case_when(grade == "I" ~ "1",
                           grade == "II" ~ "10",
                           TRUE ~ "2"),
         grade = factor(grade, levels = c("1","2","10")))

trial2 %>%
  tbl_summary(by = trt) %>%
  add_p() %>%
  modify_footnote(update = everything() ~ NA) %>%
  bold_labels()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM