![]() |
VOOZH | about |
In R programming, conditional statements allow a program to make decisions and execute different actions based on certain conditions. The if-else construct is a key conditional statement used to control the flow of code. Using these statements, you can handle different situations dynamically.
if (condition) {
# code to execute if condition is TRUE
} else {
# code to execute if condition is FALSE
}
if-else statements control the flow of a program by executing different code blocks based on a condition.
Here we implement a basic if-else statement in R to check whether a number is greater than or less than 10.
Output
[1] "5 is less than 10"
Here x is initialized to 5, the condition x > 10 is false, so the program executes the else block and prints: "5 is less than 10."
Here we use an if-else statement in R to check whether a number is equal to 10 or not.
Output:
[1] "5 is not equal to 10"
Here x is 5, the condition x == 10 is false, so the else block runs and prints: "5 is not equal to 10."
The if-else statements in R can be nested to form a group of statements that evaluate conditions one by one, starting from the outer condition to the inner ones. An if-else statement placed within another if-else statement in R is called a nested statement.
Syntax
if(condition1) {
# execute if condition1 is TRUE
if(condition2) {
# execute if both condition1 and condition2 are TRUE
}
} else {
# execute if condition1 is FALSE
}
Here nested if-else in R evaluates multiple conditions to find the range of x
Output:
[1] "x is between 10 and 20"
In this R code we uses nested if-else statements to assess whether a student qualifies for a scholarship based on grades and income
Output:
[1] "Congratulations, you are eligible for a scholarship!"
Here we will show the use of logical conditions in if statements. Adjust the values and conditions as needed for our specific requirements.
| Operator | Meaning | Example |
|---|---|---|
| == | Equal | x == y |
| != | Not equal | x != y |
| > | Greater than | a > b |
| < | Less than | x < y |
| >= | Greater than or equal to | x >= y |
| <= | Less than or equal to | x <= y |