Conditional Statements in R - If, If-else, elseif, Nested if, Switch


April 7, 2022, Learn eTutorial
3031

We already discussed the basics of control structures in the previous tutorial. In this tutorial, we focus on learning conditional statements or decision-making statements in the R programming language. Let us move forward with each type of conditional statement.

The conditional statements further include

  • If statement
  • If-else statement
  • If-else if-else statement
  • Nested if-else statement
  • R-switch statement
  • ifelse() function, a shorthand declaration of if-else statement.

If control statement in R

If control structure in R programming language evaluates a given condition or expression is satisfied. The block of statement inside the curly braces {} is executed only when the condition followed by the if keyword is satisfied. The condition should be evaluated either as TRUE or FALSE.

If the condition is TRUE the codes or statements just after the condition provided in {} will execute otherwise the control will switch to the next statement immediately after the if statement.

A general structure for the control flows during the if condition is depicted in below flow chart.

if control flowchart

Syntax


If(condition){
#Perform some instructions
       ……..
       ……..
}

Example


a = 5
b = 7
if(a<b){
  print(paste(a,"is smaller than ", paste(b)))
}

Created two variables a and b with values assigned as  5 and 7 respectively. The condition is to check whether the value in a is smaller than the value in b.The syntax if(a<b) checks the condition (a<b) and evaluate the statements inside the {} braces if condition is met TRUE.

The output produced by the corresponding block of code is


[1] "5 is smaller than  7"

Let us see what happens if the condition is not satisfied, the value assigned to a is modified to 8, which is greater than the value in b(7). Here the condition is followed by a keyword if statement goes wrong or unsatisfied because 8<7 is FALSE.


a = 8
b = 7
if(a<b){
  print(paste(a,"is smaller than ", paste(b)))
}
 print(paste(a ,"is greater than",paste(b)))
 print("The condition (a<b) is not satisfied")

The output generated by the above code is


[1] "8 is greater than 7"
[1] "The condition (a<b) is not satisfied"

From the output, you can observe that the statement outside the curly braces {} is executed and displayed. The control flows to the next statement immediately followed by the if condition if the expression evaluated returns a false result.

If-else control statement in R

If-else is another control structure somewhat similar to if statements but here you can provide an else part after the if condition. The if condition checks the condition or expression to be evaluated inside the curly braces {} is True or false. If it returns a true then executes the block of codes inside the {} curly braces. On the other hand, if the expression or the condition evaluated is false the code provided inside the else part will get executed.

Let us understand the if-else control structure in R programming with a flow chart

if-else control flowchart

Syntax of if-else control structure


If( condition) {
//do some instructions
}else {
//do some instructions
}

Example shows two variables a and b with values 5 and 7 are assigned to it are declared. The condition needs to check if the value in a is less than that in a. The condition (a<b) is evaluated and if true executes the code under the if condition. On the other hand, the condition (a<b) fails to satisfy the control jumps to the else part and executes the code of statements provided inside the else part curly braces {}.


a = 5
b = 7
if(a<b){
  print(paste(a,"is smaller than ", paste(b)))
  print("Terminated if condition")
}else{
print(paste(a ,"is greater than",paste(b)))
print("The condition (a<b) is not satisfied")
print("Executed else condition")
}

The below output is generated by executing the code for the if-else control structure, here 5<7 is evaluated as true and displays the codes inside {}


[1] "5 is smaller than  7"
[1] "Terminated if condition"

Let us check the case when if condition fails to execute, the else part of the control structure starts executing. We modify the value of a as 8, which affects the condition (a<b) to be evaluated which returns a false result. So else part codes get executed.


a = 8
b = 7
if(a<b){
  print(paste(a,"is smaller than ", paste(b)))
  print("Terminated if condition")
}else{
print(paste(a ,"is greater than",paste(b)))
print("The condition (a<b) is not satisfied")
print("Executed else condition")
}

The output generated is statements enclosed inside the else part.


[1] "8 is greater than 7"
[1] "The condition (a<b) is not satisfied"
[1] "Executed else condition"

Compare the syntax of if and if-else and the examples we discussed to get a clear picture of both these control structures. In if statements the code after it gets executed, in if-else when the execution of if fails sequence of control flow moves to execute else region.

If- else if - else control statement in R

The control structure can be customized with the addition of an else if statement in between if and else statements. The R provides multiple else if conditions to be included between if and else statements.

The execution begins with evaluating the condition inside the if statement (if(condition)) if it returns a true, the set of statements under if(condition) gets executed. Suppose If condition fails the remaining multiple else if(condition) starts checking one by one. The condition which satisfied gets executed others are discarded. The else part at the end is to display if all the condition gets unsatisfied.

