Advanced Tidyverse Workflows and Tidy Evaluation
7 min read
Welcome to the deep end of the pool! πββοΈ Don't worry, the water is fine, and we have floaties (documentation).
Up until now, you've likely been treating data frames like Excel sheets on steroids: rows are observations, columns are atomic values (numbers, strings, factors). But what if I told you that a single cell in your data frame could contain... another entire data frame? Or a linear regression model? Or a plot?
In this module, we are going to level up your data engineering skills. We will move from simple data manipulation to functional programming inside data frames, and finally, we will tackle the final boss of R programming: Tidy Evaluation (writing your own functions that use dplyr).
Let's get tidy. π§Ή
1. List-Columns: Storing Complex Data (nest())
The Definition
A List-Column is exactly what it sounds like: a column in a tibble (data frame) where the datatype is a list. Because lists in R can contain anything (vectors, other lists, models, data frames), a list-column allows you to store complex objects aligned with your grouping variables.
The Problem
Imagine you are analyzing sales data for 50 different countries. You want to run a separate analysis for each country.
- The Old Way: You split the data frame into a list of 50 data frames, losing the connection to the other columns, or you create 50 separate variables (e.g.,
usa_df,canada_df), polluting your global environment. - The Messy Way: You keep everything in one huge sheet and use complex grouping indices.
The Solution: nest()
The nest() function from the tidyr package takes a group of rows and compresses them into a single list-column containing a data frame.
The Workflow:
- Group your data.
- Nest the data.
- Now you have one row per group, and the data for that group is tucked away in a cell.
π» Hands-on Code
Let's use the classic gapminder dataset (life expectancy data) to visualize this.
library(tidyverse)
library(gapminder)
# We want to treat each Country as an individual unit of analysis
nested_gap <- gapminder %>%
group_by(country, continent) %>%
nest()
# Let's look at what we created
print(nested_gap)Output Interpretation:
You will see a column usually named data (or whatever you named it). It will look like this: <tibble [12 Γ 4]>.
This means inside that single cell, there is a tiny tibble with 12 rows and 4 columns representing that specific country's data.
Why is this cool?
Your data frame is now a meta-table. It summarizes the structure of your data. You haven't lost the data; you've just organized it like a bento box. π±
2. Mapping over List-Columns: A Modeling Workflow
The Definition
Mapping is the process of applying a function to each element of a list (or vector) and returning the results in a new list (or vector). In the Tidyverse, we use the purrr package (specifically map()) to do this.
The Problem
You have your nested data (50 countries). Now you want to fit a linear model (lifeExp ~ year) for each country to see if life expectancy is improving.
- The Loop Way: You write a
forloop. It breaks. You cry. You debug. It works, but the results are a messy list of models disconnected from the country names.
The Solution: mutate() + map()
Since your data is in a column, and mutate() creates new columns based on existing ones, you can use mutate() to apply a function to your list-column!
We keep the data, the model, and the results all in the same row, perfectly aligned.
π» Hands-on Code
We will use broom::tidy() here. If you don't know it, broom converts ugly statistical model objects into pretty tibbles.
library(broom)
# 1. Define a function to run our model
country_model <- function(df) {
lm(lifeExp ~ year, data = df)
}
# 2. The Power Move: Map inside Mutate
models_df <- nested_gap %>%
mutate(
# Apply the model to every tibble in the 'data' column
model = map(data, country_model),
# Extract the coefficients (slope/intercept) into a tidy format
tidied = map(model, broom::tidy)
)
print(models_df)What just happened?
data: The raw data for the country.model: The actual linear regression object (lm) for that country.tidied: A tibble containing the statistical results (p-values, estimates).
Now, if you want to see the results, you just unnest the column you care about:
# Extracting the slope (year term) for every country
slopes <- models_df %>%
unnest(tidied) %>%
filter(term == "year") %>%
arrange(desc(estimate))
head(slopes)Industry Standard: This is called the "List-Column Workflow." It is arguably the cleanest way to handle batch modeling in R. It keeps your inputs and outputs synchronized.
3. Tidy Evaluation Introduction: Programming with dplyr
The Definition
Tidy Evaluation (or Tidy Eval) is the system underlying the Tidyverse packages. It allows functions to distinguish between environment variables (objects in your workspace) and data variables (columns inside a data frame).
The Problem
You love dplyr. You want to write a reusable function to filter data.
# Fails miserably β
my_filter <- function(df, var_name, value) {
df %>% filter(var_name == value)
}
my_filter(mtcars, cyl, 6)
# Error: object 'cyl' not foundWhy?
In standard programming, R looks for cyl in the global environment. It doesn't exist there; it exists inside mtcars. Standard R functions don't know how to look inside the dataframe automatically. dplyr functions use Data Masking to look inside the dataframe, but when you wrap them in your own function, that link gets broken unless you explicitly bridge it.
The Solution
We need a way to tell R: "Hey, don't look for cyl right now. Wait until you are inside the filter function, then look for cyl inside the dataframe."
This concept is often called indirection.
4. The Embracing Operator ({{ }}): Custom Functions
The Definition
The Embracing Operator, written as {{ }} (pronounced "curly-curly"), is the modern, industry-standard way to tunnel data-variables (column names) through your function arguments into dplyr verbs.
The Problem
Historically, solving the problem in section 3 required understanding enquo(), !! (bang-bang), and quoting. It was confusing and terrified beginners.
The Solution: {{ }}
If you want to pass a column name to a function, wrap the argument name in {{ }} inside your dplyr verb.
π» Hands-on Code
Let's fix the broken function from the previous section.
Example 1: The Basic Wrapper
# Works perfectly β
my_filter_fixed <- function(df, var_name, value) {
df %>%
filter({{ var_name }} == value)
}
# Usage
mtcars %>%
my_filter_fixed(cyl, 6) %>%
head()Example 2: Flexible Plotting Function (Industry Common)
A very common task is making the same ggplot with different variables.
plot_distribution <- function(data, x_col, title_text) {
data %>%
ggplot(aes(x = {{ x_col }})) + # Tunnel the column name
geom_histogram(bins = 30, fill = "steelblue", color = "white") +
labs(title = title_text) +
theme_minimal()
}
# Plot 1: Life Expectancy
gapminder %>%
plot_distribution(lifeExp, "Distribution of Life Expectancy")
# Plot 2: GDP per Capita
gapminder %>%
plot_distribution(gdpPercap, "Distribution of GDP")Technical Note:
Under the hood, {{ x }} is actually a shortcut for !!enquo(x). It captures the code you typed (the symbol lifeExp) and its context (the environment), and injects it directly into the tidyverse function.
Did you know? π€―
The {{ }} operator was inspired by the template interpolation syntax used in the glue package and many web frameworks (like Jinja2 or Mustache). The Tidyverse team added it specifically to make programming with dplyr accessible to non-computer scientists.
π§ͺ Summary Checklist
- List-Columns: Use
nest()to put data frames inside data frames. - Map: Use
purrr::map()insidemutate()to apply models/functions to those list-columns. - Unnest: Use
unnest()to get your results back into a flat table. - Curly-Curly: Use
{{ arg }}when writing functions that take column names as arguments.
π References & Further Reading
- List-Columns & Nesting: Tidyr Documentation - Nest
- Purrr & Functional Programming: R for Data Science - Iteration
- Programming with dplyr: The Official Guide
- Broom Package: Tidying models
Challenge
Challenge: Build a Reusable Batch Regression Function
Your task is to create a versatile R function named batch_regression that performs a series of linear regressions on grouped data. This function must be robust enough to accept unquoted column names as arguments, leveraging Tidy Evaluation.
Function Requirements:
- The function signature must be:
batch_regression(data, group_var, response_var, predictor_var). - Inside the function, you must use the embracing operator (
{{ }}) to correctly handle thegroup_var,response_var, andpredictor_vararguments withindplyrand other Tidyverse functions. - The function's workflow should be as follows:
- Group the input
datatibble by the column specified ingroup_var. nest()the grouped data to create a list-column.- Create a new list-column by using
purrr::map()to fit a linear model (lm()) for each nested data frame. The model's formula should beresponse_var ~ predictor_var. - Create another new list-column by mapping over the model column and applying
broom::tidy()to extract model coefficients in a clean format. - Finally,
unnest()the tibble containing the tidy coefficients to return a single, flat tibble.
- Group the input
Complete the function body in the provided initial code.
Expected result
When your batch_regression function is called with the provided sales_data and the arguments region, units_sold, and advertising_spend, it should return a single, unnested tibble.
The resulting tibble should have the following columns (or similar columns produced by broom::tidy):
region: The grouping variable, containing the unique values from thegroup_varcolumn.term: A character column with the names of the model coefficients (e.g.,"(Intercept)"and"advertising_spend").estimate: The numeric value for each coefficient estimate.std.error: The standard error for the estimate.statistic: The t-statistic.p.value: The p-value associated with the coefficient.
Each unique value in the region column should correspond to two rows in the output tibble: one for the intercept and one for the predictor variable's coefficient.