Menu
Coddy logo textTech

If Statement

Part of the Fundamentals section of Coddy's R journey — lesson 22 of 78.

Now that you know how to create logical expressions, it's time to make your programs actually do something based on those conditions. The if statement lets your code make decisions.

An if statement runs a block of code only when a condition is TRUE:

temperature <- 35

if (temperature > 30) {
  print("It's hot outside!")
}

When R encounters an if statement, it evaluates the condition inside the parentheses. If the result is TRUE, the code inside the curly braces {} executes. If it's FALSE, R skips that block entirely and continues with the rest of the program.

You can use any expression that evaluates to a logical value as your condition, including the comparison and logical operators you've already learned:

age <- 20
has_id <- TRUE

if (age >= 18 && has_id) {
  print("Access granted")
}

The code inside the braces only runs when both conditions are met. If either age is below 18 or has_id is FALSE, nothing happens.

challenge icon

Challenge

Easy

Use an if statement to check a condition and print a message only when the condition is TRUE.

You are provided with the following variables:

balance <- 250
withdrawal_amount <- 100
is_account_active <- TRUE

Write an if statement that checks if the following conditions are all met:

  • The account is active
  • The balance is greater than or equal to the withdrawal amount

If both conditions are TRUE, print the message "Withdrawal approved" using the print() function.

If the conditions are not met, your code should produce no output.

Cheat sheet

The if statement executes a block of code only when a condition is TRUE:

if (condition) {
  # code to run when condition is TRUE
}

Example:

temperature <- 35

if (temperature > 30) {
  print("It's hot outside!")
}

You can use comparison and logical operators in the condition:

age <- 20
has_id <- TRUE

if (age >= 18 && has_id) {
  print("Access granted")
}

If the condition evaluates to FALSE, the code block is skipped entirely.

Try it yourself

# Variables provided
balance <- 250
withdrawal_amount <- 100
is_account_active <- TRUE

# TODO: Write your code below
# Use an if statement to check if:
# 1. The account is active
# 2. The balance is greater than or equal to the withdrawal amount
# If both conditions are TRUE, print "Withdrawal approved"
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals