How to Use If Else in R: Simple Guide with Examples
In R, use
if to run code when a condition is true, and else to run code when it is false. The syntax is if (condition) { code } else { code }. This helps your program make decisions based on conditions.Syntax
The if else statement in R lets you choose between two actions based on a condition.
- if (condition): Checks if the condition is true.
- { code }: Runs this code if the condition is true.
- else: Runs this code if the condition is false.
r
if (condition) { # code to run if condition is TRUE } else { # code to run if condition is FALSE }
Example
This example checks if a number is positive or not and prints a message accordingly.
r
number <- 5 if (number > 0) { print("The number is positive") } else { print("The number is zero or negative") }
Output
[1] "The number is positive"
Common Pitfalls
Common mistakes include missing curly braces or using else without an if. Also, placing else on a new line without the previous block ending properly can cause errors.
Always put else right after the closing brace of if block.
r
## Wrong way (causes error): number <- -3 if (number > 0) print("Positive") else print("Not positive") ## Right way: if (number > 0) { print("Positive") } else { print("Not positive") }
Output
[1] "Not positive"
Quick Reference
Use if to check a condition and run code if true. Use else to run code if false. Always use curly braces { } to group code blocks.
| Keyword | Purpose | Example |
|---|---|---|
| if | Runs code if condition is TRUE | if (x > 0) { print("Positive") } |
| else | Runs code if condition is FALSE | else { print("Not positive") } |
Key Takeaways
Use if else in R to run different code based on conditions.
Always put else immediately after the if block's closing brace.
Use curly braces { } to group code inside if and else.
Conditions inside if must be logical expressions returning TRUE or FALSE.
Indent your code inside if else blocks for better readability.