Recall & Review
beginner
What is a
for loop used for in R?A
for loop is used to repeat a block of code multiple times, once for each item in a sequence or vector.Click to reveal answer
beginner
Write the basic syntax of a
for loop in R.The basic syntax is:<br>
for (variable in sequence) {
# code to repeat
}Click to reveal answer
beginner
What happens if the sequence in a
for loop is empty?The code inside the loop does not run at all because there are no items to iterate over.
Click to reveal answer
beginner
How can you use a
for loop to print numbers 1 to 5 in R?You can write:<br>
for (i in 1:5) {
print(i)
}Click to reveal answer
intermediate
Can you modify the loop variable inside a
for loop to affect the next iteration?No, modifying the loop variable inside the loop does not change the sequence or affect the next iteration. The loop variable takes the next value from the original sequence each time.
Click to reveal answer
What does the
for loop variable represent in R?✗ Incorrect
The loop variable takes each item from the sequence one at a time during each iteration.
Which of the following is the correct way to loop over numbers 1 to 3 in R?
✗ Incorrect
Option A uses correct R syntax for a for loop. Options B, C, and D are not valid R syntax.
What will this code print?<br>
for (x in c()) { print(x) }✗ Incorrect
The sequence is empty, so the loop body does not run and nothing is printed.
Can you use a
for loop to iterate over characters in a string in R?✗ Incorrect
You can split a string into characters using functions like
strsplit() and then loop over the resulting vector.What is the output of this code?<br>
for (i in 1:3) { i <- i + 10; print(i) }✗ Incorrect
Inside the loop,
i is increased by 10 and printed. The loop variable resets each iteration, so the original sequence is unaffected.Explain how a
for loop works in R and give a simple example.Think about how the loop variable takes each value from the sequence.
You got /4 concepts.
Describe what happens if the sequence in a
for loop is empty.Consider what it means to have nothing to loop over.
You got /3 concepts.