R if…else Statement
In this article, you will learn to create if and if…else statement in R programming with the help of examples.
Decision making is an important part of programming. This can be achieved in R programming using the conditional if...else
statement.
R if statement
The syntax of if statement is:
if (test_expression) {
statement
}
If the test_expression
is TRUE
, the statement gets executed. But if it’s FALSE
, nothing happens.
Here, test_expression
can be a logical or numeric vector, but only the first element is taken into consideration.
In the case of numeric vector, zero is taken as FALSE
, rest as TRUE
.
Flowchart of if statement
Example: if statement
x <- 5
if(x > 0){
print("Positive number")
}
Output
[1] "Positive number"
if…else statement
The syntax of if…else statement is:
if (test_expression) {
statement1
} else {
statement2
}
The else part is optional and is only evaluated if test_expression
is FALSE
.
It is important to note that else must be in the same line as the closing braces of the if statement.
Flowchart of if…else statement
Example of if…else statement
x <- -5
if(x > 0){
print("Non-negative number")
} else {
print("Negative number")
}
Output
[1] "Negative number"
The above conditional can also be written in a single line as follows.
if(x > 0) print("Non-negative number") else print("Negative number")
This feature of R allows us to write construct as shown below.
> x <- -5
> y <- if(x > 0) 5 else 6
> y
[1] 6
if…else Ladder
The if…else ladder (if…else…if) statement allows you execute a block of code among more than 2 alternatives
The syntax of if…else statement is:
if ( test_expression1) {
statement1
} else if ( test_expression2) {
statement2
} else if ( test_expression3) {
statement3
} else {
statement4
}
Only one statement will get executed depending upon the test_expressions.
Example of nested if…else
x <- 0
if (x < 0) {
print("Negative number")
} else if (x > 0) {
print("Positive number")
} else
print("Zero")
Output
[1] "Zero"
There is an easier way to use if…else statement specifically for vectors in R programming.
You can use ifelse() function instead; the vector equivalent form of the if…else statement.
Check out these related examples:
-
PREVIOUS
R Operator Precedence and Associativity -
NEXT
R ifelse() Function