Learn tidyverse · 12/13

Functional Programming: Iteration Made Easy (purrr)

7 min read

Welcome to the clean, consistent world of iteration. If you have been writing R for a while, you are likely familiar with the for loop. While for loops are a fundamental building block of programming, they can be verbose, difficult to read, and prone to "bookkeeping" errors in R.

The purrr package (part of the core tidyverse) enhances R's functional programming capabilities. It provides a complete and consistent set of tools for working with functions and vectors.

Prerequisites:
Ensure you have the tidyverse installed and loaded.

r
# If not installed
install.packages("tidyverse")

# Load the core libraries
library(tidyverse)

1. Saying Goodbye to for Loops: Introduction to map() 🗺️

The Problem: Loop Boilerplate

In a traditional for loop, you often have to do three things:

  1. Initialize an output container (like an empty vector).
  2. Iterate over an index or element.
  3. Assign the result to the specific spot in the container.

This is "imperative programming"—telling the computer how to do something step-by-step.

The "Old" Way:

r
# We want to square these numbers
numbers <- list(1, 2, 3, 4, 5)

# 1. Initialize
output <- vector("list", length(numbers))

# 2. Iterate
for (i in seq_along(numbers)) {
  # 3. Assign
  output[[i]] <- numbers[[i]] ^ 2
}

print(output)

Fun Fact: Programmers spend 20% of their life checking if they used i or j in nested loops. Okay, I made that up, but it feels true.

The Solution: map()

map() creates a loop under the hood. It abstracts away the initialization and assignment. You simply tell it what you want to do.

Definition:

map(.x, .f) transforms an input vector or list (.x) by applying a function (.f) to each element, and always returns a list.

The purrr Way:

r
numbers <- list(1, 2, 3, 4, 5)

# "For every element in 'numbers', apply the square function"
squared_list <- map(numbers, \(x) x^2)

str(squared_list)
# List of 5
# $ : num 1
# $ : num 4
# ...

Why use this?

  1. Conciseness: No empty vector creation.
  2. Safety: map creates its own environment, reducing side effects (variables leaking into your global environment).
  3. Pipeable: It fits perfectly into %>% or |> chains.

2. Type-Safe Mapping: map_dbl(), map_chr(), and map_df() 🛡️

The Problem: Lists are Flexible but Annoying

The standard map() function represents the "most general" case: it always returns a list. Lists are great because they can hold anything, but they are terrible if you want to do math afterward. You can't calculate the mean of a list directly; you need a numeric vector.

The Solution: Suffixes

purrr uses suffixes to enforce the type of the output. If the function fails to return that type, purrr will throw an error immediately (failing fast is good in production code!).

  • map_dbl(): Returns a numeric (double) vector.
  • map_chr(): Returns a character vector.
  • map_lgl(): Returns a logical vector.
  • map_dfr() / map_dfc(): Returns a data frame (binds rows or columns).

Examples in Action

1. map_dbl (Doubles/Numbers)

Let's extract the mean from a list of vector data.

r
# A list of vectors with random numbers
data_list <- list(
  a = c(1, 2, 3),
  b = c(10, 20, 30),
  c = c(100, 200, 300)
)

# Returns a numeric vector, not a list
means <- map_dbl(data_list, mean)

print(means)
#   a   b   c 
#   2  20 200 

2. map_chr (Characters)

Great for extracting names or string manipulation.

r
fruit_list <- list("apple", "banana", "cherry")

# Convert to uppercase and return a character vector
upper_fruits <- map_chr(fruit_list, toupper)

print(upper_fruits)
# [1] "APPLE"  "BANANA" "CHERRY"

3. map_dfr (Data Frames)

Note: In the newest versions of purrr, map_dfr is considered "superseded" by map() |> list_rbind(), but map_dfr is still widely used in the industry.

This iterates over inputs, creates a dataframe for each, and then stacks them on top of each other.

r
# Imagine a list of people
people <- list(
  list(name = "Alice", role = "Admin"),
  list(name = "Bob", role = "User")
)

# Convert list of lists into a Data Frame
users_df <- map_dfr(people, identity) # identity just returns the input

print(users_df)
# # A tibble: 2 × 2
#   name  role 
#   <chr> <chr>
# 1 Alice Admin
# 2 Bob   User

3. Mapping Over Multiple Arguments: map2() and pmap() 🤹

The Problem: Functions with Multiple Inputs

map() iterates over one list/vector. But standard R functions often need multiple arguments.
For example, rnorm(n, mean, sd) generates random numbers. It needs a count (n), a mean, and a standard deviation (sd).

