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:
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:
#Assign values to our input variablesVAR_x <- 3VAR_y <- 2VAR_control <- 1#Whenever VAR_control is 1, execute the first set of bracketsif(VAR_control == 1) {#Perform a basic mathematical operationOUT_z <- VAR_x + VAR_y} else if (VAR_control == 2) { #Whenever VAR_control is 2,#execute the second set of bracketsOUT_z <- -1 * VAR_x #Perform some other operation} else { #Otherwise, execute the third set of bracketsOUT_z = 0}#Print the resultOUT_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 ...