Use the “if() {}” function to create an if-then statement in R. 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
[1] "data is False!"
[1] "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 its outcome.
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
[1] "You have hit the century"
That’s it for the If-then statement in R.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language.