For Loop in R Programming

R has three statements that provide explicit looping. They are forwhile and repeat. Each of the three statements returns the value of the last statement that was evaluated. R also provides other functions for implicit looping such as tapplyapply, and lapply.

There are two statements that can be used to explicitly control looping. They are break and next. The break statement causes an exit from the innermost loop that is currently being executed. The next statement immediately causes control to return to the start of the loop. The next iteration of the loop (if there is one) is then executed. No statement below next in the current loop is evaluated.

In this lesson, we will discuss the for loop. The syntax of the for loop is:

for ( name in vector )
    statement1

Here vector can be either a vector or a list. For each element in vector the variable name is set to the value of that element and statement1 is evaluated. Basically, the loop iterates over the vector.

Example: Generate Fibonacci sequence for ‘n’ numbers

The following example shows generating Fibonacci sequence for ‘n’ numbers using the For loop.

n <- 10
fib <- numeric(n)
fib[1] <- 1
fib[2] <- 1
for (i in 3:n)
{
  fib[i] <- fib[i-1]+fib[i-2] 
}
print(fib)

The above code will output the Fibonacci series as shown below:

> print(fib)
 [1]  1  1  2  3  5  8 13 21 34 55

Example: Print Stock Prices

Below is another simple example that prints the stocks prices of a stock from a vector containing stock prices for the past five days.

stock_A <- c(10, 8, 9, 11, 12)
for (i in stock_A)
{
  print(i)
}

This will print the stock prices one by one as the loop iterates over the elements in the vector:

[1] 10
[1] 8
[1] 9
[1] 11
[1] 12

Example: Break

The below example demonstrates the use of break statement. For this example, we would like to break and end the loop if the stock price is equal to 11.

stock_A <- c(10, 8, 9, 11, 12)
for (i in stock_A)
{
  if(i == 11)
  {
    break
  } 
  print(i)
}

The loop will execute normally. Each time, it will check if i is equal to 11, if not, it will proceed to print the value of i. If i becomes equal to 11, then the break statement will be executed and the loop will be exited.

[1] 10
[1] 8
[1] 9