Loops
Published Aug 30, 2022
Contribute to Docs
A loop is used to repeat some operation a multiple number of times. In R, there are while
and for
loops.
While Loop
The statement(s) within a while
loop code block will continue to execute as long as a declared condition is TRUE
.
The following example will continuously execute the statements within the while
loop block until the condition is no longer TRUE
:
var1 <- 0while (var1 < 100) {print(var1)var1 <- var1 + 1}
For Loop
The statement(s) within a for
loop code block will execute once for each item in a list-like data structure like a vector
or list
.
The following example will execute the statement within the for
loop block for each item in the list
:
NY <- list("Bronx", "Brooklyn", "Manhattan", "Queens", "Staten Island")for (borough in NY) {print(borough)}
Additional control flow statements can be used within these blocks for both types of loops.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn R on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn R
Learn how to code and clean and manipulate data for analysis and visualization with the R programming language.Beginner Friendly14 hours