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.