Control Structures in R
Control Structures in R
In order to control the execution of the expressions flow in R, we make use of the control
structures. These control structures are also called as loops in R. There are eight types of
control structures in R:
if
if-else
for
nested loops
while
repeat and break
next
return
If Statement
x <- “Intellipaat”
if(is.character(x)) {
print("X is a Character")
}
Else Statement
Switch Statement
x <- switch(
3,
"Intellipaat",
"R",
"Tutorial",
"Beginners"
)
print(x)
Repeat Loop
A repeat loop is one of the control statements in R programming that executes a set
of statements in a loop until the exit condition specified in the loop, evaluates to
TRUE. It works as a infinite loop.
The basic syntax for a repeat loop is given below:
repeat {
statements
if(exit_condition) {
break
}
Repeat
If(num>0)
break;
while (Boolean_expression) {
statement
}
v <-9
while(v>5){
print(v)
v = v-1
}
For Loop
For loop is one of the control statements in R programming that executes a set of
statements in a loop for a specific number of times, as per the vector provided to it.
The basic syntax of a for loop is given below
for (value in vector) {
statements
}
v <- c(1:5)
for (i in v) {
print(i)
}
Loop-control Statements
Loop-control statements are part of control statements in R programming that are
used to change the execution of a loop from its normal execution sequence.
There are two loop-control statements in R
Break Statement
Next Statement
where,
R Functions Types
In-built functions
User-defined functions
In-built Functions
User-defined Functions
Recursive Functions
Recursive means a function calling itself. The R Programming language introduced a
new technique called Recursion for elegant and straightforward coding.
It means, 6! = 6 * 5 * 4 * 3 * 2 * 1
We can achieve the same in R programming using For Loop, While Loop, etc. But if
you observe the above pattern, its behavior is repetitive, which means recursive. So
instead of writing the loops (costly), we can write the recursive functions R
Programming as it will utilize the memory in the form of stack. It will not contain
another space except the fixed size stack.
# Example
if(number == 0 || number == 1) {
return (1)
} else {
fact(6)