Flow Control

Learn to control the flow of R scripts using conditional if statements and loops.

We’ll often need two fundamental structures for our code: conditional statements and loops. These let us control the flow of our code such that certain sections are executed only when a specific condition indicates that they should be, or certain sections are repeated until a criterion is met.

Conditional statements

Firstly, conditional statements let us group several lines of code and set them to execute only when a condition is met. For our purposes, we will focus on the if statement, which lets us control our code according to the tree below:

Press + to interact
Flow of code execution through an if-else if-else structure
Flow of code execution through an if-else if-else structure

The idea is that we can encapsulate a true or false statement into the if statement. If the if statement is true, then it causes some section of code to be executed. If the if statement is false, then the else if statements are sequentially checked until one is true and its associated code is executed. If none of the else if statements are true, then the else statement is executed. Note that all of these elements are optional. We can have an if statement with no else if or no else. Here is how this looks in actual code:

Press + to interact
#Assign values to our input variables
VAR_x <- 3
VAR_y <- 2
VAR_control <- 1
#Whenever VAR_control is 1, execute the first set of brackets
if(VAR_control == 1) {
#Perform a basic mathematical operation
OUT_z <- VAR_x + VAR_y
} else if (VAR_control == 2) { #Whenever VAR_control is 2,
#execute the second set of brackets
OUT_z <- -1 * VAR_x #Perform some other operation
} else { #Otherwise, execute the third set of brackets
OUT_z = 0
}
#Print the result
OUT_z

There are a couple of new elements here:

  • Lines 7–15: Encapsulate an if-else if-else statement structure, described in detail below.

  • Lines 7 and 10: Contain comparison operators (in this case ==), which are described in detail below.

if statement structure

Firstly, we have an if(something) {one thing} else if {do something else} structure. The terms if, else if, and else are special keywords that let R know we’re sectioning off a conditional statement. In our case, if something is true, then the first statement will be ...