Introduction to the pubh package"

Introduction

Rationale for the package

There has been a long relationship between the disciplines of Epidemiology / Public Health and Biostatistics. Students frequently find introductory textbooks explaining statistical methods and the maths behind them, but how to implement those techniques in a computer is most of the time not explained.

One of the most popular statistical software's in public health settings is Stata. Stata has the advantage of offering a solid interface with functions that can be accessed via the use of commands or by selecting the proper input in the graphical unit interface (GUI). Furthermore, Stata offers "Grad Plans" to postgraduate students, making it relatively affordable from an economic point of view.

R is a free alternative to Stata. The use of R keeps growing; furthermore, with the relatively high number of packages and textbooks available, it's popularity is also increasing.

In the case of epidemiology, there are already some good packages available for R, including: Epi, epibasix, epiDisplay, epiR and epitools. The pubh package does not intend to replace any of them, but to only provide a common syntax for the most frequent statistical analysis in epidemiology.

Syntax: the use of formulas

Most students and professionals from the disciplines of Epidemiology and Public Health analyse variables in terms of outcome, exposure and confounders. The following table shows the most common names used in the literature to characterise variables in a cause-effect relationships:

Response variable|Explanatory variable(s) ---|--- Outcome|Exposure and confounders Outcome|Predictors Dependent variable|Independent variable(s) y|x

In R, formulas are used to declare relationships between variables. Formulas are common in classic statistical tests and in regression methods.

Formulas have the following standard syntax:

y ~ x, data = my_data

Where y is the outcome or response variable, x is the exposure or predictor of interest and my_data specifies the name of the data frame where x and y can be found.

The symbol ~ is used in R for formulas. It can be interpreted as depends on. In the most typical scenario, y ~ x means y depends on x or y is a function of x:

y = f(x)

Using epidemiology friendly terms:

Outcome = f(Exposure)

Is worth to mention that Stata requires for variables to be given in the same order as in formulas: outcome first, predictors next.

The pubh package integrates well with other packages of the tidyverse which use formulas and the pipe operator %>% to add layers over functions. In particular, pubh uses ggformula as a graphical interface for plotting and takes advantage of variable labels from sjlabelled. This versatility allows it to interact also with tables from moonBook and effect plots from sjPlot.

Stratification

One way to control for confounders is the use of stratification. In Stata stratification is done by including the by option as part of the command. In the ggformula package, one way of doing stratification is with a formula like:

y ~ x|z, data = my_data

Where y is the outcome or response variable, x is the exposure or predictor of interest, z is the stratification variable (a factor) and my_data specifies the name of the data frame where x, y and z can be found.

Pipes and the tidyverse

The tidyverse has become now the standard in data manipulation in R. The use of the pipe function %>% from magrittr allows for cleaner code. The principle of pipes is to change the paradigm in coding. In standard codding, when many functions are used, one goes from inner parenthesis to outer ones.

For example if we have three functions, a common syntax would look like:

f3(f2(f1(..., data), ...), ...)

With pipes, however, the code reads top to bottom and left to right:

data %>%
  f1(...) %>% 
  f2(...) %>% 
  f3(...)

Most of the functions from pubh are compatible with pipes and the tidyverse.

Contributions of the pubh package

The main contributions of the pubh package to students and professionals from the disciplines of Epidemiology and Public Health are:

  1. Use of a common syntax for the most used analysis.
  2. A function, glm_coef that displays coefficients from most common regression analysis in a way that can be easy interpreted and used for publications.
  3. Integration with the ggformula package, introducing plotting functions with a relatively simple syntax.
  4. Integration with the most common epidemiological analysis, using the standard formula syntax explained in the previous section.
  5. Integration with the gtsummary and huxtable packages. The pubh use huxtables as standard as they can be easily exported to html, pdf and doc files when knitting. Tables of descriptive statistics and of regression coefficients are generated through functions from gtsummary and then converted to huxtable objects with convenient cosmetics.

Descriptive statistics

Many options currently exists for displaying descriptive statistics. I recommend the function tbl_summary from the gtsummary package for constructing tables of descriptive statistics where results don't need to be stratified.

In Public Health and Epidemiology it is common to be interested on comparing cohorts, categorical variables considered as exposure of interest. The most classic example are randomised control trials where we want to compare treatment versus control cohorts. Package pubh introduces the function cross_tbl as a wrapper to tbl_summary from gtsummary. The idea is to construct these tables, in a simple way and convert them to huxtables.

The estat function from the pubh package displays descriptive statistics of continuous outcomes; it can use labels to display nice tables. As a way to aid in the understanding of the variability, estat displays also the relative dispersion (coefficient of variation) which is of particular interest for comparing variances between groups (factors).

Some examples. We start by loading packages.

