R If … Else
🔀 R If … Else
It allows your program to execute different code blocks based on conditions.
🔹 1. Basic if Statement
Syntax:
Example:
🔹 2. if … else Statement
Syntax:
Example:
🔹 3. else if Statement (Multiple Conditions)
Syntax:
Example:
🔹 4. Nested if … else
An if inside another if.
🔹 5. Logical Conditions in if
You can use logical operators (&, |, &&, ||).
🔹 6. ifelse() Function (Vectorized)
Used when working with vectors.
Syntax:
Example:
Output:
✔ Faster and cleaner for vectors
🔹 7. Common Mistakes ❌
❌ Using = instead of ==
✅ Correct:
❌ Forgetting braces for multiple lines
🔹 8. Best Practices ✔
Always use curly braces
{}Keep conditions simple and readable
Use
ifelse()for vector operations
📌 Summary
ifchecks a conditionelseruns when condition is FALSEelse ifhandles multiple conditionsifelse()works best with vectors
