For in R Programming Language

Our first program will demonstrate various looping constructs in R. Here’s the full source code with explanations:

# The most basic type, with a single condition.
i <- 1
while (i <= 3) {
  print(i)
  i <- i + 1
}

# A classic initial/condition/after loop using a for loop.
for (j in 0:2) {
  print(j)
}

# Another way of accomplishing the basic "do this N times" iteration
# is using seq_len() function.
for (i in seq_len(3)) {
  print(paste("range", i-1))
}

# While loop without a condition will loop repeatedly
# until you break out of the loop or return from
# the enclosing function.
repeat {
  print("loop")
  break
}

# You can also use next to skip to the next iteration of the loop.
for (n in 0:5) {
  if (n %% 2 == 0) {
    next
  }
  print(n)
}

To run the program, save the code in a file (e.g., loops.R) and use the R interpreter:

$ Rscript loops.R
[1] 1
[1] 2
[1] 3
[1] 0
[1] 1
[1] 2
[1] "range 0"
[1] "range 1"
[1] "range 2"
[1] "loop"
[1] 1
[1] 3
[1] 5

Let’s break down the different types of loops used in this R code:

  1. The while loop is used for the most basic type with a single condition.
  2. The for loop with a sequence (0:2) is equivalent to the classic initial/condition/after loop.
  3. The for loop with seq_len() demonstrates iteration over a range of numbers.
  4. The repeat loop shows an infinite loop that’s immediately broken, similar to a for without condition.
  5. Another for loop demonstrates the use of next 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.