0
0
R Programmingprogramming~5 mins

For loop in R Programming - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AThe last item in the sequence
BThe total number of items in the sequence
CThe sum of all items in the sequence
DEach item in the sequence one by one
Which of the following is the correct way to loop over numbers 1 to 3 in R?
Afor (i in 1:3) { print(i) }
Bfor i in 1 to 3 { print(i) }
Cfor (i = 1; i <= 3; i++) { print(i) }
Dloop (i in 1:3) { print(i) }
What will this code print?<br>
for (x in c()) { print(x) }
ANothing
BAn error
CNULL
D0
Can you use a for loop to iterate over characters in a string in R?
AYes, directly on the string without conversion
BNo, <code>for</code> loops only work with numbers
CYes, by converting the string to a vector of characters
DNo, you must use <code>while</code> loops for strings
What is the output of this code?<br>
for (i in 1:3) { i <- i + 10; print(i) }
A1, 2, 3
B11, 12, 13
C10, 11, 12
DAn error
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.