Conditional Statements

Back

Loading concept...

🚦 R Control Flow: Conditional Statements

Imagine you’re a traffic cop directing cars at a busy intersection. Sometimes cars go left, sometimes right, sometimes straight—it all depends on where they want to go. That’s exactly what conditional statements do in R: they help your code make decisions!


🎯 What Are Conditional Statements?

Think of your code as a story where the hero (your program) reaches a fork in the road. Conditional statements are the signposts that say:

  • If it’s raining, take an umbrella”
  • If you’re hungry, eat lunch; else keep working”
  • Switch between different doors based on your magic key”

Let’s explore each type!


1️⃣ The if Statement

🧸 The Simple Question

The if statement is like asking a yes/no question. If the answer is “yes” (TRUE), do something. If “no” (FALSE), do nothing.

# Is it cold outside?
temperature <- 5

if (temperature < 10) {
  print("Wear a jacket!")
}

Output: "Wear a jacket!"

🎨 How It Works

graph TD A["Start"] --> B{Is condition TRUE?} B -->|Yes| C["Do the action"] B -->|No| D["Skip it"] C --> E["Continue"] D --> E

📝 The Recipe

if (condition) {
  # Code runs only if
  # condition is TRUE
}

Real-life example: A vending machine only gives you a snack if you put in enough money!


2️⃣ The if-else Statement

🍦 Two Choices

What if you want to do something different when the answer is “no”? That’s where else comes in!

age <- 8

if (age >= 18) {
  print("You can vote!")
} else {
  print("Too young to vote")
}

Output: "Too young to vote"

🎨 The Two Roads

graph TD A["Check age"] --> B{age >= 18?} B -->|Yes| C["Can vote!"] B -->|No| D["Too young"] C --> E["Done"] D --> E

📝 The Recipe

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

Think of it like: “If it’s sunny, play outside. Otherwise, play inside.”


3️⃣ Nested Conditionals

🪆 Decisions Inside Decisions

Sometimes one question leads to another—like a treasure hunt with multiple clues! You can put if statements inside other if statements.

score <- 85
attendance <- 90

if (score >= 60) {
  if (attendance >= 80) {
    print("You passed! 🎉")
  } else {
    print("Good score, but")
    print("attend more classes!")
  }
} else {
  print("Study harder!")
}

Output: "You passed! 🎉"

🎨 The Nested Path

graph TD A["Start"] --> B{score >= 60?} B -->|No| C["Study harder!"] B -->|Yes| D{attendance >= 80?} D -->|Yes| E["You passed! 🎉"] D -->|No| F["Attend more!"]

💡 Pro Tip: else if Chains

When you have many choices, use else if:

grade <- 75

if (grade >= 90) {
  print("A - Excellent!")
} else if (grade >= 80) {
  print("B - Great job!")
} else if (grade >= 70) {
  print("C - Good work!")
} else {
  print("Keep trying!")
}

Output: "C - Good work!"


4️⃣ The ifelse() Function

⚡ The Quick Decision Maker

R has a special shortcut called ifelse(). It’s like a tiny decision machine that works super fast—especially with lists of things!

# Check multiple ages at once!
ages <- c(5, 12, 18, 25, 8)

status <- ifelse(ages >= 18,
                 "Adult",
                 "Child")

print(status)

Output: "Child" "Child" "Adult" "Adult" "Child"

📝 The Recipe

ifelse(test, yes_value, no_value)
Part Meaning
test The question (TRUE/FALSE)
yes_value Answer if TRUE
no_value Answer if FALSE

🎯 One-Liner Magic

# Is the number even or odd?
num <- 7
result <- ifelse(num %% 2 == 0,
                 "Even", "Odd")
print(result)  # "Odd"

Why use it? When you need to check many values at once, ifelse() is your best friend!


5️⃣ The switch Statement

🚪 The Magic Door Selector

Imagine you have 5 doors, each with a different prize. The switch statement lets you pick the right door based on a key!

day <- "Monday"

message <- switch(day,
  "Monday" = "Start of week! 💪",
  "Friday" = "Weekend coming! 🎉",
  "Sunday" = "Rest day! 😴",
  "Regular day"  # Default
)

print(message)

Output: "Start of week! 💪"

🎨 How Switch Works

graph TD A["Get the key"] --> B{Which door?} B -->|Door 1| C["Prize 1"] B -->|Door 2| D["Prize 2"] B -->|Door 3| E["Prize 3"] B -->|Other| F["Default prize"]

📝 Two Ways to Use Switch

Way 1: Named choices (like above)

fruit <- "apple"
color <- switch(fruit,
  "apple" = "red",
  "banana" = "yellow",
  "grape" = "purple",
  "unknown"
)
# color = "red"

Way 2: Number position

choice <- 2
result <- switch(choice,
  "First option",
  "Second option",
  "Third option"
)
# result = "Second option"

🧠 Quick Comparison Table

Tool Best For Example Use
if One simple check “Is it raining?”
if-else Two outcomes “Pass or fail?”
Nested if Complex decisions “Check grade AND attendance”
ifelse() Many values at once “Label all ages in a list”
switch Multiple exact matches “Pick action for each day”

🎮 Putting It All Together

Here’s a fun example combining everything:

# Pizza ordering system! 🍕

size <- "large"
extra_cheese <- TRUE

# Use switch for size
base_price <- switch(size,
  "small" = 8,
  "medium" = 12,
  "large" = 16,
  10  # default
)

# Use if-else for extras
if (extra_cheese) {
  total <- base_price + 2
  print("Extra cheese added!")
} else {
  total <- base_price
}

# Final message
print(paste("Total: quot;, total))

Output:

"Extra cheese added!"
"Total: $ 18"

🌟 Remember This!

🚦 Conditionals are traffic cops for your code!

  • if = “Do this if yes”
  • else = “Otherwise do this”
  • Nested = “Decisions inside decisions”
  • ifelse() = “Quick checks for many items”
  • switch = “Pick from a menu of options”

You’ve just learned how to make your R code smart enough to make decisions! Now your programs can think, choose, and act differently based on any situation. 🎉


Happy coding! 🚀

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.