I want to write a code that uses dplyr::select(), gtsummary::tbl_summary() and glue::glue().
The plan is:
- select a few variables from a dataframe (for example : all numerical variables)
- return a table summary based a grouping variable (a factor variable)
- and in the table, the caption should show the grouping variable
I will be using the gapminder dataset to demo the error.
The expected table is
Below, I demo what I have done
First, I load the libraries
library(tidyverse)
library(glue)
library(gapminder)
library(gtsummary)
And write my function
describe_grp <- function(data, group){
data %>%
tbl_summary(by = group) %>% add_p() %>%
modify_caption(glue::glue("Detection For **{group}**")) %>%
bold_labels()
}
But I need to use 'continent' (see codes below). It works like I wanted.
gapminder %>%
select(is.integer, is.double, continent) %>%
describe_grp(group = 'continent')
But, my preferred choice is not to use the hyphen, that is to use describe_grp(group = continent).
So I thought I could use
enquo()- or
{{ }}curly curly
However, both do not work. My guess it has something to do with glue::glue() function in modify_caption()
See below for the codes that do not work:
#using enquo
describe_grp2 <- function(data, group){
egroup <- enquo(group)
data %>%
tbl_summary(by = !!egroup) %>% add_p() %>%
modify_caption(glue::glue("Detection For {(!!egroup)}")) %>%
bold_labels()
}
gapminder %>%
select(is.integer, is.double, continent) %>%
describe_grp2(group = continent)
These codes also don't work
#using curly curly
describe_grp3 <- function(data, group){
data %>%
tbl_summary(by = {{group}}) %>% add_p() %>%
modify_caption(glue::glue("Detection For **{{{group}}}**")) %>%
bold_labels()
}
gapminder %>%
select(is.integer, is.double, continent) %>%
describe_grp3(group = continent)

