R - If statement



An if statement consists of a Boolean expression followed by one or more statements.

Syntax

The basic syntax for creating an if statement in R is −

if(boolean_expression) {
   // statement(s) will execute if the boolean expression is true.
}

If the Boolean expression evaluates to be true, then the block of code inside the if statement will be executed. If Boolean expression evaluates to be false, then the first set of code after the end of the if statement (after the closing curly brace) will be executed.

Flow Diagram

R if statement

Example - Check if variable is an Integer

x <- 30L
if(is.integer(x)) {
   print("X is an Integer")
}

When the above code is compiled and executed, it produces the following result −

[1] "X is an Integer"

Example - Check if variable is less than 20

x <- 10L
if(x < 20) {
   print("X is less than 20.")
}

When the above code is compiled and executed, it produces the following result −

[1] "X is less than 20."

Example - Check if variable is greater than 20

x <- 30L
if(x > 20) {
   print("X is greater than 20.")
}

When the above code is compiled and executed, it produces the following result −

[1] "X is greater than 20."
r_decision_making.htm
Advertisements