Chapter_5_Control structures
Chapter_5_Control structures
5. Control Structures
Control structures include two basic types in R like any other programming
language:
Decision structures
Loop structures
If Statement:
If statement includes an Boolean expression followed by one or more
statements. The basic syntax of if statement is mentioned below:
if (test_expression) {
statement
}
If else statement:
If statement is usually followed with optional else statement, which executes
when the Boolean expression is false.
The complete structure (basic syntax) of if-else statement is mentioned below:
if (test_expression) {
statement1
} else {
statement2
}
Switch Statement:
The switch function in R is usually designed to test an expression against
elements of a list. If the value which is used for evaluation from the expression
matches item from the list, the corresponding value is returned.
The complete syntax for creating a switch statement in R is –
switch(expression, case1, case2, case3....)
The demonstration of switch statement is demonstrated below:
> switch(2,"red","yellow","blue")
[1] "yellow"
> switch(1,"red","green","blue")
[1] "red
Note: If the value evaluated is a number, that item of the list is returned.
Looping Structures:
R supports various looping structures which is mentioned below. These
looping structures help us in delivering iterations in systematic manner.
The flowchart of looping structure is mentioned in following snapshot:
Repeat Loop:
Repeat loop in R executes the same code again and again until the loop
condition required is met.
The standard syntax for creating repeat loop in R is mentioned below:
repeat {
commands
if(condition) {
break
}
}
For Loop:
For loop works in the similar way like repeat loop with a sequence of
instructions under certain conditions. The sequence of instructions with
respect to iterations creating a for loop structure. The complete structure of
“for loop execution” is as follows:
for (value in vector) {
statements
}
[1] "E"
[1] "F"
[1] "G"
[1] "H"
[1] "I"
[1] "J"
[1] "K"
[1] "L"
[1] "M"
[1] "N"
[1] "O"
[1] "P"
[1] "Q"
[1] "R"
[1] "S"
[1] "T"
[1] "U"
[1] "V"
[1] "W"
[1] "X"
[1] "Y"
[1] "Z"
In the above example, the alphabets are listed just by specifying the respective
index number. All the uppercase characters are printed in systematic manner.
While loop:
The while loop in R executes the condition with iteration until stop condition is
met. The difference between while loop and for loop differs with respect to the
syntax. The syntax of while loop working is mentioned below:
while (test_expression) {
statement
}
Summary
The user can conditionally execute statements using if and else.
The if-else function is a vector size equivalent of these.
R has three kinds of loops: repeat, while, and for.