Module 08 of 10

Functional Programming & Performance

Lessons

About This Module

As your R scripts grow, repeating the same step over many items by hand gets slow and error-prone. This module shows the functional approach: instead of writing for loops, you hand a function to a tool that applies it to every element for you. You'll start with the base R apply family — lapply(), sapply(), vapply(), and mapply() — then move to the map() functions in the tidyverse's purrr package.

Along the way you'll see why code written this way is shorter and easier to read, and how thinking in whole vectors rather than single values, known as vectorization, is the key to writing faster R code.

Watch the lessons in order, then continue on to Reporting with R Markdown & Shiny.

Lessons

4 videos
01

How to Use lapply, sapply and mapply in R

Shows how the apply family of functions runs a function on each element of a list or vector, with examples of lapply, sapply, and mapply.

02

The lapply, sapply, and vapply functions in R

Explains how to use lapply, sapply, and vapply with several worked examples, and how the three differ in what they return.

03

Alternative to for loops in R with purrr's map, map_dbl, and map_dfr functions

Pat Schloss shows how to replace for loops with the map, map_dbl, and map_dfr functions from the purrr package.

04

purrr::map - VERY basic: part 2, iterating functions to import multiple files

A hands-on example of purrr::map in practice, iterating a function over many files to read them into R in one step.