Skip to Content

Control Flow in R

In this article, we will be covering what control flow is conceptually, and how we can establish control flow in R. We will introduce if/else blocks through various examples and challenges.

How do we program decision-making into our code? In this article, we will be covering what control flow is conceptually, and how we can establish control flow in R. Note that this is written with a beginner programming level in mind.

First, take a look at the diagram above. This is a series of decisions we might be making each morning, where a YES will send us one way, and a NO will send us the other. Different choices open up, while other outcomes become impossible.

A flow chart of different decisions one makes in the morning. It starts at morning. Asks, is It a weekday? If yes, Get up at 8:30. If no, Get up at 6:30. If it's not a weekday and you get up at 8:30, you ask Do I need to go outside? If yes, Stay in PJs. If no, Get dressed. If it is a weekday and you get up at 6:30, you ask Is it raining? If no, Don't wear a raincoat. If yes, Wear a raincoat.

We want our programs, in R or otherwise, to have a similar way of making decisions based on whether certain conditions are true at different steps. A program will run and start moving through its checklists and ask “is this condition met?” then execute a code block if the answer is yes, or skip it if the answer is no. This is the Control Flow of a program.

R is a script language, meaning every code file executes from the top down, until there is nothing left to run. It is the programmer’s job to include gateways throughout, known as conditional statements, to tell the computer whether or not it should execute certain blocks of code.

In this article, we will cover how to build conditional statements that check logical (TRUE or FALSE) values, just like the YES’s or NO’s from above, and manage the control flow in our code.

If statements

The most basic kind of conditional statement is an if statement. If a certain condition is true, execute this code. The syntax looks like so:

if (condition_to_check) { # code to execute }

A short example:

a <- 10 if (a < 12) { print("The variable a is less than 12") }

if is an R keyword, followed by a condition inside the parentheses. The code for the condition should evaluate to a TRUE or FALSE. As a refresher, in order for a code expression to evaluate to a TRUE or FALSE value, we can use comparison operators like <, >, >=, <=, ==, and !=. We can combine TRUE and FALSE values with logical operators like & (AND), | (OR), and ! (NOT).