R Condition Control

In programming languages, there are many instances where we might want to control the flow of code execution or we might want to execute some code on some specific condition. We can also achieve such condition control in R with If and Switch flow control statement.

There are the two condition control structures: If and Switch.

If Statement

The if statement is the most commonly used in conditional control statements.
These are the conditions where we can use the If statement-

To Check Single Expression

Syntax of the if statement

if(condition) { 
 statements
} 

If the condition in the 'if statement' is true, then the statements enclosed within the curly braces are executed.

Example

> x <- 10
> if(x > 0){
+ print("x is positive number")
+ }
[1] "x is positive number"
> 

Execute one of two statements based on the condition

In this, if the expression within the if statement is true, then the statements within the if are executed otherwise the statements within the else are executed.

Syntax of the if..else statement

if(condition) { 
 Statement1 
} 
else { 
  Statement2 
}

If the expression in the if statement is true, then statement1 is executed , If the expression in if statement is false, then statement2 is executed.

Example

> x <- 10
> if(x > 0){
+ print("x is positive number")
+ } else {
+ print("x is negative number")
+ }
[1] "x is positive number"

Multiple Conditions

If ...elseif.... else statements are used for more than one conditions.

if(condition1) { 
    Statement1; 
} 
elseif(condition2) { 
    Statement2; 
}
else{ 
    Statement3; 
}

Example

> x <- 10
> if(x > 0){
+ print("x is positive number")
+ } else if(x < 0){
+ print("x is negtive number")
+ } else {
+ print("x is zero")
+ }
[1] "x is positive number"

Switch

If there is need to match the value from many different cases and execute the statements within the matched case. Switch statement executes line by line and read all the cases. If the case value is matched with a value passed in the switch expression, then statement within the matched case is executed. We can write break to terminate the execution of further statements, if match case is found.

switch(expression, case1, case2, case3,......,caseN)

Example

> switch(3, "Cat","Dog","Elephant","Fox")
[1] "Elephant"




Read more articles


General Knowledge



Learn Popular Language