如何调整tbl_uvregression生成表格的变量显示顺序?
解决gtsummary中tbl_uvregression变量顺序不符问题
你定义的变量顺序为age, stage, grade, marker, response,但使用tbl_uvregression生成表格时,变量顺序却变成了age、marker、stage、grade、response。这是因为include参数仅负责筛选要纳入的变量,不会改变变量的显示顺序——表格默认会按照变量在原始数据集里的出现顺序排列。
解决方法
可以通过modify_table_body()函数手动指定变量顺序,调整后的完整代码如下:
covars <- c("age", "stage", "grade", "marker", "response") tbl_uvregression( trial, method = coxph, y = Surv(ttdeath, death), exponentiate = TRUE, include = all_of(covars), hide_n = TRUE, add_estimate_to_reference_rows = TRUE ) %>% # 按预设顺序重新排列变量行 modify_table_body( ~ .x %>% dplyr::arrange(factor(label, levels = covars)) ) %>% as_kable()
另一种思路是先重新排列数据集的变量顺序,再调用函数:
covars <- c("age", "stage", "grade", "marker", "response") trial_reordered <- trial %>% select(all_of(covars), ttdeath, death) tbl_uvregression( trial_reordered, method = coxph, y = Surv(ttdeath, death), exponentiate = TRUE, include = all_of(covars), hide_n = TRUE, add_estimate_to_reference_rows = TRUE ) %>% as_kable()
当前生成的表格(顺序不符,中文翻译版)
| 特征 | HR | 95% CI | p值 |
|---|---|---|---|
| 年龄 | 1.01 | 0.99, 1.02 | 0.332 |
| 标记物水平(ng/mL) | 0.91 | 0.72, 1.15 | 0.435 |
| T分期 | |||
| T1 | 1.00 | 参考值 | |
| T2 | 1.18 | 0.68, 2.04 | 0.560 |
| T3 | 1.23 | 0.69, 2.20 | 0.476 |
| T4 | 2.48 | 1.49, 4.14 | 4.7e-04 |
| 分级 | |||
| I | 1.00 | 参考值 | |
| II | 1.28 | 0.80, 2.05 | 0.305 |
| III | 1.69 | 1.07, 2.66 | 0.024 |
| 肿瘤反应 | 0.50 | 0.31, 0.78 | 0.003 |
内容的提问来源于stack exchange,提问作者TJ87
相关产品推荐
相关产品推荐

