R Programming - Part 4 - For Loop, While Loop

17 Oct 2020 - Benjamin Loi

Introduction

This article will demonstrate another essential structure, for loop and while loop, which can repeatedly execute parts of the code.

For Loop

For loop will iterate over the elements of a sequence and run the block under the for loop at each iteration. At the start of each repetition, the next entry of the sequence will be assigned to a dummy loop variable, that can be referenced in the lines enclosed by the loop. For loop stops when all elements have been gone through. To implement for loop, we simple write a statement with the form of for ( in ) and use a pair of curly brackets to surround the block to be repeated. A simple usage to print out consecutive numbers is shown below, with i as the loop variable.

R-04-00

A more complicated example is to sum the entries in a series, although you can simply use the function sum() instead.

R-04-01
R-04-02

Multiple For Loops

Nested for loops can be utilized to deal with more complicated situations. They behave in a way that the innermost loop is iterated the fastest. It is even possible for the range of an inner loop to depend on an outer loop. When the inner loop finishes all the iteration, the outer loop immediately around it will run once, and then the inner loop is restarted. Two slightly different cases are shown below.

R-04-03
R-04-04
R-04-05
R-04-06

While Loop

While loop is another kind of loops which will keep repeating the code, given the condition stated in the loop statement is true. The statement has the form of while (). Extra care is needed to avoid that the test condition always returns true, otherwise, it will become an infinite loop and the code will never stop. A brief example is given below.

R-04-07
R-04-08

Combined usage of Loop and If-then-else statement

Loops and If-then-else statements can be manipulated together to allow more flexibility and control. Often we also use the command break to interrupt when it is appropriate. An example is presented below.

R-04-09
R-04-10

Previous: Part 3 - If-then-else Statement

Last Update: 2020-10-17