2.5.1 If/Else
The if/else statement executes a block of code based on a specified condition. The syntax is:
# Syntax of If/Else statement
if (CONDITION) {
# Code block to be executed if CONDITION is TRUE
else {
} # Code block to be executed if CONDITION is FALSE
}
In this syntax, the code block will be executed based on whether the CONDITION is TRUE or FALSE. For example:
# Example 1
= 6
x if(x > 5){
print("x is greater than 5")
else{
}print("x is 5 or less")
}
In R, else
is not mandatory, especially for simple conditional checks. R allows you to use if to evaluate a condition and execute code if the condition is true, without requiring an else block to handle other cases. For example,
# Example 2
= 6
x if(x > 5){
print("x is greater than 5")
}
The ifelse
function in R is used to execute one of two values based on a specified condition, element-wise across a vector. The syntax is:
# Syntax of function 'ifelse'
ifelse(CONDITION, VALUE_IF_TRUE, VALUE_IF_FALSE)
In this syntax, ifelse
evaluates each element of CONDITION. If the element meets the CONDITION (is TRUE), VALUE_IF_TRUE is returned; otherwise, VALUE_IF_FALSE is returned. For example:
# Example 3
= c(3, 9, 1, 6, 5)
x = ifelse(x > 5, "grater than 5", "not grater than 5")
result print(result)
In this example, the code will check each element in x to see if it is greater than 5. If true, it will return “greater than 5”; otherwise, it will return “not greater than 5”.