R Programming - Part 3 - If-then-else Statement

11 Oct 2020 - Benjamin Loi

Introduction

This article will explain one of the most used programming structure, the if-then-else statement, and how it is written in R.

Boolean Values and Comparison

Often in the world of programming, we want to carry out some tests. Then based on the results of the tests, we perform corresponding actions, like calculation and assignment. Before talking about how to selectively execute certain actions after checks, we first need to know about the checks themselves, and the boolean values incurred. Boolean values can be regarded as true false values (TRUE, FALSE) usually obtained from comparison, including less than, greater than, equal to. In R they correspond to the operators < (<=), > (>=) and ==. The outputs of some comparisons are shown in the figure below.

R-03-00

Multiple Conditions

Sometimes a composite test may be needed in which two or more conditions are considered. To construct such a test, we will make use of two operators, || (or), && (and). && has a higher precedence than || and hence leads to the following outputs.

R-03-01

If-then-else Statement

Now we are able to formulate a test through comparison, and use it to selectively execute a particular part of the code. This is done by the if-then-else statement, with if, else and curly brackets. Given the condition in the if statement is satisfied, or it is TRUE, then the block under the if statement will be executed. Otherwise, FALSE will cause the block under the else statement to be run. A simple example is included below.

R-03-02
R-03-03

Else-if statement

Contrary to if and else which can only appear once in a single if-then-else structure, the composite operator else if can appear for an arbitrary amount of times in the same if-then-else structure. It checks the condition if the previous testing by if or else if fails, and when the current testing is fulfilled, the block under this particular else if statement is executed, and all the subsequent else if or else are ignored. An extended version of the previous example is displayed below.

R-03-04

Previous: Part 2 - Functions Next: Part 4 - For Loop, While Loop

Last Update: 2020-10-12