Control structures allow you to specify the execution of your code. They are extremely useful if you want to run a piece of code multiple times, or if you want to run a piece a code if a certain condition is met. Control strcutures in R contains conditionals, loop statements like any other programming languages.
if (cond) expr
if (cond) expr1 else expr2 Example of if condition:
a<-10
if(a==10)
{
print("hi")
}
## [1] "hi"
Guess what is the output of the code.
#a=10
#if(a>2)
#{
# print("go to hell")
#}
#else
# {
# print("hi")
#}
It’s an error. Because,The right brace before the “else” is used by the R to understand that this is an “if-else” rather than just an “if”.
So, The correct code is:
a=10
if(a>2)
{
print("go to hell")
}else
{
print("hi")
}
## [1] "go to hell"
A loop statement allows us to execute a statement or group of statements multiple times.
A For loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
for (val in sequence) { statement }
for(i in 1:5)
{
print (i^2)
}
## [1] 1
## [1] 4
## [1] 9
## [1] 16
## [1] 25
The placing of one loop inside the body of another loop is called nesting. When you “nest” two loops, the outer loop takes control of the number of complete repetitions of the inner loop. Thus inner loop is executed N- times for every execution of Outer loop.
for(val in sequence) { for(val in sequence) { statment } }
for(i in 1:5)
{
for(j in 2:4)
{
print(i*j)
}
print(paste("we have multiplied",i,"with 2,3 and 4"))
}
## [1] 2
## [1] 3
## [1] 4
## [1] "we have multiplied 1 with 2,3 and 4"
## [1] 4
## [1] 6
## [1] 8
## [1] "we have multiplied 2 with 2,3 and 4"
## [1] 6
## [1] 9
## [1] 12
## [1] "we have multiplied 3 with 2,3 and 4"
## [1] 8
## [1] 12
## [1] 16
## [1] "we have multiplied 4 with 2,3 and 4"
## [1] 10
## [1] 15
## [1] 20
## [1] "we have multiplied 5 with 2,3 and 4"
A break statement is used inside a loop to stop the iterations and flow the control outside of the loop.
for(i in 1:10)
{
if(i==4)
{
break
}
print(i)
}
## [1] 1
## [1] 2
## [1] 3
“next” discontinues a particular iteration and jumps to the next cycle. In fact, it jumps to the evaluation of the condition holding the current loop.
for(i in 1:10)
{
if(i==4)
{
next
}
print(i)
}
## [1] 1
## [1] 2
## [1] 3
## [1] 5
## [1] 6
## [1] 7
## [1] 8
## [1] 9
## [1] 10
In R programming, while loops are used to loop until a specific condition is met.
while (test_expression) { statement }
i=1
while(i<6){
print(i^2)
i=i+1
}
## [1] 1
## [1] 4
## [1] 9
## [1] 16
## [1] 25
The Repeat Function(loop) in R executes a same block of code iteratively until a stop condition is met. The basic syntax for creating a repeat loop in R is
repeat { if(condition) { break } }
repeat loop in R, is similar to while and for loop, it will execute a block of commands repeatedly till break.
sum<-0
repeat{
sum<-sum+1
print(sum)
if(sum>=6){
break
}
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
## [1] 6