01 / 21

Readable
Pipelines in R

Learn to write clean, expressive data pipelines using the pipe operator: chaining steps clearly without creating tangled, unreadable code.

R Programming

What is a Pipeline?

A pipeline is a sequence of data transformations connected together so the output of one step becomes the input of the next. In R, we use the pipe operator to build pipelines:

result <- data %>% step_one() %>% step_two() %>% step_three()

Why Pipelines Matter

✓ Readability
Code reads top-to-bottom like a recipe: do this, then this, then this.
✓ No Nesting
Eliminates deeply nested function calls that read inside-out.
✓ Fewer Temps
No need for intermediate throwaway variables cluttering your environment.

Anatomy of a Pipeline

data %>% filter() Step 1 %>% mutate() Step 2 %>% summarise() Step 3 Input Output Data flows left to right through each step

The Golden Rule of Pipelines

1
One logical task per pipeline: filtering and summarising a dataset is one task. Cleaning, reshaping, joining, modelling, and plotting are five tasks.
2
Aim for 5-7 steps max: beyond that, break the chain into named intermediate results.
3
Name your intermediates well: clean_data, daily_summary: each name documents intent.

The Readability Curve

Readability Number of Steps in Pipeline 0 2 4 6 8 10 12 Sweet Spot Too Long ~5 steps

Three Styles Compared

Nesting Temp Variables Pipeline
Read order Inside-out Top-to-bottom Top-to-bottom
Clutters environment No Yes No
Easy to debug Hard Easy Moderate
Scalable Poor Fair Best

Nesting vs. Pipeline

Nested (hard to read)
arrange( summarise( group_by( filter(df, score > 80), subject), avg = mean(score)), desc(avg))
✕ Reads inside-out
Pipeline (clear)
df %>% filter(score > 80) %>% group_by(subject) %>% summarise(avg = mean(score)) %>% arrange(desc(avg))
✓ Reads top-to-bottom

How to Write a Clean Pipeline

1
Start with the data object on its own line. This anchors the reader.
2
One verb per line: each pipe step gets its own line, indented two spaces.
3
End the line with the pipe: place %>% at the end, not the start of the next line.
4
Comment complex steps: add # why comments above non-obvious transformations.
5
Break at ~6 steps: assign the intermediate result to a descriptive name and start a new pipeline.

Example 1: Simple Pipeline

Task: Find the average price of houses with more than 3 bedrooms.

houses %>% filter(bedrooms > 3) %>% summarise(avg_price = mean(price))

Example 2: Medium Pipeline

Task: Get the top 5 students by average score in each subject.

grades %>% filter(!is.na(score)) %>% # remove missing group_by(subject, student) %>% # per student per subject summarise(avg = mean(score)) %>% # student averages slice_max(avg, n = 5) %>% # top 5 per group arrange(subject, desc(avg))

Example 3: Breaking a Long Chain

Before: 10 steps in one chain
raw %>% select(...) %>% rename(...) %>% mutate(...) %>% filter(...) %>% left_join(...) %>% group_by(...) %>% summarise(...) %>% pivot_wider(...) %>% mutate(...) %>% ggplot(...)
After: two named stages
# Stage 1: clean and join clean_data <- raw %>% select(...) %>% rename(...) %>% mutate(...) %>% filter(...) %>% left_join(...) # Stage 2: summarise and visualise clean_data %>% group_by(...) %>% summarise(...) %>% pivot_wider(...) %>% mutate(...) %>% ggplot(...)

Formatting Rules

1 2 3 4 5 df %>% filter(x > 10) %>% group_by(cat) %>% summarise(m = mean(x)) %>% arrange(desc(m)) Data on its own line Indent 2 spaces Pipe at end of line One verb per line Consistent formatting = consistent readability These rules work for both %>% and |>

When to Break a Pipeline

✕ Side effects
If a step writes a file, sends a message, or prints: break before it.
✕ Reused results
If you need the intermediate result elsewhere, assign it a name.
✕ Context switch
When the "story" changes (cleaning to modelling), start a new chain.

Common Mistakes

✕ Mega-chain
Chaining 15+ steps without any named intermediate. Impossible to debug when something breaks at step 11.
✕ Pipe into assignment
Using %>% to assign mid-chain (x %>% ... -> y). This breaks the flow and confuses readers.
✕ No indentation
Writing all steps on one line or without consistent indentation. The visual structure disappears.

Pipeline Checklist

Principle Good Practice Anti-pattern
Length 5-7 steps 15+ steps
Formatting One verb per line All on one line
Pipe placement End of line Start of next line
Intermediates Named at boundaries temp1, temp2, temp3
Comments Above complex steps None or every line
Side effects Separate chain Buried mid-chain

Question 1 of 5

What is the recommended maximum number of steps in a single R pipeline before you should consider breaking it up?

Question 2 of 5

Which style is more readable and why?

Question 3 of 5

Where should the pipe operator %>% be placed?

Question 4 of 5

Your pipeline has 12 steps that clean data, join two tables, compute summaries, and create a plot. What should you do?

Question 5 of 5

Which of the following is a valid reason to break a pipeline into separate chains?