gtsummary“前 10 名”

问题描述 投票:0回答:1

有没有办法让带有分类数据的 gtsummary tbl_summary 只包含 10 个最常见的条目?

我目前正在使用以下代码

library(forcats)
library(dplyr)
library(magrittr)

table<- fct_count(df$name, sort = T, prop = T)%>%
  slice_head(n = 10)
table$p<- round(table$p, digits = 3)
table$p<- table$p * 100
table %<>% rename(Organism = f,`%` = p)
table

这会在控制台中生成一个漂亮的表格:

a table of bacterial names with the frequency and proportion for which they appear in the dataframe

但理想情况下,我会将其放在 gsummary 表中(因为这就是我的报告的其余部分所使用的)。 我可以使 tbl_summary 没有问题,我只是不知道如何限制为仅 10 种最常见的生物体,而且我还没有在任何地方看到这个问题/答案。

示例数据集

library(AMR)
df<- data.table::as.data.table(example_isolates)
df$name<- mo_name(df$mo)
r gtsummary
1个回答
0
投票

由于

tbl_summary
不提供这样的开箱即用功能,您可以简单地预先计算前 10 个类别并过滤数据,然后将其输入到
tbl_summary
:

library(gtsummary)

top_categories <- fct_count(df$name, sort = TRUE, prop = TRUE) %>%
  slice_head(n = 10) %>%
  pull(f) %>%
  as.character()

tbl_summary(df %>% filter(name %in% top_categories), include = name, 
            sort = all_categorical(FALSE) ~ "frequency") 

产生:

Table with columns Characteristic and N showing the distribution of name in total and percent

© www.soinside.com 2019 - 2024. All rights reserved.