rm(list = ls())
library(tidyverse)
library(rstatix)
library(jtools)
library(pubh)
library(sjlabelled)
library(sjPlot)

theme_set(sjPlot::theme_sjplot2(base_size = 10))
theme_update(legend.position = "top")
options('huxtable.knit_print_df' = FALSE)
options('huxtable.autoformat_number_format' = list(numeric = "%5.2f"))
knitr::opts_chunk$set(comment = NA)

We will use a data set about a study of onchocerciasis in Sierra Leone.

data(Oncho)
Oncho %>% head()

A two-by-two contingency table:

Oncho %>%
  mutate(
    mf = relevel(mf, ref = "Infected")
  ) %>%
  copy_labels(Oncho) %>%
  select(mf, area) %>% 
  cross_tbl(by = "area") %>%
  theme_pubh(2)

Table with all descriptive statistics except id and mfload:

Oncho %>%
  select(- c(id, mfload)) %>%
  mutate(
    mf = relevel(mf, ref = "Infected")
  ) %>%
  copy_labels(Oncho) %>%
  cross_tbl(by = "area") %>%
  theme_pubh(2)

Next, we use a data set about blood counts of T cells from patients in remission from Hodgkin's disease or in remission from disseminated malignancies. We generate the new variable Ratio and add labels to the variables.

data(Hodgkin)
Hodgkin <- Hodgkin %>%
  mutate(Ratio = CD4/CD8) %>%
  var_labels(
    Ratio = "CD4+ / CD8+ T-cells ratio"
    )

Hodgkin %>% head()

Descriptive statistics for CD4+ T cells:

Hodgkin %>%
  estat(~ CD4) %>%
  as_hux() %>% theme_pubh()

In the previous code, the left-hand side of the formula is empty as it's the case when working with only one variable.

For stratification, estat recognises the following two syntaxes:

where, outcome is continuous and exposure is a categorical (factor) variable.

For example:

Hodgkin %>%
  estat(~ Ratio|Group) %>%
  as_hux() %>% theme_pubh()

As before, we can report a table of descriptive statistics for all variables in the data set:

Hodgkin %>%
  mutate(
    Group = relevel(Group, ref = "Hodgkin")
  ) %>%
  copy_labels(Hodgkin) %>%
  cross_tbl(by = "Group", bold = FALSE) %>%
  theme_pubh(2) %>%
  add_footnote("Median (IQR)", font_size = 9)

Inferential statistics

From the descriptive statistics of Ratio we know that the relative dispersion in the Hodgkin group is almost as double as the relative dispersion in the Non-Hodgkin group.

For new users of R it helps to have a common syntax in most of the commands, as R could be challenging and even intimidating at times. We can test if the difference in variance is statistically significant with the var.test command, which uses can use a formula syntax:

var.test(Ratio ~ Group, data = Hodgkin)

What about normality? We can look at the QQ-plots against the standard Normal distribution.

Hodgkin %>%
  qq_plot(~ Ratio|Group) 

Let's say we choose a non-parametric test to compare the groups:

wilcox.test(Ratio ~ Group, data = Hodgkin)

Graphical output

For relatively small samples (for example, less than 30 observations per group) is a standard practice to show the actual data in dot plots with error bars. The pubh package offers two options to show graphically differences in continuous outcomes among groups:

For our current example:

Hodgkin %>%
  strip_error(Ratio ~ Group)

The error bars represent 95% confidence intervals around mean values.

Is relatively easy to add a line on top, to show that the two groups are significantly different. The function gf_star needs the reference point on how to draw an horizontal line to display statistical difference or to annotate a plot; in summary, gf_star:

Thus:

$$ y1 < y2 < y3 $$

In our current example:

Hodgkin %>%
  strip_error(Ratio ~ Group) %>%
  gf_star(x1 = 1, y1 = 4, x2 = 2, y2 = 4.05, y3 = 4.1, "**")

For larger samples we could use bar charts with error bars. For example:

data(birthwt, package = "MASS")
birthwt <- birthwt %>%
  mutate(
    smoke = factor(smoke, labels = c("Non-smoker", "Smoker")),
    Race = factor(race > 1, labels = c("White", "Non-white")),
    race = factor(race, labels = c("White", "Afican American", "Other"))
    ) %>%
  var_labels(
    bwt = 'Birth weight (g)',
    smoke = 'Smoking status',
    race = 'Race',
  )
birthwt %>%
  bar_error(bwt ~ smoke)

Quick normality check:

birthwt %>%
  qq_plot(~ bwt|smoke)

The (unadjusted) $t$-test:

birthwt %>% 
  t_test(bwt ~ smoke, detailed = TRUE) %>% 
  as.data.frame()

The final plot with annotation to highlight statistical difference (unadjusted):

