For in R Programming Language
Our first program will demonstrate various looping constructs in R. Here’s the full source code with explanations:
To run the program, save the code in a file (e.g., loops.R
) and use the R interpreter:
Let’s break down the different types of loops used in this R code:
- The
while
loop is used for the most basic type with a single condition. - The
for
loop with a sequence (0:2) is equivalent to the classic initial/condition/after loop. - The
for
loop withseq_len()
demonstrates iteration over a range of numbers. - The
repeat
loop shows an infinite loop that’s immediately broken, similar to afor
without condition. - Another
for
loop demonstrates the use ofnext
to skip iterations.
In R, there’s no built-in range
function like in some other languages, so we use seq_len()
or the colon operator to create sequences for iteration.
The break
statement is used to exit a loop prematurely, while next
is used to skip to the next iteration, similar to continue
in other languages.
These looping constructs provide flexible ways to iterate in R, allowing you to control the flow of your program efficiently.