If you try to map over just n, how do you pass different means for each iteration?

The Solution: map2 and pmap

1. map2(.x, .y, .f)

Iterates over two vectors in parallel (lock-step). It stops when the shortest input is exhausted (though usually, you want them the same length).

r
# We want: 
# 1 random number with mean 10
# 2 random numbers with mean 20
# 3 random numbers with mean 30

counts <- c(1, 2, 3)
means  <- c(10, 20, 30)

# .x = counts, .y = means
random_nums <- map2(counts, means, \(n, m) rnorm(n, mean = m))

print(random_nums)
# [[1]] [1] 9.4 (approx)
# [[2]] [1] 19.1 20.5 (approx)
# [[3]] [1] 30.1 29.8 31.2 (approx)

2. pmap(.l, .f)

The "p" stands for parallel. This iterates over any number of arguments supplied as a list.

Definition:

pmap takes a list of lists (or a data frame) and maps a function over the elements at the same index across all input lists.

This is incredibly powerful when applying a function to every row of a data frame.

r
# Parameters for simulation
params <- tibble(
  n = c(1, 2),
  mean = c(10, 20),
  sd = c(1, 5)
)

print(params)
# # A tibble: 2 × 3
#       n  mean    sd
#   <dbl> <dbl> <dbl>
# 1     1    10     1
# 2     2    20     5

# Apply rnorm to every row
# We use pmap inside mutate usually
params_with_data <- params %>%
  mutate(
    generated_data = pmap(list(n, mean, sd), rnorm)
  )

4. Purrr in Practice: Reading Multiple Files Automatically 📂

The Scenario

This is the #1 interview question and real-world task for R data engineers.
You have a folder called sales_data/ containing:

  1. jan_sales.csv
  2. feb_sales.csv
  3. mar_sales.csv

You need to load them all and combine them into one Master Data Frame.

The "For Loop" Nightmare

You'd have to list files, create an empty dataframe, loop, read, bind rows... it's messy.

The purrr Workflow

Step 1: Get the file paths.
We use fs::dir_ls or base R list.files.

Step 2: Map read_csv over the paths.

Step 3: Combine.

(Note: For this example, we will simulate the files conceptually, but the code is exactly what you run in production).

r
# 1. Get vector of file paths
# full.names = TRUE is CRITICAL so R can find the file
files <- list.files(path = "sales_data/", pattern = "*.csv", full.names = TRUE)

# files looks like: c("sales_data/jan.csv", "sales_data/feb.csv")

# 2. Iterate and Combine
all_sales <- files %>%
  # set_names ensures the result list is named after the filenames
  set_names() %>% 
  # Read each file. Result is a list of dataframes.
  map(read_csv) %>% 
  # Combine them into one big dataframe
  # .id = "source_file" adds a column showing which file the row came from!
  list_rbind(names_to = "source_file")

# Result: A single dataframe with all months combined.

Why this is industry standard:

  1. Scalable: Works for 3 files or 3,000 files.
  2. Traceable: Using set_names and .id (or names_to) allows you to track data lineage (knowing which file a specific row came from).
  3. Robust: If one file is corrupt, you can easily wrap read_csv in possibly() (another purrr function) to skip errors without stopping the whole script.

Summary

  • map() is the new for loop. It returns a list.
  • map_dbl/chr/lgl are strict. They return atomic vectors.
  • map2/pmap let you iterate over multiple arguments simultaneously.
  • Real World: Use map to read, process, and combine multiple data files in just 3 lines of code.

🔗 Useful Links & References

Challenge

You are given a list of data frames named sales_data_list, where each data frame represents sales from a different store location. You are also given a character vector, store_locations, containing the ID for each store.

Your task is to process this data using purrr functions to create a single, combined sales report.

  1. First, create a function that takes a data frame as input. Inside this function, use pmap_dbl() to calculate a profit_margin for each product (row). The formula for profit margin is (price - cost) / price.
  2. Use a map variant to apply this function to every data frame in sales_data_list.
  3. Your final mapping operation must return a single data frame, not a list of data frames. This final data frame must also include a new column named store_id that contains the corresponding location ID from store_locations for each row.

Assign the final, combined data frame to a variable named combined_sales_report.

Expected result

The variable combined_sales_report should be a single tibble (or data frame) with 8 rows and 5 columns: store_id, product_id, price, cost, and profit_margin.

The store_id column should be a character vector containing the names of the stores, correctly mapped to their respective sales data. The profit_margin column should contain the calculated profit margin for each product as a numeric (double) vector.

r

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.