如何为R语言gt()表格添加数据框中的行名?
解决gt()表格不显示drop1输出行名的问题
方法1:将行名转换为普通数据列
先通过tibble::rownames_to_column()把行名提取为单独的列(比如命名为Term),再传入gt生成表格:
library(tibble) library(gt) # 把drop1输出的行名转为数据列 drop1_processed <- drop1_output %>% rownames_to_column(var = "Term") # 生成带行名的gt表格 drop1_processed %>% gt() %>% tab_header(title = md("<strong>Model Selection Output</strong>"), subtitle = "GLMM with binomial distribution")
方法2:将行名设置为表格侧边栏(Stub)
如果希望行名固定在表格左侧作为分类表头,可直接使用gt自带的rownames_to_stub()函数,无需转换列:
library(gt) drop1_output %>% gt() %>% rownames_to_stub() %>% # 将行名移至左侧侧边栏 tab_header(title = md("<strong>Model Selection Output</strong>"), subtitle = "GLMM with binomial distribution")
补充说明
drop1()的输出属于anova类对象,转为数据框后行名对应模型中的各项(如age_category:gender),但gt默认不会渲染行名,因此需要手动指定行名的展示方式。两种方法中,侧边栏展示更贴合模型输出的阅读习惯,而转为普通列则方便对该列做格式调整(如加粗、排序)。
内容的提问来源于stack exchange,提问作者Alanna-Jo Mccallum
相关产品推荐
相关产品推荐

