Dark Mode On/Off

# IF ELSE, ELSE IF Statement in R

Posted in Programming   LAST UPDATED: SEPTEMBER 22, 2022

In this post, you are going to learn about `if else` and` else if` statements in R. We'll see the Syntax of `If else` statement in R and examples of these conditional statements.

## IF ELSE Statement in R

`If Else` statement in R has a condition. When the condition is true, `if` block is executed and when the condition is false, `else` block is executed.

`else` Block is optional in R.

### Syntax of if else statement in R -

``````if (condition) {
statement1
} else {
statement2
}``````

### Example -

``````x <- -5
if(x > 0){
print("Positive number")
} else {
print("Negative number")
}``````

Negative number

In the above example, the variable `x `holds the value -5. The condition in this conditional statement will be true if `x` is greater than 0 otherwise, it will be false.

In the above example, the value of `x` is -5 therefore, the outcome will be "Negative Number".

## ELSE IF Statement in R

The `else if` statement is used when you have two or more conditions unlike `if else` that has only one condition to check.

### Syntax of ELSE IF statement in R -

``````if (condition1) {
statement1
} else if (condition2) {
statement2
} else if (condition3) {
statement3
} else {
statement4
}``````

### Example -

``````x <- 0
if (x < 0) {
print("Negative number")
} else if (x > 0) {
print("Positive number")
} else
print("It's Zero")``````

It's Zero

In the above example of `else if` statement, the variable `x` holds the value 0. The `if` block will be executed if the condition `x `< 0 is true. The `else if` block will be executed if the condition `x `> 0 is true otherwise the `else` statement will be executed.

The variable `x` is 0 then the output will be "It's Zero".

## Related Questions

### 1). What is the syntax of if-else else if in R?

Syntax -

``````if(boolean_expression 1) {
// Executes when the boolean expression 1 is true.
} else if( boolean_expression 2) {
// Executes when the boolean expression 2 is true.
} else if( boolean_expression 3) {
// Executes when the boolean expression 3 is true.
} else {
// executes when none of the above conditions are true.
}``````

### 2). How do you do two if statements in R?

Use logical operators like `&&` (and), `||` (or) and `!` (not) to join two or more conditions.

### 3). How do you write an If then statement in R?

To run an if-then statement in R, use the if() {} function.

### 4). Does elif work in R?

There is an if-elif else statement in R.