How to loop through a list of item using a for loop in R

Overview

In this shot, we want to learn how we can loop through a list in R. To understand a for loop in R, click on this shot.

You can loop through items of a list using a for loop.

Code

mylist <- list("mango", "orange", "pear", "apple", "lemon", "cashew")
for (x in mylist){
print(x)
}

Explanation

  • Line 1, we create a list mylist.
  • Line 3, we use a for loop, and make x represent the items in the list.
  • Line 4 we print x, which means printing all the list items.

That is a straightforward way of looping through a list in R.

Code

mylist <- list("mango", "orange", "pear", "apple", "lemon", "cashew")
for (x in 1:length(mylist)) {
print(mylist[[x]])
}

Explanation

In the code above we defined a looping index variable x in the loop and called the lengh() function. With this method, we are also able to loop through the giving list using a for loop.

Summary

The two different methods to use in order to loop through a list of items are:

  1. To loop directly over the list.

  2. To define a looping index variable and call the length() function.

Free Resources