Session 5: Summarizing Your Data

Factors, counts and percentages, group_by() and summarise(), tabyl() cross-tabs, and a Table 1 with gtsummary

NoteIn this session you will learn to
  1. Put categories in a sensible order with factors
  2. Count categories and calculate percentages, overall and within groups
  3. Calculate summary statistics (mean, median, SD, …) by group with group_by() + summarise()
  4. Make frequency and cross-tabulation tables with tabyl()
  5. Make a publication-ready “Table 1” with gtsummary and save it to Word

Before you start: open the workshop folder in Positron (File → Open Folder…) and open student_scripts/Session 5 - Summarizing_STUDENT.R. This session starts from the files you saved in Session 3: processed_data/combined_linelist.rds and processed_data/measles_final.rds. Missed Session 3? Ready-made copies are already in processed_data/.

Where this session fits. Today covers Summarize and Save and share (highlighted): turning thousands of rows into counts, percentages, and statistics, and saving a finished table to Word.

  1. Import
  2. Inspect
  3. Clean
  4. Combine
  5. Reshape
  6. Summarize
  7. Visualize
  8. Save and share
  9. Automate

There are many packages for summary tables. This session uses three that cover almost every need: dplyr (count()/summarise()) for flexible summaries you can plot, janitor (tabyl()) for quick cross-tabs, and gtsummary for tables you publish.

Part 1: Set up

library(tidyverse)
library(here)
library(rio)
library(janitor)
library(gtsummary)

linelist <- import(here("processed_data", "combined_linelist.rds"), trust = TRUE)

glimpse(linelist)
Rows: 6,451
Columns: 19
$ case_id           <chr> "5fe599", "8689b7", "11f8ea", "b8812a", "893f25", "b…
$ gender            <chr> "male", "female", "male", "female", "male", "female"…
$ age_years         <dbl> 2, 3, 56, 18, 3, 16, 16, 0, 61, 27, 12, 42, 19, 7, 7…
$ age_cat           <chr> "Under 18", "Under 18", "50-59", "18-29", "Under 18"…
$ wt_kg             <dbl> 27, 25, 91, 41, 36, 56, 47, NA, 86, 69, 67, 84, 68, …
$ ht_cm             <dbl> 48, 59, 238, 135, 71, 116, 87, 11, 226, 174, 112, 18…
$ bmi               <dbl> NA, NA, 16.1, 22.5, NA, 41.6, NA, NA, 16.8, 22.8, 53…
$ date_of_infection <date> 2014-05-08, NA, NA, 2014-05-04, 2014-05-18, 2014-05…
$ onset_date        <date> 2014-05-13, 2014-05-13, 2014-05-16, 2014-05-18, 201…
$ hospital_date     <date> 2014-05-15, 2014-05-14, 2014-05-18, 2014-05-20, 201…
$ date_of_outcome   <date> NA, 2014-05-18, 2014-05-30, NA, 2014-05-29, 2014-05…
$ hospital_name     <chr> "Other/Unknown", "Other/Unknown", "St. Mark's Matern…
$ outcome           <chr> "Unknown", "Recover", "Recover", "Unknown", "Recover…
$ fever             <chr> "no", "Unknown", "Unknown", "no", "no", "no", "Unkno…
$ chills            <chr> "no", "Unknown", "Unknown", "no", "no", "no", "Unkno…
$ cough             <chr> "yes", "Unknown", "Unknown", "no", "yes", "yes", "Un…
$ aches             <chr> "no", "Unknown", "Unknown", "no", "no", "no", "Unkno…
$ vomit             <chr> "yes", "Unknown", "Unknown", "no", "yes", "yes", "Un…
$ temp              <dbl> 36.8, 36.9, 36.9, 36.8, 36.9, 37.6, 37.3, 37.0, 36.4…
Note🔍 What this code does
  • The library() lines load today’s five packages. gtsummary is new: it makes the Table 1 in Part 6.
  • import(here("processed_data", "combined_linelist.rds"), trust = TRUE) reads the file you saved at the end of Session 3. An .rds file can hold more than plain data, so rio asks you to confirm that you trust it: trust = TRUE.
  • glimpse() shows 6451 rows and 19 columns. age_cat and outcome are text (<chr>), so they sort alphabetically. Part 2 fixes that.

This is the dataset you finished in Session 3: cleaned, de-duplicated, and joined to the case information (symptoms and temperature).

Important✏️ TRY IT 1 (1 min): import the measles data

Import processed_data/measles_final.rds (with trust = TRUE) as measles.

✅ Check: in the Variables pane, measles shows 1163 rows and 14 columns

measles <- import(here("processed_data", "measles_final.rds"), trust = TRUE)
dim(measles)
[1] 1163   14

measles now appears in the Variables pane with 1163 rows and 14 columns.

Part 2: Putting categories in order (factors)

R sorts text alphabetically:

linelist %>% count(age_cat)
   age_cat    n
1    18-29 1455
2    30-39  582
3    40-49  245
4    50-59   77
5    60-69   27
6    70-79    6
7      80+    1
8 Under 18 3962
9  Unknown   96
Note🔍 What this code does
  • count(age_cat) lists the age groups in alphabetical order. Numbers sort before letters, so “18-29” comes first, and the biggest group, “Under 18” (3962 cases), ends up after “80+”.
  • This order would carry into every table and plot, which is why you set a better one next.

