'Assign object name to different tbl_summary tables from lapply function
I would want to generate different tbl_summary tables from a loop(lapply function) over similar categorical variables (var1, var2, var3) applied to "by= " and assign each of them an object name e.g "tbl_var1", "tbl_var2" and "tbl_var3"
dflist <- c("var1",
"var2",
"var3")
vartbls = lapply(dflist, function(df) {
tbl_summary_ex2 <-
trial %>%
select(age, grade, response, trt) %>%
tbl_summary(
by = df,
label = list(age ~ "Patient Age"),
statistic = list(all_continuous() ~ "{mean} ({sd})"),
digits = list(age ~ c(0, 1))
)
}
)
Solution 1:[1]
Here is a reprex with a working version of your function with code to set the names:
library(gtsummary)
dflist <- c("age", "grade")
vartbls <- lapply(dflist, function(x) {
tbl_summary_ex2 <-
trial %>%
select(age, grade, response, trt) %>%
tbl_summary(
by = x,
label = list(age ~ "Patient Age"),
statistic = list(all_continuous() ~ "{mean} ({sd})"),
digits = list(age ~ c(0, 1))
)
}
)
names(vartbls) <- paste0("tbl_", dflist)
Here is a version using {purrr} and setting names before iterating:
library(gtsummary)
library(purrr)
result <- c("trt", "grade") %>%
purrr::set_names(paste0("tbl_", .)) %>%
purrr::map(., ~ trial %>%
select(age, grade, response, trt) %>%
tbl_summary(
by = .x,
label = list(age ~ "Patient Age"),
statistic = list(all_continuous() ~ "{mean} ({sd})"),
digits = list(age ~ c(0, 1))
))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
