If else Statements in R
If else Statements in R
In any programming language, decision making and control structures are crucial. In R, the if else
statement is one of the fundamental control structures that allows us to perform different actions based on different conditions. This tutorial will guide you through the understanding and implementation of if else
statements in R.
Understanding the 'If Else' Statement
The if else
statement in R tests a condition, and if the condition is TRUE
, it executes the expression following the if
keyword. If the condition is FALSE
, it executes the expression following the else
keyword.
Here is the basic syntax of if else
statement in R:
if(condition){
# code to be executed if condition is TRUE
} else {
# code to be executed if condition is FALSE
}
Simple if Statement
Let's start with a simple if
statement. In this case, we only handle the situation when the condition is TRUE
.
x <- 10
if(x > 5){
print("x is greater than 5")
}
When you run this code, you will see "x is greater than 5" in the output because the condition x > 5
is TRUE
.
If Else Statement
Now, let's add an else
part to handle the situation when the condition is FALSE
.
x <- 3
if(x > 5){
print("x is greater than 5")
} else {
print("x is not greater than 5")
}
In this case, you will see "x is not greater than 5" in the output because the condition x > 5
is FALSE
.
If Elseif Else Statement
If we need to check multiple conditions, we can use else if
keyword. You can add as many else if
parts as you need.
x <- 10
if(x > 20){
print("x is greater than 20")
} else if(x > 15){
print("x is greater than 15")
} else {
print("x is not greater than 15")
}
In the above example, you will see "x is not greater than 15" in the output.
Nested If Else Statement
We can also nest if else
statements within each other.
x <- 10
if(x > 5){
if(x > 15){
print("x is greater than 15")
} else {
print("x is between 5 and 15")
}
} else {
print("x is not greater than 5")
}
In this example, you will see "x is between 5 and 15" in the output.
Conclusion
The if else
statement is a basic but powerful control structure in R, which allows us to handle different situations based on different conditions. Practice with different scenarios to get used to this structure, as it is widely used in R programming.