“Under 18” should come first, and “Unknown” last. A factor is a text column with a set order of categories (called levels). fct_relevel() from the forcats package (part of the tidyverse) sets that order:

linelist <- linelist %>%
  mutate(age_cat = fct_relevel(age_cat,
    "Under 18", "18-29", "30-39", "40-49", "50-59", "60-69", "70-79", "80+", "Unknown"
  ))

linelist %>% count(age_cat)
   age_cat    n
1 Under 18 3962
2    18-29 1455
3    30-39  582
4    40-49  245
5    50-59   77
6    60-69   27
7    70-79    6
8      80+    1
9  Unknown   96

The order carries through to every table and every plot. Other useful forcats functions:

  • fct_infreq() — order by how common each category is (most common first)
  • fct_rev() — reverse the order
  • fct_relevel(x, "Unknown", after = Inf) — move one category to the end
linelist <- linelist %>%
  mutate(outcome = fct_relevel(outcome, "Recover", "Death", "Unknown"))
Note🔍 What this code does
  • fct_relevel(age_cat, "Under 18", "18-29", ...) turns age_cat into a factor and sets its levels in the order you list them. mutate() puts the result back in the same column, and linelist <- saves it.
  • count(age_cat) now goes from youngest to oldest, with “Unknown” last. The counts didn’t change, only the order.
  • The second block does the same for outcome: Recover, Death, Unknown.
  • Each level has to be spelled exactly as in the data, capitals included.
Note

A .csv file can’t store factor order at all. An .rds file can, but the files we saved in Session 3 contain plain text columns, so you set the order again after importing.

WarningCommon mistakes
  • Misspelling a level: fct_relevel() warns “Unknown levels” and ignores it.
Note🔁 The base R way: factor()

In other people’s code you will see factor(x, levels = c(...)). It sets the order too, but a misspelled level is not ignored with a warning: every value that doesn’t match becomes NA, silently.

factor(c("Recover", "Death", "Death"), levels = c("Recover", "Death"))
[1] Recover Death   Death  
Levels: Recover Death
factor(c("Recover", "Death", "Death"), levels = c("Recover", "death"))   # oops: NA, no warning
[1] Recover <NA>    <NA>   
Levels: Recover death
Note🔍 What this code does
  • The first line makes a factor with the levels Recover, Death. R prints the values, then a Levels: line with their order.
  • In the second line, “death” (lower case) matches none of the values, so both “Death” values become <NA>, and R doesn’t warn you. fct_relevel() would have.

levels(x) shows the order of any factor. The forcats functions are safer for day-to-day work; factor() is what you need to read.

Important✏️ TRY IT 2 (3 min): order the measles categories

In measles, use fct_relevel() on:

  • age_cat: “Under 5”, “5-9”, “10-14”, “15+”, “Unknown”
  • vaccinated: “Yes”, “No”, “Unknown”
  • outcome: “Recovered”, “Died”, “Unknown”

✅ Check: count(age_cat) now starts with “Under 5”

measles <- measles %>%
  mutate(
    age_cat    = fct_relevel(age_cat, "Under 5", "5-9", "10-14", "15+", "Unknown"),
    vaccinated = fct_relevel(vaccinated, "Yes", "No", "Unknown"),
    outcome    = fct_relevel(outcome, "Recovered", "Died", "Unknown")
  )

measles %>% count(age_cat)
  age_cat   n
1 Under 5 369
2     5-9 352
3   10-14 217
4     15+ 196
5 Unknown  29

One mutate() can change several columns at once. The age groups now go from youngest to oldest, with “Unknown” last.

Note📖 Good to know
  • A factor stores each value as a number that points to its list of levels: that’s how it remembers the order. levels(x) shows the list, and as.character(x) turns a factor back into plain text.
  • The order matters in statistics too: in a regression model, the first level is the reference group that the others are compared with.

Part 3: Counting and percentages with count()

Counts and cross-tabs

linelist %>% count(outcome)
  outcome    n
1 Recover 2158
2   Death 2840
3 Unknown 1453
# Two columns: every combination
linelist %>% count(age_cat, outcome)
    age_cat outcome    n
1  Under 18 Recover 1322
2  Under 18   Death 1755
3  Under 18 Unknown  885
4     18-29 Recover  498
5     18-29   Death  648
6     18-29 Unknown  309
7     30-39 Recover  179
8     30-39   Death  256
9     30-39 Unknown  147
10    40-49 Recover   85
11    40-49   Death  105
12    40-49 Unknown   55
13    50-59 Recover   24
14    50-59   Death   29
15    50-59 Unknown   24
16    60-69 Recover   16
17    60-69   Death    8
18    60-69 Unknown    3
19    70-79 Recover    3
20    70-79   Death    3
21      80+ Recover    1
22  Unknown Recover   30
23  Unknown   Death   36
24  Unknown Unknown   30
Note🔍 What this code does
  • count(outcome) gives one row per outcome: Recover 2158, Death 2840, Unknown 1453. The rows follow the factor order you set in Part 2.
  • count(age_cat, outcome) counts every combination of age group and outcome that occurs: 24 rows. Combinations with no cases, such as 80+ and Death, are left out.

Percentages

count() makes a column called n. Divide by the total to get a proportion, and use scales::percent() to show it nicely:

linelist %>%
  count(outcome) %>%
  mutate(percent = scales::percent(n / sum(n), accuracy = 0.1))
  outcome    n percent
