R : Control Flow

Control flow is the order in which we code and have our statement evaluated. These allow us to control flow of execution of script inside the function.

  1. IF Conditional Statement: –

Decision-making is an important part of programming. This can be achieved in R programming using the conditional if…else statement.

Syntax :-  If(condition )action

If conditional statements are TRUE then statement gets executed. But if conditional statement is FALSE, nothing is happen.

Here, Conditional Statement can be logical or numeric vector, but only the first element is taken into consideration.

 

 

 

 

Output;-

 

 

2. IF Conditional Statement with Multiple Actions.

IF Conditional statement is TRUE then its Executed Action 1………….Action n, but if Conditional statement is FALSE then it should display message with out Execution.

Syntax:-

if(condition )

{

Action 1

Action 2

.

.

.

Action n

}

Flow Chart of If condition with multiple Action:-

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  1. If…..else Statement:-

The Else part is optional and is only evaluated if condition is FALSE. It is important to note that else must be in the same line as the closing braces of the if statement.

Syntax:-

if(condition)

{

Action 1

} else

{

Action 2

}

 

Flow Chart of if…..Else Condition:-

 

4.  Nested if ………else Statement: – Placing one if statement inside another if statement is called as Nested If Else Statement in R. The If…Else Statement allows us to print Statement depending upon the Expression result (TRUE or FALSE). Some times we have to check Further when the condition is TRUE.

NOTE:-While using this Nested If….Else concept ,please be careful.

Syntax:-

if (condition 1)

{

Action1

} else if (condition2)

{

Action2

} else if (condition3)

{

Action3

}  else

{

Action4

}

5. Switch Function:- Switch works in two distinct ways depending whether the first argument evaluates to a character or a number.

Syntax :-

{

Vname<-Switch (“String/Variable”

Text1=value1,

Text2=value2,

.

.

Text n-1=value n-1;

)

Example: –

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

About Vijaya Kumar Reddy :

Vijaya Kumar Reddy is MBA in Marketing from Alliance University & B.Tech (Computer Science Engineering). Currently he is working as Analyst Intern with NikhilGuru Consulting Analytics Service LLP (Nikhil Analytics), Bangalore.

Please follow and like us:

1 Trackbacks & Pingbacks

  1. R: Control Flow II

Leave a comment

Your email address will not be published.


*


Subscribe for Data Analytics Edge Newsletter & Share..:-)

error: Content is protected !!