We’ve seen how to control which lines of code are ran with conditionals.
Today, we’ll review how to control repetition of lines of code.
Suppose you have a vector with thousands of integers.
You’d like to find the indices of your favorite number, but you can’t use vectorization or loops.
Recursive solutions are often elegant but also difficult to write.1
For this reason, we introduce an alternate approach: iterative solutions.
Iterative solutions contain a block of code that is directly repeated.
We’ve seen a series of statements (if, else, else if) for conditionally executing bodies of code.
We’ll now introduce another series of statements for repeatedly executing bodies of code (looping).
while: execute its body while a condition holds true.
for: execute its body for each object in a specified vector.
repeat: execute its body repeatedly and unconditionally.
while StatementThe while statement is similar in form and behavior to if:
while(LOGICAL) <body>
where <body> is executed while LOGICAL returns TRUE,
as if an if statement that repeats until LOGICAL == FALSE,
if(LOGICAL) <body> if(LOGICAL) <body> ...
while Statement: Example 1Here we count up from from to to, printing the numbers along the way.
while Statement: Example 2Using a similar idea, we can recreate a (simplified) version of seq.
For which input will this function not work?
whileLet’s rewrite num_indices with a while loop.
for Statementfor (<variable> in <vector>) <body>
where <body> is executed once for each object in <vector>.
for Makes CopiesWe cannot modify <vector> by reassigning <variable>.
for Statement VariablesYou are free to name <variable> anything.
i for index or n for number) may be sufficient.forLet’s rewrite num_indices with a for loop.
seq_along()Notice that to get a vector of the indices, we wrote 1:length(vec).
The idiomatic way of doing this is with the seq_along() function:
repeat Statementrepeat <body>
where <body> is executed repeatedly and unconditionally until a break statement is encountered1.
break statement?The break statement can be used in any loop (for, while, repeat) to immediately stop its execution.
The last iteration of the loop’s body is not completed. The body of the loop is immediately exited on encountering break.
repeat Statement: Exampleprint_hesitantly <- function(sentence, times) {
cutoff <- sample(1:nchar(sentence))
to_repeat <- substr(sentence, 1, cutoff)
repeat {
cat(to_repeat, '...'); times <- times - 1
if (times <= 0) {
break
}
}
cat(substr(sentence, cutoff + 1, nchar(sentence)))
}
print_hesitantly("I like you", 5)I like ...I like ...I like ...I like ...I like ... you
repeatThe favorite number problem. Notice the similarity to the while solution.