Control Statements in R

As a programming language, R has functions for loops and control flows. Looping, in particular, is a powerful extension that allows you to repeat or automate certain tasks. Further, looping, when combined with R’s indexing functions provides an excellent way to perform the same set of analyses on different subsets of a dataset.

There are three main commands to control your code: for(), which repeats a set of commands a number of times,while(), which repeats a set of commands a numbe of times, and while(), which repeats a set of commands until a condition is reached. Finally, the if() function allows different code to be run dependent on the outcome of a test (e.g. if the value of some variable goes over a threshold.

For loops

The format of the for() function is: for (counter in start:stop). The counter (or iterator) is an integer which is increased by one each time the loop runs. ‘start’ gives the initial value of the counter, and ‘stop’ gives the final value. The commands which are to be run within the loop are then enclosed within curly brackets.{…}.

The following is an example of a very single loop.

for (i in 1:12) {
  print(i)
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
## [1] 6
## [1] 7
## [1] 8
## [1] 9
## [1] 10
## [1] 11
## [1] 12

The loop starts at 1 and runs to 12, and the iterator i is printed then increased by one at each step.

while loops

while loops allow a program to continue to run until some value has been reached. These are quite widely used in optimization, where we want to keep reducing the error of a model until it no longer changes by more than some small amount.

count <- 1
while (count <= 5) {
  print(count)
  count <- count + 1
}

In this loop:

If statements

If statements in R is used to execute a block of code based on a condition. It allows your program to make decisions and run specific code only when certain conditions are met.

number <- 5 
if (number > 0) {
   print ("The number is positive.")
}

In this statement:


More resources

Additional resources and information regarding control statements in are can be found in Geeks for Geeks, Bookdown, and C#Corner.