General Introduction to if Statement in R
In R Language, the if
statement(s) is a conditional control used for making a decision. The if
statement in R is used to run the block of statements when a certain condition is met. Therefore, if statements are also called conditional statements.
if Statement in R
An if
statement consists of a boolean expression followed by one or more statements. The basic syntax for creating a if
statement is
if ( boolean expression ) { # statements # these statements will execute only if the boolean expression is true }
The code inside the brackets of the if
statement will be executed if the boolean expression in parenthesis evaluates to be true. For example,
x <- 3.0L if ( is.integer(x) ){ print("x is an integer") }
if-else Statement
An if
statement can be followed by an optional else
statement. The else
statement executes only when the boolean expression in the parenthesis of the if statement evaluates to false. The basic syntax of a if-else
statement is
if (boolean expression){ # statement(s) will execute if the boolean expression is true } else{ # statemenet(s) will execute if boolean expression is false }
For example,
x <- 31 if ( x %% 2 == 0 ){ print("X is even") }else{ print("X is odd") }
if-else-if Statement
An if
statement can be followed by an optional else-if-else
statement, which is very useful for testing various conditions using a single if-else-if
statement. The basic syntax for creating an if-else-if
is
if ( boolean expression-1 ){ # statements execute when the boolean expression-1 is true } else if ( boolean expression-2 ) { # statements execute when the boolean expression-2 is true } else if ( boolean expression-3 ){ # statements execute when the boolean expression-3 is true } else { # statements execute when none of the above condition is true }
For example,
# Consider durbin watson statistics d = -2 if (d == 2){ print("no autocorrelation") } else if (d > 0 & d < 2){ print("Positive autocorrelation") } else if (d > 2){ print("successive error terms are negatively correlated") } else { print("d is less than 0") }
The value of $d (d=-2)$ will be compared with the expression’s result in the parenthesis of if
or else if
statement. From all of the if
or else if
statements only one statement will be true. In the example, $d=-2$ does not match with any of the if
(or else if
statement), therefore, the last statement (that is else
statement) will be executed.