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.
# 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:
- Initialize an output container (like an empty vector).
- Iterate over an index or element.
- 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:
# 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:
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?
- Conciseness: No empty vector creation.
- Safety:
mapcreates its own environment, reducing side effects (variables leaking into your global environment). - 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.
# 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.
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.
# 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 User3. 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).
# 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:
pmaptakes 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.
# 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:
jan_sales.csvfeb_sales.csvmar_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).
# 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:
- Scalable: Works for 3 files or 3,000 files.
- Traceable: Using
set_namesand.id(ornames_to) allows you to track data lineage (knowing which file a specific row came from). - Robust: If one file is corrupt, you can easily wrap
read_csvinpossibly()(anotherpurrrfunction) to skip errors without stopping the whole script.
Summary
map()is the newforloop. It returns a list.map_dbl/chr/lglare strict. They return atomic vectors.map2/pmaplet you iterate over multiple arguments simultaneously.- Real World: Use
mapto 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.
- First, create a function that takes a data frame as input. Inside this function, use
pmap_dbl()to calculate aprofit_marginfor each product (row). The formula for profit margin is(price - cost) / price. - Use a
mapvariant to apply this function to every data frame insales_data_list. - 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_idthat contains the corresponding location ID fromstore_locationsfor 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.