3 min read•august 9, 2024
If-else statements are the backbone of decision-making in R programming. They allow your code to take different paths based on specific conditions, enabling dynamic and responsive program behavior.
These statements are crucial for creating flexible and intelligent programs. By mastering if-else structures, you'll be able to handle various scenarios in your code, from simple binary decisions to complex multi-condition logic trees.
if
statement evaluates a condition and executes code block if trueelse
statement provides alternative code block when if
condition is falseelse if
statement allows multiple conditions to be checked sequentially[&&](https://www.fiveableKeyTerm:&&)
, [||](https://www.fiveableKeyTerm:||)
, !
) and comparison operators ([==](https://www.fiveableKeyTerm:==)
, [!=](https://www.fiveableKeyTerm:!=)
, [<](https://www.fiveableKeyTerm:<)
, >
, [<=](https://www.fiveableKeyTerm:<=)
, [>=](https://www.fiveableKeyTerm:>=)
)if (x > 0 && (y < 10 || z == 5)) { ... }
[switch](https://www.fiveableKeyTerm:switch)
statement provides efficient alternative to multiple else if
statements
switch(expression, case1 = action1, case2 = action2, ...)
[ifelse()](https://www.fiveableKeyTerm:ifelse())
function offers vectorized conditional operations
ifelse(test, yes, no)
yes
or no
based on test
temp <- 25 if (temp < 0) { print("Freezing") } else if (temp < 10) { print("Cold") } else if (temp < 20) { print("Cool") } else { print("Warm") }
switch
:
grade <- function(score) { switch(as.character(score), "A" = "Excellent", "B" = "Good", "C" = "Average", "D" = "Poor", "F" = "Fail", "Invalid grade") }
&&
(AND) requires both conditions to be true||
(OR) requires at least one condition to be true!
(NOT) negates a condition&&
stops evaluating if first condition is false||
stops evaluating if first condition is true==
(equal to)!=
(not equal to)<
(less than)>
(greater than)<=
(less than or equal to)>=
(greater than or equal to)TRUE
or FALSE
(x > 0 && x < 10) || (y >= 20 && y <= 30)
subset(df, age > 18 & income < 50000)
ifelse(temperatures > 30, "Hot", "Not Hot")
classify_bmi <- function(bmi) { if (bmi < 18.5) return("Underweight") else if (bmi < 25) return("Normal") else if (bmi < 30) return("Overweight") else return("Obese") }
{ }
in Rif (condition) { # Code block for true condition statement1 statement2 return(result) }
if (age >= 18) { if (income > 50000) { if (credit_score > 700) { print("Approved for premium card") } else { print("Approved for standard card") } } else { print("Approved for basic card") } } else { print("Not eligible for credit card") }
if (age < 18) return("Not eligible") if (income <= 50000) return("Basic card") if (credit_score <= 700) return("Standard card") return("Premium card")