birthwt %>%
  bar_error(bwt ~ smoke) %>%
  gf_star(x1 = 1, x2 = 2, y1 = 3400, y2 = 3500, y3 = 3550, "**")

Both strip_error and bar_error can generate plots stratified by a third variable, for example:

birthwt %>%
  bar_error(bwt ~ smoke, fill = ~ Race) %>%
  gf_refine(ggsci::scale_fill_jama()) 
birthwt %>%
  bar_error(bwt ~ smoke|Race)
birthwt %>%
  strip_error(bwt ~ smoke, pch = ~ Race, col = ~ Race) %>%
  gf_refine(ggsci::scale_color_jama())

Regression models

The pubh package includes the function cosm_reg, which adds some cosmetics to objects generated by tbl_regression and huxtable. The function multiple helps in the analysis and visualisation of multiple comparisons.

For simplicity, here we show the analysis of the linear model of smoking on birth weight, adjusting by race (and not by other potential confounders).

model_bwt <- lm(bwt ~ smoke + race, data = birthwt)
model_bwt %>% 
  tbl_regression() %>% 
  cosm_reg() %>% theme_pubh() %>% 
  add_footnote(get_r2(model_bwt), font_size = 9)

Similar results can be obtained with the function glm_coef.

model_bwt %>%
  glm_coef(labels = model_labels(model_bwt)) %>%
  as_hux() %>% theme_pubh() %>% 
  set_align(everywhere, 2:3, "right") %>%
  add_footnote(get_r2(model_bwt), font_size = 9)

In the last table of coefficients confidence intervals and p-values for levels of race are not adjusted for multiple comparisons. We can use functions from the emmeans package to make the corrections.

multiple(model_bwt, ~ race)$df
multiple(model_bwt, ~ race)$fig_ci %>%
  gf_labs(x = "Difference in birth weights (g)")
multiple(model_bwt, ~ race)$fig_pval %>%
  gf_labs(y = " ")

Epidemiology functions

The pubh package offers two wrappers to epiR functions.

  1. contingency calls epi.2by2 and it's used to analyse two by two contingency tables.
  2. diag_test calls epi.tests to compute statistics related with screening tests.

Contingency tables

Let's say we want to look at the effect of ibuprofen on preventing death in patients with sepsis.

data(Bernard)
Bernard %>% head()

Let's look at the table:

Bernard %>%
  mutate(
    fate = relevel(fate, ref = "Dead"),
    treat = relevel(treat, ref = "Ibuprofen")
  ) %>%
  copy_labels(Bernard) %>%
  select(fate, treat) %>% 
  cross_tbl(by = "treat") %>%
  theme_pubh(2)

For epi.2by2 we need to provide the table of counts in the correct order, so we would type something like:

dat <- matrix(c(84, 140 , 92, 139), nrow = 2, byrow = TRUE)
epiR::epi.2by2(as.table(dat))

For contingency we only need to provide the information in a formula:

Bernard %>%
  contingency(fate ~ treat) 

Advantages of contingency:

  1. Easier input without the need to create the table.
  2. Displays the standard epidemiological table at the start of the output. This aids to check what are the reference levels on each category.
  3. In the case that the $\chi^2$-test is not appropriate, contingency would show the results of the Fisher exact test at the end of the output.

Mantel-Haenszel odds ratio

For mhor the formula has the following syntax:

outcome ~ stratum/exposure, data = my_data

Thus, mhor displays the odds ratio of exposure yes against exposure no on outcome yes for different levels of stratum, as well as the Mantel-Haenszel pooled odds ratio.

Example: effect of eating chocolate ice cream on being ill by sex from the oswego data set.

data(oswego, package = "epitools")

oswego <- oswego %>%
  mutate(
    ill = factor(ill, labels = c("No", "Yes")),
    sex = factor(sex, labels = c("Female", "Male")),
    chocolate.ice.cream = factor(chocolate.ice.cream, labels = c("No", "Yes"))
  ) %>%
  var_labels(
    ill = "Developed illness",
    sex = "Sex",
    chocolate.ice.cream = "Consumed chocolate ice cream"
  )
oswego %>%
  mhor(ill ~ sex/chocolate.ice.cream)

Diagnostic tests

Example: We compare the use of lung’s X-rays on the screening of TB against the gold standard test.

Freq <- c(1739, 8, 51, 22)
BCG <- gl(2, 1, 4, labels=c("Negative", "Positive"))
Xray <- gl(2, 2, labels=c("Negative", "Positive"))
tb <- data.frame(Freq, BCG, Xray)
tb <- expand_df(tb)

diag_test(BCG ~ Xray, data = tb)

Using the immediate version (direct input):

diag_test2(22, 51, 8, 1739)


Try the pubh package in your browser

Any scripts or data that you put into this service are public.

pubh documentation built on Nov. 14, 2023, 1:08 a.m.