if and if-else Statements in R


Control statements are expressions used to control the execution and flow of the program based on the conditions provided in the statements.These statements are used to make a decision after assessing the variable. 

if condition

This control structure checks the expression provided in parenthesis is true or not. If true, the execution of the statements in braces {} continues.

Syntax:
if(expression)
        { statements .... .... 
        }
Example:
x <- 100
if(x > 10){
print(paste(x, "is greater than 10"))
}

output
[1] "100 is greater than 10"

if-else condition

It is similar to if condition but when the test expression in if condition fails, then statements in else condition are executed.

Syntax:
            if(expression)
                            { statements .... .... }
             else{ statements .... .... }

Example:
x <- 5
# Check value is less than or greater than 10
if(x > 10)
{
print(paste(x, "is greater than 10"))
}else{
print(paste(x, "is less than 10"))
}
output
[1] "5 is less than 10"


if-else-if ladder

It is similar to if-else statement, here the only difference is that an if statement is attached to else. If the condition provided to if block is true then the statement within the if block gets executed, else-if the another condition provided is checked and if true then the statement within the block gets executed.

Syntax:

if(condition 1 is true) {

execute this statement

} else if(condition 2 is true) {

execute this statement

} else {

execute this statement

}
example:
# R if-else-if ladder Example
a <- 67
b <- 76
c <- 99


if(a > b && b > c)
{
print("condition a > b > c is TRUE")
} else if(a < b && b > c)
{
print("condition a < b > c is TRUE")
} else if(a < b && b < c)
{
print("condition a < b < c is TRUE")
}
output:
[1] "condition a < b < c is TRUE"


Nested if-else statement


When we have an if-else block as an statement within an if block or optionally within an else block, then it is called as nested if else statement. When an if condition is true then following child if condition is validated and if the condition is wrong else statement is executed, this happens within parent if condition. If parent if condition is false then else block is executed with also may contain child if else statement.

Syntax:

if(parent condition is true) {
if( child condition 1 is true) {
execute this statement
} else {
execute this statement
}
} else {
if(child condition 2 is true) {
execute this statement
} else {
execute this statement
}
}

example:
# R Nested if else statement Example
a <- 10
b <- 11


if(a == 10)
{
if(b == 10)
{
print("a:10 b:10")
} else
{
print("a:10 b:11")
}
} else
{
if(b == 11)
{
print("a:11 b:11")
} else
{
print("a:11 b:10")
}
}

output:
[1] "a:10 b:11"

Comments

Popular posts from this blog

Programming in R - Dr Binu V P

Introduction

R Data Types