Loop over a vector
Last, but not least, in our discussion of loops is the for loop. When you know how many times you want to repeat an action, a for loop is a good option. The idea of the for loop is that you are stepping through a sequence, one at a time, and performing an action at each step along the way. That sequence is commonly a vector of numbers (such as the sequence from 1:10
), but could also be numbers that are not in any order like c(2, 5, 4, 6)
, or even a sequence of characters!
for (value in sequence) {
code
}
In words this is saying, "for each value in my sequence, run this code." Examples could be, "for each row of my data frame, print column 1", or "for each word in my sentence, check if that word is DataCamp."
Let's try an example! First, you will create a loop that prints out the values in a sequence from 1 to 10. Then, you will modify that loop to also sum the values from 1 to 10, where at each iteration the next value in the sequence is added to the running sum.
A vector seq
and a variable sum
have been defined for you.
This is a part of the course
“Intermediate R for Finance”
Exercise instructions
- Fill in the for loop, using
seq
as your sequence. Print outvalue
during each iteration. - Use the loop to sum the numbers in
seq
. Each iteration,value
should be added tosum
, thensum
is printed out.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Sequence
seq <- c(1:10)
# Print loop
for (value in ___) {
print(___)
}
# A sum variable
sum <- 0
# Sum loop
for (value in seq) {
sum <- ___ + ___
print(___)
}