When the if condition evaluates to be TRUE then prints the code of statements just below if condition. And ignores or skips all the rest of the statements.

On the other hand when the if condition seems to be FALSE the control moves or jumps to else if statement just below the if statement. Evaluates  else if condition if it is satisfied or TRUE the resulting print statement gets executed. And R ignores the below codes. When both if and else if condition is unsatisfied that is their result remains FALSE the else part gets executed. You can have multiple else if statements between the if and else code of statements

 

Syntax of if-else control structure


if(condition){
   //do some instructions

}else if(condition){
   //do some instructions

}else{
   //do some instructions
}

The flow chart to represent if-else is

Switch control flowchart

Example


a = -3           #varaible a is assigned value -3

if(a<0){         #checks if (condition)
  print("negative number")
  print("Terminated if condition")
}else if(a>0){    #checks else  if (condition)
  print("positive number")
  print("Executed else if condition")
}else{            #checks  else  region
  print("a is zero")
}

There are three different regions in code that get executed based on the evaluation of our expression. Suppose the if(condition) is satisfied “a is less than 0” (a<0) the sequence of statements inside the curly braces gets executed. The resulting output will be displayed as shown below when a is -3 and if condition gets satisfied


[1] "negative number"
[1] "Terminated if condition"

When the value assigned to a is other than some negative numbers the control navigates the next section of syntax we described that is else if(condition). The condition is given inside the parentheses followed by else-if begins to evaluate. If condition in our example “a is greater than 0” (a>0) is found to be true then displays the corresponding output by executing the series of codes inside the curly braces {} of else if.


[1] "positive number"
[1] "Executed else if condition"

If all the condition goes unsatisfied i.e. a False value after evaluating the expressions the code inside the else part gets executed.


[1] "a is zero"

Nested if in R

In R programming one if statement inside another if statement is defined as a nested if statement.

When the if condition evaluates to be TRUE immediately control jumps to nested if condition and starts evaluating the condition given inside the if statement. After evaluation, if the result is TRUE or satisfied the block of codes just below the inner if condition enclosed within curly braces gets executed. On the other hand if the inner if condition falls as FALSE the else part code region gets executed. Till now we discussed when the outer if condition is evaluated to be TRUE.

When the outer if condition is  FALSE after its evaluation the control jumps to the else part at the end section and executes the instruction given inside its curly braces.

Syntax of Nested if


if(condition) {  #outer if
     
    If(condition) { #inner if
        //do some instructions
    } else {
        //do some instructions
    }
} else {
    //do some instructions
}

Nested if control flowchart

The program shows when the outer if condition is satisfied inner if condition gets executed. In the example, x is assigned a value of 23.

  • If (x>20) is evaluated as TRUE control jumps to immediate if condition  if (x > 0).
  • Evaluates  if (x > 0) if it is TRUE print statements inside {} otherwise execute else region followed by the inner if condition.
  • Terminates control structure execution.

x < -23

if (x > 20) {
    print("x is greater than 20")
    if (x > 0) {
        print("x is greater than 0")
    } else {
        print("x is negative ")
    }
} else {
    print("x is zero.")
}

Output


[1] "x is greater than 20"
[1] "x is greater than 0"


Program to show when outer if condition meets FALSE control jumps to else region without executing nested if condition to terminate the control structure. Given a variable x is assigned a value of 23.

  • if (x > 25) is FALSE  control jumps to next inner if condition(if (x > 0))
  • control jumps to the else part at the end of the control structure and prints block of statements inside {}.
  • control structure terminates

x < -23

if (x > 25) {
    print("x is greater than 20")
    if (x > 0) {
        print("x is greater than 0")
    } else {
        print("x is negative ")
    }
} else {
    print("x is greater than 25.")
}

Output


[1] "x is greater than 25."

Switch control statement in R

The switch control structure is another control statement and is somewhat similar to the else-if functionality. The R programming language using switch statements has m number of options to choose and execute any one of the options (cases) by validating which case satisfies the requirement of the provided condition. When the condition matches with the corresponding case then that case will only execute.

Thus the switch() statement in R programming language evaluates a condition against a list of given elements or values and always returns the first matching element or value from the list.

The switch control structure in R evaluates the expression or the condition provided and accordingly selects the arguments such as case1 and case2 inside the parentheses ().

Syntax


switch(condition,case1 = “”,case2= “”,………., Default statement)