1 Recover 2158   33.5%
2   Death 2840   44.0%
3 Unknown 1453   22.5%
Note🔍 What this code does
  • count(outcome) puts the counts in a column called n.
  • Inside mutate(), sum(n) is the total of that column (6451), so n / sum(n) is each outcome’s share: 2840 / 6451 = 0.440 for Death.
  • scales::percent(..., accuracy = 0.1) shows 0.440 as “44.0%”. accuracy = 0.1 means one decimal place. The result is text: easy to read, but not for further calculations.

Percentages within groups: group_by()

group_by() makes the next steps happen separately for each group. Here, sum(n) becomes the total within each age group, so each age group adds up to 100%:

linelist %>%
  group_by(age_cat) %>%
  count(outcome) %>%
  mutate(percent = scales::percent(n / sum(n), accuracy = 0.1)) %>%
  ungroup()
# A tibble: 24 × 4
   age_cat  outcome     n percent
   <fct>    <fct>   <int> <chr>  
 1 Under 18 Recover  1322 33.4%  
 2 Under 18 Death    1755 44.3%  
 3 Under 18 Unknown   885 22.3%  
 4 18-29    Recover   498 34.2%  
 5 18-29    Death     648 44.5%  
 6 18-29    Unknown   309 21.2%  
 7 30-39    Recover   179 30.8%  
 8 30-39    Death     256 44.0%  
 9 30-39    Unknown   147 25.3%  
10 40-49    Recover    85 34.7%  
# ℹ 14 more rows
Note🔍 What this code does
  • group_by(age_cat) splits the rows into one group per age group. The data looks the same, but the next steps run once for each group.
  • count(outcome) then counts the outcomes inside each age group.
  • In mutate(), sum(n) is now the total of that age group, so each age group adds up to 100%. For example, 44.3% of the under-18s died (1755 of 3962).
  • ungroup() removes the grouping, so later steps work on all the rows again.

Without grouping, the percentages are out of all 6,451 cases, so all the rows together add up to 100%. With group_by(age_cat), each age group adds up to 100% on its own.

Tipungroup() when you’re done

A grouped data frame stays grouped. End with ungroup() so later steps don’t surprise you.

Note🔁 The base R way: table() and prop.table()

Base R makes a cross-table with table() (from Session 1), and turns it into proportions with prop.table(). margin = 1 makes each row add up to 1, like group_by(age_cat) above:

age_outcome <- table(linelist$age_cat, linelist$outcome)
age_outcome
          
           Recover Death Unknown
  Under 18    1322  1755     885
  18-29        498   648     309
  30-39        179   256     147
  40-49         85   105      55
  50-59         24    29      24
  60-69         16     8       3
  70-79          3     3       0
  80+            1     0       0
  Unknown       30    36      30
round(prop.table(age_outcome, margin = 1) * 100, 1)
          
           Recover Death Unknown
  Under 18    33.4  44.3    22.3
  18-29       34.2  44.5    21.2
  30-39       30.8  44.0    25.3
  40-49       34.7  42.9    22.4
  50-59       31.2  37.7    31.2
  60-69       59.3  29.6    11.1
  70-79       50.0  50.0     0.0
  80+        100.0   0.0     0.0
  Unknown     31.2  37.5    31.2
Note🔍 What this code does
  • table(linelist$age_cat, linelist$outcome) makes a cross-table: age groups down the side, outcomes across the top, and a count in each cell. It’s saved as age_outcome so you can reuse it.
  • prop.table(age_outcome, margin = 1) divides each cell by its row total, so each row adds up to 1. * 100 and round(..., 1) turn that into percentages: the same numbers as the group_by() version (44.3 for Under 18 and Death).
  • Unlike count(), table() shows combinations with no cases as 0.

The result is a table, not a data frame, so it doesn’t work with filter(), mutate(), or ggplot. That is why we use count() in this workshop.

Important✏️ TRY IT 3 (5 min): vaccination coverage
  1. What percentage of measles cases were vaccinated?
  2. Within each age group, what percentage were vaccinated? Which age group has the lowest percentage?

✅ Check: a) Yes 23.8% b) 10-14 is lowest at 21.2%

# a)
measles %>%
  count(vaccinated) %>%
  mutate(percent = scales::percent(n / sum(n), accuracy = 0.1))
  vaccinated   n percent
1        Yes 277   23.8%
2         No 709   61.0%
3    Unknown 177   15.2%
# b)
measles %>%
  group_by(age_cat) %>%
  count(vaccinated) %>%
  mutate(percent = scales::percent(n / sum(n), accuracy = 0.1)) %>%
  ungroup()
# A tibble: 15 × 4
   age_cat vaccinated     n percent
   <fct>   <fct>      <int> <chr>  
 1 Under 5 Yes           83 22.5%  
 2 Under 5 No           235 63.7%  
 3 Under 5 Unknown       51 13.8%  
 4 5-9     Yes           83 23.6%  
 5 5-9     No           210 59.7%  
 6 5-9     Unknown       59 16.8%  
 7 10-14   Yes           46 21.2%  
 8 10-14   No           138 63.6%  
 9 10-14   Unknown       33 15.2%  
10 15+     Yes           54 27.6%  
11 15+     No           113 57.7%  
12 15+     Unknown       29 14.8%  
13 Unknown Yes           11 37.9%  
14 Unknown No            13 44.8%  
15 Unknown Unknown        5 17.2%  

Fewer than a quarter of all cases were vaccinated. In b), each age group adds up to 100%, so you can compare groups: 10-14 year olds have the lowest coverage, at 21.2%.

