0Pricing
R Academy · Lesson

map() and Typed Variants

Apply functions over lists with map(), map_dbl(), map_chr(), and map_lgl().

Functional Programming with purrr

The purrr package provides consistent, type-safe tools for functional programming in R. Instead of writing for loops, you map a function over a list or vector. The result is cleaner code that's easier to reason about and compose.

library(purrr)

# A list of numbers
numbers <- list(1, 4, 9, 16, 25)

# Apply sqrt() to each element
result <- map(numbers, sqrt)
print(result)

map() — Always Returns a List

map(.x, .f) applies function .f to each element of .x and returns a list. The input can be a list, vector, or data frame (iterates over columns). This is the most general map variant.

library(purrr)

# Map over a character vector
fruits <- c('apple', 'banana', 'cherry')

# nchar() counts characters in each string
result <- map(fruits, nchar)
print(result)  # Returns a list
print(class(result))

All lessons in this course

  1. map() and Typed Variants
  2. map2() and pmap() for Multiple Inputs
  3. reduce(), accumulate(), and walk()
  4. keep(), discard(), and List Filtering
← Back to R Academy