LoslegenKostenlos loslegen

Iteration with purrr

You've made a great for loop, but it uses a lot of code to do something as simple as input a series of files into a list. This is where purrr comes in. We can do the same thing as a for loop in one line of code with purrr::map(). The function map() iterates over a list, and uses another function that can specified with the .f argument.

map() takes two arguments:

  • The first is the list over that will be iterated over
  • The second is a function that will act on each element of the list

The readr library is already loaded.

Diese Übung ist Teil des Kurses

Foundations of Functional Programming with purrr

Kurs anzeigen

Anleitung zur Übung

  • Load the purrr library (note the 3 Rs).
  • Replicate the for loop from the last exercise using map() instead. Use the same list files and the same function readr::read_csv().
  • Check the length of all_files_purrr.

Interaktive Übung

Versuche dich an dieser Übung, indem du diesen Beispielcode vervollständigst.

# Load purrr library
library(___)

# Use map to iterate
all_files_purrr <- map(___, ___) 

# Output size of list object
length(___)
Code bearbeiten und ausführen