Note📖 Good to know
  • Always ask “percent of what?” Of all cases, of each age group, or only of cases with a known value? Here the “Unknown” outcomes are part of the total, so leaving them out would change every percentage.
  • scales::percent() gives text. To plot or calculate with a percentage, keep the plain proportion (n / sum(n)) as well.

Part 4: Summary statistics with summarise()

summarise() collapses many rows into one row of results. You name each new column on the left of =.

linelist %>%
  summarise(
    n          = n(),
    mean_age   = mean(age_years, na.rm = TRUE),
    sd_age     = sd(age_years, na.rm = TRUE),
    median_age = median(age_years, na.rm = TRUE)
  )
     n mean_age   sd_age median_age
1 6451 16.05732 12.64829         13

na.rm = TRUE means “skip missing values”. Without it, one NA makes the whole result NA.

Note🔍 What this code does
  • summarise() collapses all 6451 rows into one row. Each name = calculation inside it makes one column of the result.
  • n() counts the rows: 6451.
  • mean() is the average age (about 16.1 years). sd() is the standard deviation (about 12.6): how spread out the ages are. median() is the middle value: 13.
  • 96 patients have no age, so without na.rm = TRUE the mean, SD, and median would all be NA.

By group

Add group_by() first to get one row per group:

linelist %>%
  group_by(outcome) %>%
  summarise(
    n          = n(),
    mean_age   = mean(age_years, na.rm = TRUE),
    median_age = median(age_years, na.rm = TRUE),
    mean_bmi   = mean(bmi, na.rm = TRUE),
    mean_temp  = mean(temp, na.rm = TRUE)
  )
# A tibble: 3 × 6
  outcome     n mean_age median_age mean_bmi mean_temp
  <fct>   <int>    <dbl>      <dbl>    <dbl>     <dbl>
1 Recover  2158     16.1         13     30.6      38.6
2 Death    2840     15.9         13     30.7      38.6
3 Unknown  1453     16.2         14     30.4      38.6
Tip🧩 Reading a function call

Here is a shorter version of the code above, taken apart:

linelist %>% group_by(outcome) %>% summarise(n = n(), mean_age = mean(age_years, na.rm = TRUE))

Piece What it is What it does
linelist the data where the steps start
%>% the pipe passes the result on its left into the next function, as its first argument
group_by(outcome) a dplyr function splits the rows into one group per outcome
summarise(...) a dplyr function collapses each group into one row of results
n = n() a new column called n, made by the function n() counts the rows in each group
mean_age = mean(age_years, ...) a new column called mean_age, made by mean() the average age in each group
na.rm = TRUE a named argument of mean() “remove NAs”: skip the missing ages

Inside summarise(), the name on the left of = is the new column, and the calculation is on the right. With the pipe, R runs the steps from left to right. Read each %>% as “and then”: “take linelist, and then group it by outcome, and then summarise: n is the number of rows, and mean_age is the mean of age_years, skipping missing values.”

Note🔍 What this code does
  • group_by(outcome) before summarise() gives one row per outcome instead of one row for everyone.
  • Each row is calculated only from its own group: 2158 patients who recovered, 2840 who died, and 1453 with an unknown outcome.
  • In this fictional dataset the groups are very similar: the median age is 13 for both recovered and died, and the mean temperature is 38.6 °C in all three groups.
NoteUseful summary functions

Centre: mean(), median() · Spread: sd(), IQR(), min(), max(), quantile(x, 0.25) · Counts: n(), n_distinct(), sum(is.na(x))

The same calculation on many columns: across()

You met across() in Session 3. In summarise() it saves a lot of typing:

linelist %>%
  group_by(outcome) %>%
  summarise(across(c(age_years, bmi, temp), ~ mean(.x, na.rm = TRUE)))
# A tibble: 3 × 4
  outcome age_years   bmi  temp
  <fct>       <dbl> <dbl> <dbl>
1 Recover      16.1  30.6  38.6
2 Death        15.9  30.7  38.6
3 Unknown      16.2  30.4  38.6
Note🔍 What this code does
  • across(c(age_years, bmi, temp), ...) does the same calculation on each of the three columns.
  • ~ mean(.x, na.rm = TRUE) is the calculation. The ~ starts a short formula, and .x stands for “the current column”: first age_years, then bmi, then temp.
  • The results keep the original column names, so each of age_years, bmi, and temp now holds a mean.

Percentages of “yes”

fever == "yes" is TRUE or FALSE for each row (vectorization, from Session 4). sum() counts the TRUEs, and mean() gives the proportion that are TRUE:

linelist %>%
  group_by(outcome) %>%
  summarise(
    n_cases   = n(),
    n_fever   = sum(fever == "yes"),
    pct_fever = round(mean(fever == "yes") * 100, 1),
    pct_cough = round(mean(cough == "yes") * 100, 1),
    pct_vomit = round(mean(vomit == "yes") * 100, 1)
  )
# A tibble: 3 × 6
  outcome n_cases n_fever pct_fever pct_cough pct_vomit
  <fct>     <int>   <int>     <dbl>     <dbl>     <dbl>
1 Recover    2158    1708      79.1      82        47.9
2 Death      2840    2245      79        82.9      48.8
3 Unknown    1453    1124      77.4      84.2      46.5
Note🔍 What this code does
  • fever == "yes" is TRUE for each patient with fever and FALSE for everyone else.
  • sum(fever == "yes") counts the TRUEs (each TRUE counts as 1): 1708 of the patients who recovered had fever.
  • mean(fever == "yes") is the share that are TRUE: 1708 / 2158 = 0.791. * 100 and round(..., 1) turn that into 79.1.
  • Patients whose fever is “Unknown” count as “not yes”, so these percentages are out of all patients in the group.
Note🔁 The base R way: tapply() and aggregate()

Two base R functions do what group_by() + summarise() does for one statistic:

tapply(linelist$age_years, linelist$outcome, median, na.rm = TRUE)   # a named vector
Recover   Death Unknown 
     13      13      14 
aggregate(age_years ~ outcome, data = linelist, FUN = median)        # a data frame
  outcome age_years
1 Recover        13
2   Death        13
3 Unknown        14
Note🔍 What this code does
  • tapply(linelist$age_years, linelist$outcome, median, na.rm = TRUE) splits age_years by outcome and runs median() on each piece. The result is a named vector: 13, 13, 14.
  • aggregate(age_years ~ outcome, data = linelist, FUN = median) gives the same medians as a data frame. Read age_years ~ outcome as “age_years by outcome”.
  • Before calculating, aggregate() quietly leaves out the 96 rows with no age. Here that doesn’t change the medians.

Read tapply(X, GROUP, FUNCTION) as “apply FUNCTION to X, split by GROUP”. aggregate() with a formula silently drops rows with a missing value, one reason summarise() (where you choose with na.rm) is clearer.

TipSave summaries as objects

Every result here is a data frame. Save it with <- and you can plot it (Sessions 6 and 7), join it, or export it like any other data.

Important✏️ TRY IT 4 (4 min): statistics by outcome

For each measles outcome, calculate the number of cases, mean and median age, mean temperature, and mean days in hospital (careful: NAs!).

✅ Check: Recovered n = 1048, median age 7; Died n = 50, median age 5

measles %>%
  group_by(outcome) %>%
  summarise(
    n          = n(),
    mean_age   = mean(age_years, na.rm = TRUE),
    median_age = median(age_years, na.rm = TRUE),
    mean_temp  = mean(temp_c),
    mean_days  = mean(days_in_hospital, na.rm = TRUE)
  )
# A tibble: 3 × 6
  outcome       n mean_age median_age mean_temp mean_days
  <fct>     <int>    <dbl>      <dbl>     <dbl>     <dbl>
1 Recovered  1048     8.92          7      38.8      4.94
2 Died         50     6.80          5      38.8      4.55
3 Unknown      65     7.47          5      38.7      5.12

Children who died were younger than children who recovered (median age 5 vs 7). days_in_hospital is missing for patients who were never hospitalized, so it needs na.rm = TRUE.

Important✏️ TRY IT 5 (4 min): case rates by district

Calculate cases per 10,000 people by district (number of cases / population * 10000), sorted highest first.

Hint: count(district, population) gives both columns; then mutate() and arrange(desc()).

✅ Check: East has the highest rate (22.8); Central the lowest (5.2)

measles %>%
  count(district, population) %>%
  mutate(rate_per_10k = round(n / population * 10000, 1)) %>%
  arrange(desc(rate_per_10k))
  district population   n rate_per_10k
1     East      98000 223         22.8
2     West      76500 170         22.2
3    South     142000 284         20.0
4    North     185000 342         18.5
5  Central     210000 110          5.2
6  Unknown         NA  34           NA

Central has the most people but the lowest rate: raw counts and rates can tell different stories. The “Unknown” district has no population, so it gets no rate.

Note📖 Good to know
  • Mean or median? A few large values pull the mean up, but barely move the median. Ages here are skewed toward children: the mean age is 16.1, the median 13. For skewed numbers like ages, incomes, or days in hospital, the median is usually the better summary.
  • n() counts all rows, including rows with missing values. To count only the non-missing values of a column, use sum(!is.na(x)).

Part 5: Quick tables with tabyl()

tabyl() from janitor makes frequency tables with percentages in one step:

linelist %>% tabyl(outcome)
 outcome    n   percent
 Recover 2158 0.3345218
   Death 2840 0.4402418
 Unknown 1453 0.2252364
linelist %>% tabyl(age_cat, outcome)
  age_cat Recover Death Unknown
 Under 18    1322  1755     885
    18-29     498   648     309
    30-39     179   256     147
    40-49      85   105      55
    50-59      24    29      24
    60-69      16     8       3
    70-79       3     3       0
      80+       1     0       0
  Unknown      30    36      30
Note🔍 What this code does
  • tabyl(outcome) counts each outcome (n) and adds its share (percent) as a proportion: 0.3345 for Recover means 33.5%.
  • tabyl(age_cat, outcome) makes a cross-table: the first column goes down the side, the second across the top, and each cell is a count. Unlike count(), it’s wide, like a table in a paper, and it shows empty combinations as 0.

The adorn_ functions add totals and percentages. The order matters:

  1. adorn_totals() — needs the raw counts, so it goes first
  2. adorn_percentages() — turns counts into proportions ("row" by default, or "col")
  3. adorn_pct_formatting() — shows them as percentages
  4. adorn_ns() — adds the counts back in brackets
  5. adorn_title() — adds a title, last
