Learning R Control Structures

Understanding how to control program flow in R

Conditional Statements: if-else

In R, you can use the if statement to execute a block of code conditionally based on a logical expression. Optionally, you can use else to specify an alternative block of code to execute when the condition is false.

x <- 10
if (x > 5) {
  print("x is greater than 5")
} else {
  print("x is less than or equal to 5")
}

Loops: for

The for loop is used to iterate over a sequence (e.g., vector or list) and execute a block of code for each element in the sequence.

for (i in 1:5) {
  print(i)
}

Loops: while

The while loop repeatedly executes a block of code as long as a specified condition is true.

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

Loops: repeat

The repeat loop executes a block of code indefinitely until a break statement is encountered.

x <- 1
repeat {
  print(x)
  x <- x + 1
  if (x > 5) {
    break
  }
}

Practice Exercises

Now that you've learned about control structures in R, it's time to practice. Try the following exercises to test your understanding:

  1. Write a loop to print all even numbers from 1 to 10.
  2. Create a vector nums containing numbers from 1 to 5. Write a loop to calculate the sum of all numbers in the vector.
  3. Use a conditional statement to check if a variable grade is greater than 90. If true, print "A", if between 80 and 90 print "B", otherwise print "C".