Conditionals in R Programming


Introduction

Conditional statements in R are used to perform different actions based on certain conditions. These include if, else, and else if statements.

1. if Statement

The if statement executes a block of code if a specified condition is true.

Syntax:

    if (condition) {
      # Code to execute if condition is TRUE
    }
        

Example:

    number <- 10
    if (number > 5) {
      print("The number is greater than 5")
    }
        

2. if-else Statement

The if-else statement executes one block of code if the condition is true, and another block if the condition is false.

Syntax:

    if (condition) {
      # Code to execute if condition is TRUE
    } else {
      # Code to execute if condition is FALSE
    }
        

Example:

    number <- 3
    if (number > 5) {
      print("The number is greater than 5")
    } else {
      print("The number is not greater than 5")
    }
        

3. if-else if-else Statement

The if-else if-else statement is used to check multiple conditions in sequence.

Syntax:

    if (condition1) {
      # Code to execute if condition1 is TRUE
    } else if (condition2) {
      # Code to execute if condition2 is TRUE
    } else {
      # Code to execute if none of the conditions are TRUE
    }
        

Example:

    number <- 7
    if (number > 10) {
      print("The number is greater than 10")
    } else if (number > 5) {
      print("The number is greater than 5 but less than or equal to 10")
    } else {
      print("The number is 5 or less")
    }
        

4. Nested if Statements

Conditional statements can be nested inside each other to check multiple levels of conditions.

Example:

    number <- 15
    if (number > 10) {
      if (number %% 2 == 0) {
        print("The number is greater than 10 and even")
      } else {
        print("The number is greater than 10 and odd")
      }
    } else {
      print("The number is 10 or less")
    }
        

Conclusion

Conditional statements in R allow for dynamic decision-making in code. They enable you to execute different blocks of code based on specific conditions.





Advertisement