Get Started

Loop over a list

Looping over a list is just as easy and convenient as looping over a vector. There are again two different approaches here:

primes_list <- list(2, 3, 5, 7, 11, 13)

# loop version 1
for (p in primes_list) {
  print(p)
}

# loop version 2
for (i in 1:length(primes_list)) {
  print(primes_list[[i]])
}

Notice that you need double square brackets - [[ ]] - to select the list elements in loop version 2.

Suppose you have a list of all sorts of information on New York City: its population size, the names of the boroughs, and whether it is the capital of the United States. We've already defined a list nyc containing this information (source: Wikipedia).

This is a part of the course

“Intermediate R”

View Course

Exercise instructions

As in the previous exercise, loop over the nyc list in two different ways to print its elements:

  • Loop directly over the nyc list (loop version 1).
  • Define a looping index and do subsetting using double brackets (loop version 2).

Hands-on interactive exercise

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

# The nyc list is already specified
nyc <- list(pop = 8405837, 
            boroughs = c("Manhattan", "Bronx", "Brooklyn", "Queens", "Staten Island"), 
            capital = FALSE)

# Loop version 1




# Loop version 2

This exercise is part of the course

Intermediate R

BeginnerSkill Level
4.5+
131 reviews

Continue your journey to becoming an R ninja by learning about conditional statements, loops, and vector functions.

Loops can come in handy on numerous occasions. While loops are like repeated if statements, the for loop is designed to iterate over all elements in a sequence. Learn about them in this chapter.

Exercise 1: While loopExercise 2: Write a while loopExercise 3: Throw in more conditionalsExercise 4: Stop the while loop: breakExercise 5: Build a while loop from scratchExercise 6: For loopExercise 7: Loop over a vectorExercise 8: Loop over a list
Exercise 9: Loop over a matrixExercise 10: Mix it up with control flowExercise 11: Next, you break itExercise 12: Build a for loop from scratch

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free