Control structures are blocks that specify directions of flow of control in a program, based on given conditions.
Conditions are usually put inside round brackets ( )
Statement blocks are usually put inside curly brackets { }
The major control structures in R are as follow:
if else: testing a condition for: execute a loop without a condition for a specific number of times
while: execute a loop while a condition is true
repeat: execute an infinite loop
break: break the loop of repeat
next: skip an iteration of a loop once
#If Else
x=1
if (x==1) {print ("x is 1")
}else {
print("x is not 1")}
[1] "x is 1"
#For
for (x in 1:3) {
print (x)
}
[1] 1
[1] 2
[1] 3
#While
x<-0
while (x <4) {
print (x)
x=x+1
}
[1] 0
[1] 1
[1] 2
[1] 3
#Repeat
x=0
repeat {
x<-x+1
if (x>3) {
break
} else {
print(x)
}
}
[1] 1
[1] 2
[1] 3
#Break
for (x in 1:3) {
print (x)
if (x>4) {
break }
}
[1] 1
[1] 2
[1] 3
References