简体   繁体   English

如何对分类变量的级别进行字母数字排序以传递到 R 中的 gtsummary 表

[英]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.我希望按 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.我知道如果在 case_when 我使用数字(即 1 而不是“1”,...)内部,这将解决问题,但在我的实际情况下,我必须将值保留为字符。
in gtsummary manual, it used sort attribute.在 gtsummary 手册中,它使用了sort属性。 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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