Understanding how to control program flow in R
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")
}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)
}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
}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
}
}Now that you've learned about control structures in R, it's time to practice. Try the following exercises to test your understanding:
nums containing numbers from 1 to 5. Write a loop to calculate the sum of all numbers in the vector.grade is greater than 90. If true, print "A", if between 80 and 90 print "B", otherwise print "C".