R If Statement
An if statement runs a block of code only when a specific condition is TRUE. It gives your program the ability to make decisions. Without if statements, a program runs the same code every time regardless of the data. With if statements, it adapts to different situations.
Syntax
if (condition) {
# code runs only when condition is TRUE
}
How It Flows
Program reaches if()
│
▼
Evaluate condition
│
┌────────┴────────┐
▼ ▼
TRUE FALSE
│ │
Run the code Skip the code
inside { } inside { }
│ │
└────────┬────────┘
▼
Continue program
Basic Example
temperature <- 38
if (temperature > 37.5) {
cat("You have a fever. Please rest.\n")
}
Output:
You have a fever. Please rest.
If temperature were 36, nothing would print — the block would be skipped entirely.
The Condition Must Be Logical
x <- 10
# Valid conditions (return TRUE or FALSE)
if (x > 5) { cat("greater\n") }
if (x == 10) { cat("ten\n") }
if (is.numeric(x)) { cat("numeric\n") }
# What happens with non-logical values
if (1) { cat("runs") } # 1 is treated as TRUE
if (0) { cat("skips") } # 0 is treated as FALSE
Single Line if (No Braces)
When the code block has only one statement, braces are optional — but keeping them is recommended for clarity.
score <- 75
if (score >= 50) cat("Pass\n") # works, no braces
if (score >= 50) { cat("Pass\n") } # preferred style
Nested If Statements
balance <- 5000
transaction <- 3000
if (transaction > 0) {
if (balance >= transaction) {
cat("Transaction approved\n")
}
}
Diagram:
transaction > 0?
│ YES
▼
balance >= transaction?
│ YES
▼
"Transaction approved"
Practical Example: Age Verification
age <- 20
if (age >= 18) {
cat("Access granted. Welcome!\n")
}
if (age < 13) {
cat("Parental guidance required.\n")
}
Output (age = 20):
Access granted. Welcome!
Using if With Variables
rainfall_mm <- 85
if (rainfall_mm > 75) {
alert <- "Heavy rain warning issued"
send_alert <- TRUE
}
if (exists("alert")) {
cat(alert, "\n")
}
Common Mistakes
# Mistake 1: Using = instead of ==
if (x = 5) { } # ERROR: use == for comparison
if (x == 5) { } # CORRECT
# Mistake 2: Condition outside parentheses
if x > 5 { } # ERROR: condition must be in ()
if (x > 5) { } # CORRECT
# Mistake 3: Comparing NA with ==
if (x == NA) { } # WRONG: always returns NA
if (is.na(x)) { } # CORRECT
The if statement is the simplest form of control flow in R. Every program that responds to data conditions — validation, alerting, filtering — starts with an if statement. Master this before moving to if-else and more complex control structures.
