Control structures are a way to control the flow of execution of a series of R expressions. They allow you to put some “logic” into your R code, rather than just always executing the same R code every time. Control structures allow you to respond to inputs or to features of the data and execute different R expressions accordingly.
Commonly used control structures
- if and else: These structures allow you to test a condition and act on it depending on whether it's true or false.
- for: This structure allows you to execute a loop a fixed number of times.
- while: This structure allows you to execute a loop while a condition is true.
- repeat: This structure allows you to execute an infinite loop (must break out of it to stop).
- break: This statement allows you to break the execution of a loop.
- next: This statement allows you to skip an iteration of a loop.
Control structures are not used in interactive sessions, but rather when writing functions or longer expressions. However, they are a valuable tool to know and understand, even if you don't use them all the time.
Example of an if statement
x <- 5
if (x > 3) {
y <- 10
} else {
y <- 5
}
In this example, the value of `y` will be set to 10 if `x` is greater than 3, and 5 otherwise.
Example of a for loop:
for (i in 1:10) {
print(i)
}
This loop will print the numbers from 1 to 10.
Example of a while loop
x <- 1
while (x <= 10) {
print(x)
x <- x + 1
}
This loop will print the numbers from 1 to 10, one per line.