linelist %>%
  tabyl(age_cat, outcome) %>%
  adorn_totals("row") %>%
  adorn_percentages("row") %>%
  adorn_pct_formatting(digits = 1) %>%
  adorn_ns() %>%
  adorn_title("combined")
 age_cat/outcome        Recover         Death       Unknown
        Under 18  33.4% (1,322) 44.3% (1,755) 22.3%   (885)
           18-29  34.2%   (498) 44.5%   (648) 21.2%   (309)
           30-39  30.8%   (179) 44.0%   (256) 25.3%   (147)
           40-49  34.7%    (85) 42.9%   (105) 22.4%    (55)
           50-59  31.2%    (24) 37.7%    (29) 31.2%    (24)
           60-69  59.3%    (16) 29.6%     (8) 11.1%     (3)
           70-79  50.0%     (3) 50.0%     (3)  0.0%     (0)
             80+ 100.0%     (1)  0.0%     (0)  0.0%     (0)
         Unknown  31.2%    (30) 37.5%    (36) 31.2%    (30)
           Total  33.5% (2,158) 44.0% (2,840) 22.5% (1,453)
Note🔍 What this code does
  • adorn_totals("row") adds a Total row at the bottom, from the raw counts.
  • adorn_percentages("row") turns each count into its share of the row, so each row adds up to 100%.
  • adorn_pct_formatting(digits = 1) shows those shares as percentages with one decimal.
  • adorn_ns() adds the counts back in brackets: “44.3% (1,755)” means 1755 under-18s died, 44.3% of that age group.
  • adorn_title("combined") puts both variable names in the top-left corner: age_cat/outcome.
Important✏️ TRY IT 6 (4 min): vaccination and death

Make a tabyl() of vaccinated by outcome in measles, with row percentages and counts. What do you notice about deaths?

✅ Check: 6.3% of unvaccinated cases died, vs 0.7% of vaccinated cases

measles %>%
  tabyl(vaccinated, outcome) %>%
  adorn_percentages("row") %>%
  adorn_pct_formatting(digits = 1) %>%
  adorn_ns()
 vaccinated   Recovered      Died   Unknown
        Yes 92.1% (255) 0.7%  (2) 7.2% (20)
         No 88.7% (629) 6.3% (45) 4.9% (35)
    Unknown 92.7% (164) 1.7%  (3) 5.6% (10)

Unvaccinated cases died far more often than vaccinated cases (6.3% vs 0.7%). Remember that this is fictional practice data, and a simple cross-tab like this can’t account for other differences between the groups (such as age).

Part 6: Table 1 with gtsummary

Most papers start with a “Table 1” that describes the study population. tbl_summary() makes one from a data frame: it detects which columns are numbers and which are categories.

linelist %>%
  filter(outcome != "Unknown") %>%
  mutate(outcome = fct_drop(outcome)) %>%     # drop the now-empty "Unknown" level
  select(outcome, gender, age_years, age_cat, bmi, hospital_name, fever, cough, temp) %>%
  tbl_summary(by = outcome)
Characteristic Recover
N = 2,1581
Death
N = 2,8401
gender

    Unknown 86 (4.0%) 139 (4.9%)
    female 1,041 (48%) 1,337 (47%)
    male 1,031 (48%) 1,364 (48%)
age_years 13 (6, 23) 13 (7, 23)
    Unknown 30 36
age_cat

    Under 18 1,322 (61%) 1,755 (62%)
    18-29 498 (23%) 648 (23%)
    30-39 179 (8.3%) 256 (9.0%)
    40-49 85 (3.9%) 105 (3.7%)
    50-59 24 (1.1%) 29 (1.0%)
    60-69 16 (0.7%) 8 (0.3%)
    70-79 3 (0.1%) 3 (0.1%)
    80+ 1 (<0.1%) 0 (0%)
    Unknown 30 (1.4%) 36 (1.3%)
bmi 29 (23, 37) 29 (23, 37)
    Unknown 450 578
hospital_name

    Central Hospital 165 (7.6%) 193 (6.8%)
    HMO Health 94 (4.4%) 124 (4.4%)
    Military Hospital 309 (14%) 399 (14%)
    Other/Unknown 804 (37%) 1,006 (35%)
    Premiere Health 81 (3.8%) 129 (4.5%)
    Regional Medical center 579 (27%) 790 (28%)
    St. Mark's Maternity Hospital 126 (5.8%) 199 (7.0%)
fever

    Unknown 79 (3.7%) 123 (4.3%)
    no 371 (17%) 472 (17%)
    yes 1,708 (79%) 2,245 (79%)
cough

    Unknown 79 (3.7%) 123 (4.3%)
    no 310 (14%) 362 (13%)
    yes 1,769 (82%) 2,355 (83%)
temp 38.80 (38.20, 39.30) 38.80 (38.30, 39.20)
    Unknown 55 61
1 n (%); Median (Q1, Q3)
Note🔍 What this code does
  • filter(outcome != "Unknown") keeps the 4998 patients with a known outcome, and fct_drop() removes the now-empty “Unknown” level.
  • select() chooses what goes in the table: each selected column becomes one variable in Table 1. by = outcome makes the outcomes the column groups.
  • tbl_summary() works out each column’s type. Categories (like gender) show count (%). Numbers (like age_years) show the median and, in brackets, the 25th and 75th percentiles: 13 (6, 23) years for patients who recovered.
  • The headers show the size of each group: N = 2,158 recovered and N = 2,840 died.
  • Two kinds of “Unknown” appear: our own “Unknown” text values, shown as a category (86 recovered patients have an unknown gender), and gtsummary’s row for missing values, which it also calls “Unknown” (30 missing ages). The next step sorts this out.

