We have covered the different operations that are available in R. Now, let's look at the control structures used in R. Control structures are the key elements of any programming language.
The control structures commonly used in R are as follows:
if
,else
: This is used to test a condition and execute based on the conditionfor
: This is used to execute a loop for a fixed number of iterationswhile
: This is used to execute a loop while a condition is truerepeat
: This is used to execute a loop indefinitely until seeking a breakbreak
: This is used to break the execution of a loopnext
: This is used to skip an iteration of a loopreturn
: This is used to exit a function
The if
and else
control structures are used to execute based on a condition, where it performs the function when the condition is satisfied and performs an alternate function when the condition fails. (The else clause is not mandatory.) We can implement nested conditions as well in R.
if(<condition>) { ## do something } else { ## do something else }
The for
loop is used to execute repetitive code statements for a definite number of iterations. The for
loops are commonly used to iterate over the element of an object (list, vector, and so on).
for(i in 1:10) { print(i) }
The while
loops are used to evaluate a condition repetitively. If the condition is true, then the expression in the loop body is executed until the condition becomes false.
count<-0 while(count<10) { print(count) count<-count+1 }