Functional Programming with purrr
6 min read
Functional Programming with purrr π±
Welcome, R adventurers, to a journey into the wonderful world of functional programming with the purrr package! If you've ever found yourself writing the same for loop over and over, you're in for a treat. purrr provides a more elegant and efficient way to handle repetitive tasks.
Getting Started with purrr
Before we dive in, let's get purrr installed and ready to go. purrr is part of the tidyverse, so if you already have that, you're all set. If not, you can install it individually.
To install the entire tidyverse:
install.packages("tidyverse")Alternatively, to install only purrr:
install.packages("purrr")Now, let's load it up:
library(purrr)πΊοΈ Beyond For-Loops: Introduction to the map() Family
The Problem: Imagine you have a list of numbers, and you want to calculate the square of each number. A traditional approach would be to use a for loop.
numbers <- c(1, 2, 3, 4, 5)
squared_numbers <- vector("double", length(numbers))
for (i in seq_along(numbers)) {
squared_numbers[i] <- numbers[i] ^ 2
}
print(squared_numbers)This works, but it's a bit verbose. We have to pre-allocate a vector and manually loop through each element. It's like having to tell a robot every single step of a task, "pick up the first number, square it, put it in the first box, pick up the second number...". π€
The Solution: The map() function from purrr allows you to apply a function to each element of a list or vector in a more concise and readable way. It's like giving the robot a single instruction: "square every number in this list and give me a new list of the results".
numbers <- c(1, 2, 3, 4, 5)
squared_numbers <- map(numbers, ~ .x ^ 2)
print(squared_numbers)Notice the ~ .x ^ 2 syntax. This is a special formula syntax in purrr that creates an "anonymous function" on the fly. .x represents the element of the vector being processed. So, for each number in numbers, it squares it.
The map() function always returns a list. This is a key feature for consistency.
π§ Type-Specific Mapping: map_dbl(), map_chr(), map_df()
The Problem: While map() is great, it always gives you back a list. Sometimes, you know for sure what kind of output you want, like a numeric vector or a character vector. Having to convert the list output can be an extra, slightly annoying step.
The Solution: purrr provides a family of type-specific map functions that return a specific data type. This is fantastic when you're confident about the output and want a simple vector back.
map_dbl(): returns a numeric (double) vector.map_chr(): returns a character vector.map_lgl(): returns a logical vector.map_int(): returns an integer vector.map_df(): returns a data frame.
Let's revisit our squaring example, but this time, let's get a numeric vector directly.
numbers <- c(1, 2, 3, 4, 5)
squared_numbers_vec <- map_dbl(numbers, ~ .x ^ 2)
print(squared_numbers_vec)Now, squared_numbers_vec is a simple numeric vector, not a list! This is incredibly handy for many data analysis tasks.
A Fun Fact: The "type-stable" nature of these functions (they always return the advertised output type or throw an error) is a big advantage over some base R functions, which can sometimes have unpredictable outputs.
π§βπ€βπ§ Mapping Over Multiple Inputs with map2() and pmap()
The Problem: What if you need to iterate over two or more lists or vectors at the same time? For example, you have a list of means and a list of standard deviations, and you want to generate random numbers for each pair. Trying to manage this with a single for loop can get a bit messy.
The Solution: purrr offers map2() for iterating over two inputs and pmap() for iterating over multiple (more than two) inputs.
map2(): The Dynamic Duo π¦ΈββοΈπ¦ΈββοΈ
map2() takes two lists or vectors as input and applies a function to corresponding pairs of elements.
Imagine you have two friends, and you want to see which one has the longer name.
friend1_names <- c("Alice", "Bob", "Charlie")
friend2_names <- c("David", "Eve", "Frank")
longer_names <- map2_chr(friend1_names, friend2_names, ~ if (nchar(.x) > nchar(.y)) .x else .y)
print(longer_names)Here, .x refers to an element from friend1_names, and .y refers to the corresponding element from friend2_names.
pmap(): The Ultimate Team-Up π
For more than two inputs, pmap() is your go-to function. It takes a list of lists as input.
Let's say you're a mad scientist creating new creatures. You have lists for their heads, bodies, and tails.
creature_parts <- list(
head = c("lion", "eagle", "snake"),
body = c("human", "fish", "lizard"),
tail = c("scorpion", "peacock", "dragon")
)
new_creatures <- pmap_chr(creature_parts, ~ paste(.x, .y, .z, sep = "-"))
print(new_creatures)Inside the pmap function, you can refer to the elements of the input lists by their names if they are named, or by ..1, ..2, ..3, and so on.
π‘οΈ Safe Iteration: Handling Errors with safely() and possibly()
The Problem: You're running a long and complex mapping operation, maybe fitting hundreds of models. Suddenly, one of them fails due to an error. Your entire process comes to a screeching halt, and you've lost all the progress. π± It's like a single faulty firework ruining the whole grand finale.
The Solution: purrr provides two powerful functions to handle these situations gracefully: safely() and possibly().
safely(): The Cautious Investigator π΅οΈ
safely() is a function "adverb" that modifies another function. It wraps your function in a protective layer. If the function runs successfully, safely() returns a list with a result component and an error component that is NULL. If an error occurs, the result will be NULL, and the error component will contain the error message.
Let's try to take the logarithm of a list of numbers, including a problematic one.
numbers_to_log <- list(10, "a", 5)
safe_log <- safely(log)
log_results <- map(numbers_to_log, safe_log)
print(log_results)Instead of stopping, the code continues, and you can inspect the log_results to see which elements caused an error.
possibly(): The Optimistic Problem-Solver π
possibly() is another helpful adverb. Instead of returning a detailed error message, it lets you specify a default value to return when an error occurs.
numbers_to_log <- list(10, "a", 5)
possible_log <- possibly(log, otherwise = NA_real_)
log_results_simple <- map_dbl(numbers_to_log, possible_log)
print(log_results_simple)This is super useful when you just want to replace errors with a placeholder and move on.
By using safely() and possibly(), you can make your code more robust and avoid the frustration of your scripts crashing midway through a long process.
π Further Reading
- Official
purrrWebsite: https://purrr.tidyverse.org/ - "R for Data Science" - Iteration Chapter: https://r4ds.had.co.nz/iteration.html
purrrCheatsheet: A great quick reference guide. You can find it on the tidyverse website.
Challenge
Challenge: Robust Data Processing Pipeline with purrr
You are given a list of datasets, data_sets, where each element is a list containing a numerator and a denominator. Some of these datasets are problematic and will cause errors during calculation (e.g., division by zero or NA values).
Your task is to build a robust data processing pipeline using purrr to calculate the ratio for each dataset, handle any errors gracefully, and return a clean numeric vector of the successful results.
Requirements:
- Define a function named
calculate_ratiothat takes a single list (e.g.,list(numerator = 10, denominator = 2)) as input and returns the result ofnumerator / denominator. - Create a "safe" version of this function called
safe_calculate_ratioby wrapping it withpurrr::safely(). - Use
purrr::map()to applysafe_calculate_ratioto every element in thedata_setslist. Store this output in a variable namedmap_output. - The
map_outputwill be a list where each element contains$resultand$error. To easily separate the successes from failures,transposethis list usingpurrr::transpose()and store it intransposed_output. - From
transposed_output, extract just the list of results (which will includeNULLs for the failed calculations) into a variable namedall_results. - Finally, use a type-specific map function,
purrr::map_dbl(), combined with an anonymous function, to extract the valid numbers fromall_resultsand create a final, clean numeric vector. For this step, you must usepurrr::possibly()to handle theNULLvalues gracefully, providingNA_real_as the default value for failures, and then pipe the result tocompact()to remove theNAs. Store your final clean numeric vector infinal_ratios.
Expected result
Your final code should define several variables as instructed. The most important final output is the final_ratios variable.
calculate_ratioshould be a function that performs division.safe_calculate_ratioshould be the adverb-modified version ofcalculate_ratio.map_outputshould be a list of 6 lists, where the 3rd and 5th elements contain errors in their$errorcomponent andNULLin their$resultcomponent.transposed_outputshould be a list with two elements,$resultand$error.all_resultsshould be the$resultcomponent fromtransposed_output, containing numbers andNULLs.final_ratiosmust be a numeric vector containing only the successful calculations:c(20, 9, 7, 12).