In this article, we will discuss how to find the maximum of two numbers with its working example in the R Programming Language using R if-else conditions.
Syntax:
max_number <- if (condition) {
# Code block executed if the condition is TRUE
value_if_true
} else {
# Code block executed if the condition is FALSE
value_if_false
}Example
num1 <- 10
num2 <- 15
# Using if-else to find the maximum
max_number <- if (num1 > num2) {
num1
} else {
num2
}
# Print the result
print(paste(max_number,'is the maximum number'))
Output:
[1] "15 is the maximum number"num1is assigned the value10, andnum2is assigned the value15.- The
ifstatement comparesnum1andnum2. Ifnum1is greater thannum2, the code inside the curly braces following theifstatement will be executed. Otherwise, the code inside the curly braces following theelsestatement will be executed. - In this case, since
num2is greater thannum1, the code inside theelseblock will be executed. This code assigns the value ofnum2to the variablemax_number. - The
printstatement is used to display the value ofmax_number, which is15, in the console.
Example:
num1 <- 100
num2 <- 50
# Using if-else to find the maximum
max_number <- if (num1 > num2) {
num1
} else {
num2
}
# Print the result
print(paste(max_number,'is the maximum number'))
Output:
[1] "100 is the maximum number"