我有一个如下示例数据集和生成我想要的表的代码。但是,我还有很多变量要添加到表中。为每个变量重复相同的代码来创建表格会使代码超长。我正在尝试将 tbl_summary 写入函数,但似乎没有用,我不知道如何修复它。
library(gtsummary)
library(tidyverse)
test <- data.frame("Gender" = c("Female", "Male", "Male", "Female", "Female", "Female", "Male", "Female", "Female", "Male"),
"source" = c("FFQ", "Foodworks", "FFQ", "FFQ", "FFQ", "FFQ", "FFQ", "Foodworks", "Foodworks", "Foodworks"),
"EnergyDF_kJ_total" = c(8060.61, 16802.2, 10755.57, 8061.82, 8995.44, 3838.91, 7495.89, 8057.92, 15831.68, 5298.25),
"vegetable_score" = c(6.47, 5.55, 8.39, 5.17, 10, 1.82, 3.11, 1.21, 2.76, 1.21)
)
# create table overall
tbl_EnergyDF_kJ_total <-
test %>%
select(Gender, EnergyDF_kJ_total) %>%
tbl_summary(by = Gender, missing = "no",
type = EnergyDF_kJ_total ~ "continuous",
statistic = EnergyDF_kJ_total ~ "{mean} ({sd})") %>%
modify_header(stat_by = "**{level}**") # CHANGE COLUMN HEADER
# REMOVE STATISTICS FOR EnergyDF_kJ_total FROM TABLE
tbl_EnergyDF_kJ_total$table_body <-
tbl_EnergyDF_kJ_total$table_body %>%
mutate_at(vars(stat_1, stat_2), ~NA_character_)
# create table stratified by source
tbl_EnergyDF_kJ_total_by_source <-
test %>%
# keep the continuous var and the two categorical variables
select(Gender, EnergyDF_kJ_total, source) %>%
group_nest(source) %>%
mutate(
tbl = map2(
source, data,
~tbl_summary(.y, by = Gender,
type = EnergyDF_kJ_total ~ "continuous",
statistic = EnergyDF_kJ_total ~ "{mean} ({sd})",
label = list(EnergyDF_kJ_total = .x), missing = "no") %>%
add_overall(col_label = "**Overall**") %>%
add_n()
)
) %>%
pull(tbl) %>%
tbl_stack()
# stacking the tables
tbl_stack(list(tbl_EnergyDF_kJ_total, tbl_EnergyDF_kJ_total_by_source)) %>%
modify_table_body(dplyr::relocate, c("n", "stat_0"), .after = "label") %>%
# indenting the source rows
as_gt() %>%
gt::tab_style(style = gt::cell_text(indent = gt::px(10), align = "left"),
locations = gt::cells_body(columns = gt::vars(label),
rows = !is.na(n)))
以下是我尝试为整个表创建函数的代码,但它不起作用。任何帮助将非常感激。
x <- function(test, var1, var2) {
test %>%
select(var1, var2) %>%
tbl_summary(by = var1, missing = "no",
type = var2 ~ "continuous",
statistic = var2 ~ "{mean} ({sd})") %>%
modify_header(stat_by = "{level}") # CHANGE COLUMN HEADER
}
test1 <- x(test, Gender, EnergyDF_kJ_total)