Sometimes you will want to have univariate and multivariable analyses in the same table. The example below looks at the impact of variables on survival and then only selects those with a certain p-value (in this case 0.02) to include in the multivariable analysis.
It involves creating two separate tables and then joining at the end using the tbl_merge function from gtsummary.
There is an intermediate step where a table, filtered by p-value, is created. This allows the use of those selected variables with a p-value below the threshold to be used in the multivariable analysis. You could manually specify which variables to include and avoid this step but it may become cumbersome if there were a large number of variables to be included.
Finally the table is converted to a “gt” table so that some additional formatting can be done.
Code
library(titanic)library(tidyverse)library(gtsummary)theme_gtsummary_compact()table_uni <- titanic_train %>%# Dataset usedselect(-c(Name, PassengerId, Ticket, Cabin, Embarked, Parch)) %>%# Keeping only the variables we wantmutate( # Making death 1 and survival 0, easier to interpret in graphSurvived =as.numeric(Survived!='1'),Pclass =factor(Pclass) # Class should be categorical ) %>%tbl_uvregression(method=glm,y = Survived,method.args =list(family = binomial),exponentiate =TRUE,hide_n = T ) %>%add_nevent(location="level") %>%add_global_p() %>%#omnibus testbold_p() %>%# bold p-values (default 0.05)bold_labels() %>%italicize_levels() %>%modify_header(stat_nevent ="**Deaths**")p <- titanic_train %>%# Dataset used# select(Pclass, Sex, Age, Survived) %>% # Keeping only the variables we wantselect(-c(Name, PassengerId, Ticket, Cabin, Embarked, Parch)) %>%mutate( # Making death 1 and survival 0, easier to interpret in graphSurvived =as.numeric(Survived!='1'),Pclass =factor(Pclass) # Class should be categorical ) %>%tbl_uvregression(method=glm,y = Survived,method.args =list(family = binomial),exponentiate =TRUE ) %>%filter_p(t =0.02)table_multi <- titanic_train %>%# Dataset usedselect(Survived, p$table_body$variable) %>%# Keeping only the variables we wantmutate( # Making death 1 and survival 0, easier to interpret in graphSurvived =as.numeric(Survived!='1'),Pclass =factor(Pclass) # Class should be categorical ) %>%glm(Survived ~ ., family =binomial(), data = .) %>%tbl_regression(exponentiate = T ) %>%add_global_p() %>%#omnibus testbold_p() %>%# bold p-values (default 0.05)bold_labels() %>%italicize_levels()tbl_merge(list(table_uni, table_multi),tab_spanner =c("**Univariate analysis**", "**Multivariable analysis**")) %>%as_gt() %>%gt::tab_options(table.font.names ="Times New Roman") %>% gt::opt_horizontal_padding(scale =2.5)