Control Structures

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

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

https://en.wikipedia.org/wiki/Control_flow

https://www.learnbyexample.org/r-for-loop/