# If then in R: How to Use If-then Statement in R

Control structures in a programming language are blocks of code that define how other code sections are executed based on particularized parameters. Control structures set a condition and tell R what to do when that condition is met or not met. There is such a control structure called the if-then statement. Let’s see how to use the if-then statement.

## If then in R

To create an if-then statement in R, use the if() {} function. The if() function has two main elements, a logical test in the parentheses and conditional code in curly braces. The code in the curly braces is conditional because it is only evaluated if the logical test contained in the parentheses is TRUE.

### Syntax

``````if (expression) {

...statement

}``````

If the expression is TRUE, the statement gets executed. But if it’s FALSE, nothing happens.

### Example

``````is.if.then <- function(data) {

if (data == TRUE) { print("data was True!") }
if (data == FALSE) { print("data was False!") }

}

is.if.then(FALSE)
is.if.then(TRUE)``````

#### Output

`````` "data is False!"
 "data is True!"``````

If statements tell R to run a line of code if a condition returns TRUE. An if statement is a good choice because it allows us to control which statement is printed depending on which outcome occurs.

## If else statement in R

If-else statement shows the program to run one block of code if the conditional statement is TRUE and a different block of code if it is FALSE.

### Syntax

``````if (condition) {
code block
}
else {
code block
}``````

### Example

``````data_1 <- 101

if (data_1 > 99) {

print("You have hit the century")

} else {

print("You are out in nervous ninty")

}``````

#### Output

`` "You have hit the century"``

That’s it for the If-then statement in R.

Categories R