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.
mylist <- list("mango", "orange", "pear", "apple", "lemon", "cashew")for (x in mylist){print(x)}
mylist
.for
loop, and make x
represent the items in the list.x
, which means printing all the list items.That is a straightforward way of looping through a list in R.
mylist <- list("mango", "orange", "pear", "apple", "lemon", "cashew")for (x in 1:length(mylist)) {print(mylist[[x]])}
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.
The two different methods to use in order to loop through a list of items are:
To loop directly over the list.
To define a looping index variable and call the length()
function.