“Unknown” shows up as a category. In Session 3 we replaced NA with “Unknown” so missing values show up in counts — but tbl_summary() has its own Missing row, so turn “Unknown” back into NA for this table with na_if():

linelist %>%
  filter(outcome != "Unknown") %>%
  mutate(outcome = fct_drop(outcome)) %>%
  select(outcome, gender, age_years, age_cat, bmi, hospital_name, fever, cough, temp) %>%
  mutate(across(where(is.character), ~ na_if(.x, "Unknown"))) %>%
  tbl_summary(by = outcome)
Characteristic Recover
N = 2,1581
Death
N = 2,8401
gender

    female 1,041 (50%) 1,337 (50%)
    male 1,031 (50%) 1,364 (50%)
    Unknown 86 139
age_years 13 (6, 23) 13 (7, 23)
    Unknown 30 36
age_cat

    Under 18 1,322 (61%) 1,755 (62%)
    18-29 498 (23%) 648 (23%)
    30-39 179 (8.3%) 256 (9.0%)
    40-49 85 (3.9%) 105 (3.7%)
    50-59 24 (1.1%) 29 (1.0%)
    60-69 16 (0.7%) 8 (0.3%)
    70-79 3 (0.1%) 3 (0.1%)
    80+ 1 (<0.1%) 0 (0%)
    Unknown 30 (1.4%) 36 (1.3%)
bmi 29 (23, 37) 29 (23, 37)
    Unknown 450 578
hospital_name

    Central Hospital 165 (7.6%) 193 (6.8%)
    HMO Health 94 (4.4%) 124 (4.4%)
    Military Hospital 309 (14%) 399 (14%)
    Other/Unknown 804 (37%) 1,006 (35%)
    Premiere Health 81 (3.8%) 129 (4.5%)
    Regional Medical center 579 (27%) 790 (28%)
    St. Mark's Maternity Hospital 126 (5.8%) 199 (7.0%)
fever 1,708 (82%) 2,245 (83%)
    Unknown 79 123
cough 1,769 (85%) 2,355 (87%)
    Unknown 79 123
temp 38.80 (38.20, 39.30) 38.80 (38.30, 39.20)
    Unknown 55 61
1 n (%); Median (Q1, Q3)
Note🔍 What this code does
  • mutate(across(where(is.character), ~ na_if(.x, "Unknown"))) goes through every text column (where(is.character)) and replaces the value “Unknown” with NA.
  • Gender’s unknowns (86 and 139) move from a category into the missing-values row.
  • fever and cough now only have “yes” and “no”, so gtsummary shows them on one line: the number with “yes”. For fever that’s 1,708 (82%) of the patients who recovered. The percentage is now out of patients whose fever status is known, which is why it’s higher than the 79.1% in Part 4.
  • age_cat is a factor, not text, so where(is.character) skips it and its “Unknown” stays a category.
WarningCommon mistakes
  • After filter(outcome != "Unknown"), the empty level is still there. fct_drop(outcome) removes it, or tbl_summary() shows an empty column.

Customize it

table1 <- linelist %>%
  filter(outcome != "Unknown") %>%
  mutate(outcome = fct_drop(outcome)) %>%
  select(outcome, gender, age_years, bmi, hospital_name, fever, cough, temp) %>%
  mutate(across(where(is.character), ~ na_if(.x, "Unknown"))) %>%
  tbl_summary(
    by = outcome,
    label = list(
      gender        ~ "Gender",
      age_years     ~ "Age (years)",
      bmi           ~ "BMI",
      hospital_name ~ "Hospital",
      fever         ~ "Fever",
      cough         ~ "Cough",
      temp          ~ "Temperature (°C)"
    ),
    statistic = all_continuous() ~ "{mean} ({sd})",
    missing_text = "Missing"
  ) %>%
  add_overall() %>%
  bold_labels() %>%
  modify_caption("**Table 1. Patient characteristics by outcome**")

table1
Table 1. Patient characteristics by outcome
Characteristic Overall
N = 4,9981
Recover
N = 2,1581
Death
N = 2,8401
Gender


    female 2,378 (50%) 1,041 (50%) 1,337 (50%)
    male 2,395 (50%) 1,031 (50%) 1,364 (50%)
    Missing 225 86 139
Age (years) 16 (13) 16 (13) 16 (12)
    Missing 66 30 36
BMI 31 (10) 31 (10) 31 (10)
    Missing 1,028 450 578
Hospital


    Central Hospital 358 (7.2%) 165 (7.6%) 193 (6.8%)
    HMO Health 218 (4.4%) 94 (4.4%) 124 (4.4%)
    Military Hospital 708 (14%) 309 (14%) 399 (14%)
    Other/Unknown 1,810 (36%) 804 (37%) 1,006 (35%)
    Premiere Health 210 (4.2%) 81 (3.8%) 129 (4.5%)
    Regional Medical center 1,369 (27%) 579 (27%) 790 (28%)
    St. Mark's Maternity Hospital 325 (6.5%) 126 (5.8%) 199 (7.0%)
Fever 3,953 (82%) 1,708 (82%) 2,245 (83%)
    Missing 202 79 123
Cough 4,124 (86%) 1,769 (85%) 2,355 (87%)
    Missing 202 79 123
Temperature (°C) 38.59 (0.96) 38.59 (0.98) 38.59 (0.95)
    Missing 116 55 61
