In R programming, you can use if, else, and else if statements to create conditional logic, allowing your code to make decisions based on certain conditions. Here’s how you can use these statements:
- if Statement:
The if statement is used to execute a block of code only if a specified condition is true.
Example: Using if statement
x ← 10
if (x > 5) {
print(“x is greater than 5”)
}
- if-else Statement:
The if-else statement allows you to execute one block of code when a condition is true and another block of code when the condition is false.
Example: Using if-else statement
x ← 3
if (x > 5) {
print(“x is greater than 5”)
} else {
print(“x is not greater than 5”)
}
- if-else if-else Statement:
You can use the else if clause to handle multiple conditions in a series.
Example: Using if-else if-else statement
x ← 7
if (x > 10) {
print(“x is greater than 10”)
} else if (x > 5) {
print(“x is greater than 5 but not greater than 10”)
} else {
print(“x is not greater than 5”)
}
Remember that the if, else if, and else clauses should be enclosed in curly braces {} when there is more than one statement in the respective block.
These conditional statements allow you to control the flow of your program based on different conditions. You can nest them within each other to create more complex decision-making structures.