purrr Functional Programming

Advanced RpurrrFree Lesson

Advertisement

Introduction

The purrr package provides functional programming tools. It replaces loops with map functions.

Map Functions

library(purrr)

# Map to list
map(df, mean)

# Map to vector
map_dbl(df, mean)
map_chr(df, class)
map_lgl(df, is.numeric)

# Map to dataframe
map_dfr(df, ~.x * 2)

Iterating Over Two Vectors

# Map over two vectors
map2(x, y, ~.x + .y)

# Reduce to single value
pmap(list(x, y, z), ~..1 + ..2 + ..3)

Modifying Data

# Modify specific columns
df %>%
  mutate_at(vars(starts_with("score")), ~. * 2)

# Modify by type
df %>%
  modify_if(is.numeric, ~. * 2)

Summary

purrr provides functional alternatives to loops. Use it for clean, readable code.

Advertisement

Need Expert R Programming Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement