If and Else statement in R

ByHariharan Rajendran

If and Else statement in R

As we know, decision making is an important part for every programming. Almost all the projects make use of this decision making logic and sometimes this is very mandatory as well. Considering this importance, R language has if..else statement.

Probably we are in situation to run the set of codes when the condition is match. In that case, we can use if statement. It is very easy to use in R as like other programming language.

The General flow of “IF” statement,

image

Syntax:

if (test_expression) {
statement
}

Examples:

Example 1

x <- 10
if(x > 0){
print(“Positive number”)
}

 

Example 2

X<-weekdays(Sys.Date())

if(X == “Monday”)

{ print(“Today is Monday”)}

But in a real time scenario, sometimes we need to run the set of codes when the condition is not match. If that is the case then we need to use if and else statement.

image

Syntax:

if (test_expression) {
statement1
} else {
statement2
}

Examples:

Example 1

x <- -1
if(x > 0){
print(“Positive Number”)
} else {
print(“Negative number”)
}

Example 2

X<-weekdays(Sys.Date())

if(X == “Monday”)

{ print(“Today is Monday”)} else

{ print (“Today is not Monday”)}

We can use Nested if and else statement,

image

Syntax:

if ( test_expression1) {
statement1
} else if ( test_expression2) {
statement2
} else if ( test_expression3) {
statement3
} else
statement4

 

Examples:

Example 1

x <- 0
if (x < 0) {
print(“Negative number”)
} else if (x > 0) {
print(“Positive number”)
} else
print(“Zero”)

 

Example 2

X<-weekdays(Sys.Date())

if(X == “Monday”)

{ print(“Today is Monday”)} else if (X==”Tuesday”)

{ print (“Today is Tuesday”)} else if (X==”Wednesday”)

{ print (“Today is Wednesay”)} else if (X==”Thursday”)

{ print (“Today is Thursday”)} else if (X==”Friday”)

{ print (“Today is Friday”)} else if (X==”Saturday”)

{ print (“Today is Saturday”)} else

{print (“Today is Sunday”)}

About the Author

Hariharan Rajendran author

Hariharan Rajendran is a Microsoft Certified Trainer and Lead BI Solutions Consultant with 8+ years of experience in Database, BI and Azure platforms. Hariharan is also an active community leader, speaker & organizer and leads the Microsoft PUG (Power BI User Group – Chennai), SQLPASS Power BI Local Group – Chennai and an active speaker in SQL Server Chennai User Group and also a leader in Data Awareness Program worldwide events. Hariharan also frequently blogs (www.dataap.org/blog), provides virtual training (on ad-hoc basis) on Microsoft Azure, Database Administration, Power BI and database development to worldwide clients/audience.

Comments Are Closed!!!