1 n (%); Mean (SD)
  • statistic: "{median} ({p25}, {p75})" is the default for numbers; we switched to mean (SD)
  • add_overall() adds a column for all patients
  • add_p() would add p-values comparing the groups — only use it if a statistical test is part of your analysis plan

Save it to Word

as_flex_table() turns the table into a flextable, and save_as_docx() writes the Word file. The new file appears in the outputs/ folder in the Explorer.

table1 %>%
  as_flex_table() %>%
  flextable::save_as_docx(path = here("outputs", "table1.docx"))
Note🔍 What this code does
  • label = list(gender ~ "Gender", ...) gives each row a readable name. Read each ~ as “gets the label”.
  • statistic = all_continuous() ~ "{mean} ({sd})" shows mean (SD) instead of median and percentiles for every number column. gtsummary fills in the words in { }.
  • missing_text = "Missing" renames gtsummary’s missing-values row from “Unknown” to “Missing”, so it can’t be confused with a category.
  • add_overall() adds a column for all patients together, bold_labels() makes the variable names bold, and modify_caption() adds the title (the ** make it bold).
  • In the second block, as_flex_table() turns the table into a flextable, and flextable::save_as_docx() writes it to the Word file outputs/table1.docx.
Important✏️ TRY IT 7 (6 min): a measles Table 1

Make a tbl_summary() of measles cases by outcome (leave out “Unknown” outcomes) with sex, age_years, age_cat, vaccinated, rash, temp_c, and days_in_hospital. Give the rows nice labels and add an overall column.

✅ Check: the column headers say Overall N = 1,098, Recovered N = 1,048, Died N = 50

measles_table1 <- measles %>%
  filter(outcome != "Unknown") %>%
  mutate(outcome = fct_drop(outcome)) %>%
  select(outcome, sex, age_years, age_cat, vaccinated, rash, temp_c, days_in_hospital) %>%
  mutate(across(where(is.character), ~ na_if(.x, "Unknown"))) %>%
  tbl_summary(
    by = outcome,
    label = list(
      sex              ~ "Sex",
      age_years        ~ "Age (years)",
      age_cat          ~ "Age group",
      vaccinated       ~ "Vaccinated",
      rash             ~ "Rash",
      temp_c           ~ "Temperature (°C)",
      days_in_hospital ~ "Days in hospital"
    ),
    missing_text = "Missing"
  ) %>%
  add_overall() %>%
  bold_labels()

measles_table1
Characteristic Overall
N = 1,0981
Recovered
N = 1,0481
Died
N = 501
Sex


    female 483 (46%) 456 (45%) 27 (55%)
    male 577 (54%) 555 (55%) 22 (45%)
    Missing 38 37 1
Age (years) 7 (4, 12) 7 (4, 12) 5 (2, 10)
    Missing 28 27 1
Age group


    Under 5 343 (31%) 319 (30%) 24 (48%)
    5-9 333 (30%) 321 (31%) 12 (24%)
    10-14 205 (19%) 198 (19%) 7 (14%)
    15+ 189 (17%) 183 (17%) 6 (12%)
    Unknown 28 (2.6%) 27 (2.6%) 1 (2.0%)
Vaccinated


    Yes 257 (23%) 255 (24%) 2 (4.0%)
    No 674 (61%) 629 (60%) 45 (90%)
    Unknown 167 (15%) 164 (16%) 3 (6.0%)
Rash 919 (84%) 875 (83%) 44 (88%)
Temperature (°C) 38.90 (38.40, 39.40) 38.90 (38.40, 39.40) 38.90 (38.00, 39.50)
Days in hospital 5 (3, 6) 5 (3, 6) 5 (3, 5)
    Missing 697 658 39
1 n (%); Median (Q1, Q3)

“Missing” for days in hospital doesn’t mean the data were lost: those patients were never hospitalized. age_cat and vaccinated are factors, so na_if() (which only touches text columns here) leaves their “Unknown” level as a category.

Note📖 Good to know
  • A Table 1 usually shows categories as n (%) and numbers as median (IQR) or mean (SD), and reports missing values. Many journals, and the CONSORT guidelines for trials, advise against p-values in a Table 1 that describes the groups.
  • If something in the Word table needs to change, change the code and save the table again, rather than editing the Word file by hand. That way the table always matches the data.
  • gtsummary can also make tables of regression results (tbl_regression()), with the same style.
Tip⭐ Bonus
  1. Save your measles table to Word as outputs/measles_table1.docx.
  2. Use pivot_wider() (Session 4) to turn count(district, outcome) into a district × outcome table.
  3. Brought your own data? Make a Table 1 of it.

See the solutions file for the code.

Key points

  • Factors set the order of categories; fct_relevel() puts them in a sensible order that carries through to every table and plot.
  • count() counts categories; mutate(percent = n / sum(n)) adds percentages.
  • group_by() makes the next steps happen separately for each group — end with ungroup().
  • summarise() collapses rows into summary statistics; use na.rm = TRUE to skip missing values, and across() to do the same thing on many columns.
  • tabyl() + the adorn_*() functions (in order: totals, percentages, formatting, ns, title) make quick cross-tabs.
  • tbl_summary() makes a publication-ready Table 1; as_flex_table() + flextable::save_as_docx() saves it to Word.

Next: Session 6 — Plotting basics. We build plots with ggplot2 from the ground up: histograms, scatter plots, and box plots.