Conditional Statements in R

📘 Introduction

Conditional statements allow a program to make decisions based on specified conditions. They enable the program to execute different blocks of code depending on whether a condition evaluates to TRUE or FALSE. Conditional statements are fundamental to building intelligent and dynamic R programs.

Information

In R, conditions are logical expressions that evaluate to either TRUE or FALSE. Based on the result, R decides which code block to execute.

đŸŽ¯ Why Use Conditional Statements?

  • Make decisions in programs.
  • Execute different actions for different conditions.
  • Validate user input.
  • Implement business rules and logical operations.
  • Create interactive and intelligent applications.

📚 Types of Conditional Statements

Conditional Statements
if
if...else
if...else if...else
switch()

🔹 The if Statement

The if statement executes a block of code only when the specified condition is TRUE.

Syntax of if Statement

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

Example: if Statement

age <- 20

if (age >= 18) {
  print("Eligible to vote")
}

Output

Console Output

[1] "Eligible to vote"

🔸 The if...else Statement

The if...else statement executes one block of code when the condition is TRUE and another block when it is FALSE.

Syntax of if...else

if (condition) {
  # Executed if TRUE
} else {
  # Executed if FALSE
}

Example: if...else

marks <- 35

if (marks >= 40) {
  print("Pass")
} else {
  print("Fail")
}

Output

Console Output

[1] "Fail"

🔹 The if...else if...else Statement

Use multiple conditions when more than two possible outcomes are required.

Syntax of if...else if...else

if (condition1) {
  # Code
} else if (condition2) {
  # Code
} else {
  # Code
}

Example: Grade Calculation

marks <- 82

if (marks >= 90) {
  print("Grade A+")
} else if (marks >= 75) {
  print("Grade A")
} else if (marks >= 60) {
  print("Grade B")
} else if (marks >= 40) {
  print("Grade C")
} else {
  print("Fail")
}

Output

Console Output

[1] "Grade A"

🔀 The switch() Function

The switch() function selects one option from multiple choices based on a specified expression. It is useful when there are many fixed alternatives.

Syntax of switch()

switch(expression,
       option1 = statement1,
       option2 = statement2,
       option3 = statement3
)

Example: switch()

day <- "Monday"

result <- switch(
  day,
  Monday = "Start of the week",
  Friday = "Weekend is near",
  Sunday = "Holiday",
  "Invalid Day"
)

print(result)

Output

Console Output

[1] "Start of the week"

🔗 Using Logical Operators in Conditions

Logical operators allow multiple conditions to be combined into a single expression.

Logical Operators Example

age <- 25
citizen <- TRUE

if (age >= 18 && citizen) {
  print("Eligible to vote")
}

Output

Console Output

[1] "Eligible to vote"

🧮 Nested Conditional Statements

An if statement can be placed inside another if statement to evaluate multiple levels of conditions.

Nested if Statement

age <- 22
has_license <- TRUE

if (age >= 18) {
  if (has_license) {
    print("Eligible to drive")
  } else {
    print("License required")
  }
} else {
  print("Too young to drive")
}

📊 Flow of Conditional Statements

Evaluate Condition
Condition is TRUE
Condition is FALSE
Execute TRUE Block
Execute FALSE Block

🌍 Real-World Example

The following program determines whether a customer receives a shopping discount based on the purchase amount.

Shopping Discount

purchase <- 6500

if (purchase >= 5000) {
  discount <- purchase * 0.10
  print(paste("Discount:", discount))
} else {
  print("No discount available")
}

Output

Console Output

[1] "Discount: 650"

📋 Comparison of Conditional Statements

StatementPurposeBest Used When
ifExecute code when a condition is true.Only one condition needs checking.
if...elseChoose between two alternatives.Exactly two possible outcomes exist.
if...else if...elseEvaluate multiple conditions.Several outcomes are possible.
switch()Select one option from many.Working with fixed choices.

âš ī¸ Common Mistakes

MistakeExplanationSolution
Using = instead of === is used for assignment, not comparison.Use == to compare values.
Forgetting curly bracesCan reduce readability and cause logic errors.Always use for code blocks.
Writing overlapping conditionsConditions may produce unexpected results.Arrange conditions from most specific to most general.
Using vector conditions with ifif expects a single logical value.Ensure the condition evaluates to one TRUE or FALSE.

💡 Best Practices

  • Write clear and meaningful conditions.
  • Use indentation to improve readability.
  • Choose switch() when handling many fixed options.
  • Avoid deeply nested conditional statements whenever possible.
  • Test all possible outcomes to ensure correct program behavior.

Best Practice

Well-structured conditional statements make programs easier to understand, maintain, and debug. Keep conditions simple and organize them logically.

📝 Summary

Conditional statements enable R programs to make decisions based on logical conditions. You learned how to use if, if...else, if...else if...else, and switch() to control program flow. You also explored logical operators, nested conditions, and best practices for writing clear and reliable decision-making code. Mastering conditional statements is essential for creating interactive and intelligent R applications.

>>"Conditional statements give programs the ability to think, decide, and respond based on changing conditions."