Where

  • condition is the expression to be evaluated.
  • ……… is the alternative list such as case1,case2, etc.
  • Default statement is executed when the match case to the condition is missing 

The first argument is always the condition or expression to evaluate.

Consider an example


a <- switch(
   4, #condition
  #(...... or case1,case2..)
  "red",              #case1
  "blue",             #case2
  "pink",             #case3
  "orange"            #case4
) 

print(a)  

The switch evaluates the condition given 4 and the corresponding element in the list of arguments matching with it is returned. Here condition 4 matches with case4. Let us see the output displayed when the code is executed.


[1] "orange"

The flow chart for the switch control structure is

Switch control flowchart

In case the condition to evaluate is an integer beyond the number of cases within the switch statement it returns a NULL value. In the above example when the condition is modified to 5 and after searching for the selection of the corresponding match with each case, no cases are existing will return a NULL value.

Look at the snippet below

Switch control flowchart

A default statement can also be provided instead of returning a NULL. The same code with the default case attached to it is given below


a <- switch(          
  5,   #condition
  #(...... or case1,case2..)
  "red",              #case1
  "blue",             #case2
  "pink",             #case3
  "orange" ,          #case4
   print("no match found")  #default statement
  #no more cases exist to evaluate so returns default statement
)  

print(a)

The output when no match is found and a default statement do exist is


[1] "no match found"

NOTE: the default statement is optional in the switch control structure.

The switch control structure is evaluated in two different ways depending upon the initial argument is a number or character string.

  1. If the value to evaluate against the condition is not a character string it is coerced to an integer type.
  2. If the condition evaluates to be a character string then the string matches with corresponding elements given in the argument list and returns the result. 
  3. If there are more than one element matches with the condition then only the first match is returned as output.

    Example shows in the first example color red of string type is matched with the first case or element in the list in the second example color blue is matched with the first element based on their position in the options.

    
    >  switch("color", "color" = "red", "shape" = "circle", "radius" = 5,"color" = "blue")
    [1] "red"
    > switch("color", "color" = "blue", "shape" = "circle", "radius" = 5,"color" = "red")
    [1] "blue"
    >
    
    

    NOTE: The switch() function contains a string given as a condition(expression) to test.

  4. In case the matching element need to evaluate is missing then the immediate next non-missing element is returned.

    Consider the example to evaluate a missing match against an expression or condition but return the immediate case after the match. In the below example the condition to evaluate is color where the value corresponding to color is missing so the next case shape gets returned as output in such cases. In the same way, try to understand the next example.

    
    > switch("color", "color" = , "shape" = "circle", "radius" = 5,"color" = "blue")
    [1] "circle"
    > switch("color", "color" = , "radius" = 5,"shape" = "circle", "color" = "red")
    [1] 5
    
    
  5. In case no match is found the unnamed element of the cas1,case2……… (alternatives of the list) of syntax or arguments will be returned.

ifelse() function in R

The ifelse() function is a very useful function in the R programming language. It can be considered as an immediate if statement which means it evaluates the object in the first parameter of the ifelse() function and if it is TRUE returns the object in the second parameter. In the case of FALSE, it returns the object in the third parameter. When you perform certain operations most of the inputs are taken as vectors.

In R programming language ifelse() function is a shorthand representation of the conditional statement if-else. Check the if-else description to refresh the concept of the same. The below syntax is used for ifelse().

Syntax


Ifelse(condition,TRUE,FALSE)

Where

  • condition is the expression to evaluate or test. (parameter 1)
  • The TRUE denotes the statement or instruction to execute if condition is satisfied. (parameter 2)
  • The  FALSE denotes the statement or instruction to execute if condition is not satisfied. (parameter 3)

Consider the example to check a person’s fitness. Suppose let us categorize people with a weight greater than 40 are fit as others are unfit. Create a vector weight “wgt” using the c() function which is the input vector used to check the condition. The second and third parameters are TRUE and FALSE. The condition to check is whether people with a weight greater than 41 are fit. A value of 1 is returned if the condition is satisfied else 0(false)

Example


#ifelse(condition.TRUE,FALSE)
#Create a variable weight

wgt = c(39,48,42,52,60,41,38,49,58)

# we need to select weights greater than 41
#statements = weight >=41
#TRUE: people are fit(1)
#FALSE : people are not fit(0)

fit_enough = ifelse(wgt>=41,1,0)
print(fit_enough)

The output produced is given below which shows only 2 people are not fit with weight 39, 38 which is represented by value 0.


[1] 0 1 1 1 1 1 0 1 1

Instead of writing separate codes like if and else both are incorporated within a single ifelse() function to check both conditions in a single step.