Get startedGet started for free

Introduction to iteration

Imagine that you need to read in hundreds of files with a similar structure and perform an action on them. You don't want to write hundreds of repetitive lines of code to read in all the files or to perform the action. Instead, you want to iterate over them. Iteration is the process of doing the same process to multiple inputs. Being able to iterate is important to make your code efficient, and is powerful when working with lists.

For this exercise, the names of 16 CSV files have been loaded into a list called files. In your own work, you could use the list.files() function to create this list. The readr library is also already loaded.

This course touches on a lot of concepts you may have forgotten, so if you ever need a quick refresher, download the tidyverse Cheat Sheet and keep it handy!

This exercise is part of the course

Foundations of Functional Programming with purrr

View Course

Exercise instructions

  • Create a for loop, which iterates over the files list, and gives each element as an input for readr::read_csv(), which is another way of saying the read_csv() function from the readr package.
  • Then use that input, so the result is a list where each CSV file has been read into a separate element of the newly created all_files list.
  • Output the size of the all_files list.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Initialize list
all_files <- list()

# For loop to read files into a list
for(i in seq_along(files)){
  ___[[___]] <- read_csv(file = ___[[___]])
}

# Output size of list object
length(___)
Edit and Run Code