For Loop in R Programming
R has three statements that provide explicit looping. They are for
, while
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 tapply
, apply
, 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:
1for ( name in vector )
2 statement1
3
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.
1n <- 10
2fib <- numeric(n)
3fib[1] <- 1
4fib[2] <- 1
5for (i in 3:n)
6{
7 fib[i] <- fib[i-1]+fib[i-2]
8}
9print(fib)
10
The above code will output the Fibonacci series as shown below:
1> print(fib)
2 [1] 1 1 2 3 5 8 13 21 34 55
3
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.
1stock_A <- c(10, 8, 9, 11, 12)
2for (i in stock_A)
3{
4 print(i)
5}
6
This will print the stock prices one by one as the loop iterates over the elements in the vector:
1[1] 10
2[1] 8
3[1] 9
4[1] 11
5[1] 12
6
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.
1stock_A <- c(10, 8, 9, 11, 12)
2for (i in stock_A)
3{
4 if(i == 11)
5 {
6 break
7 }
8 print(i)
9}
10
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[1] 10
2[1] 8
3[1] 9
4