R – Loop through items in List
To loop through items in a list in R programming, use For Loop.
In this tutorial, we will learn how to iterate over a list using For Loop, with the help of example programs.
The syntax to use For Loop for a list is
</>
Copy
for (item in list) {
//code
}
We can access ith item inside for-loop, during ith iteration.
Examples
In the following program, we will create a list with some initial values, and iterate over the items of the list using for loop.
example.R
</>
Copy
myList <- list("Sunday", "Monday", "Tuesday")
for (item in myList) {
print(item)
}
Output
[1] "Sunday"
[1] "Monday"
[1] "Tuesday"
Now, let us take a list of numbers, and iterate over them using For Loop.
example.R
</>
Copy
myList <- list(1, 4, 9, 16, 25)
for (item in myList) {
print(item)
}
Output
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
Conclusion
In this R Tutorial, we learned how to iterate over items in a list in R programming using For Loop, with the help of examples.