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(___)
}
This exercise is part of the course
Intermediate R for Finance
Learn about how dates work in R, and explore the world of if statements, loops, and functions using financial examples.
Chapter 1: Dates
Welcome! Before we go deeper into the world of R, it will be nice to have an understanding of how dates and times are created. This chapter will teach you enough to begin working with dates, but only scratches the surface of what you can do with them.
Exercise 1: An introduction to dates in RExercise 2: What day is it?Exercise 3: From char to dateExercise 4: Many datesExercise 5: Date formats and extractor functionsExercise 6: Date formats (1)Exercise 7: Date formats (2)Exercise 8: Subtraction of datesExercise 9: months() and weekdays() and quarters(), oh my!Chapter 2: If Statements and Operators
Imagine you own stock in a company. If the stock goes above a certain price, you might want to sell. If the stock drops below a certain price, you might want to buy it while it's cheap! This kind of thinking can be implemented using operators and if statements. In this chapter, you will learn all about them, and create a program that tells you to buy or sell a stock.
Exercise 1: Relational operatorsExercise 2: Relational practiceExercise 3: Vectorized operationsExercise 4: Logical operatorsExercise 5: And / OrExercise 6: Not!Exercise 7: Logicals and subset()Exercise 8: All together now!Exercise 9: If statementsExercise 10: If thisExercise 11: If this, Else thatExercise 12: If this, Else If that, Else that other thingExercise 13: Can you If inside an If?Exercise 14: ifelse()Chapter 3: Loops
Loops can be useful for doing the same operation to each element of your data structure. In this chapter you will learn all about repeat, while, and for loops!
Exercise 1: Repeat loopsExercise 2: Repeat, repeat, repeatExercise 3: When to break?Exercise 4: While loopsExercise 5: While with a printExercise 6: While with a plotExercise 7: Break itExercise 8: For loopsExercise 9: Loop over a vectorExercise 10: Loop over data frame rowsExercise 11: Loop over matrix elementsExercise 12: Break and nextChapter 4: Functions
If data structures like data frames and vectors are how you hold your data, functions are how you tell R what to do with your data. In this chapter, you will learn about using built-in functions, creating your own unique functions, and you will finish off with a brief introduction to packages.
Exercise 1: What are functions?Exercise 2: Function help and documentationExercise 3: Optional argumentsExercise 4: Functions in functionsExercise 5: Writing functionsExercise 6: Your first functionExercise 7: Multiple arguments (1)Exercise 8: Multiple arguments (2)Exercise 9: Function scope (1)Exercise 10: Function scope (2)Exercise 11: PackagesExercise 12: tidyquant packageChapter 5: Apply
A popular alternative to loops in R are the apply functions. These are often more readable than loops, and are incredibly useful for scaling the data science workflow to perform a complicated calculation on any number of observations. Learn about them here!
Exercise 1: Why use apply?Exercise 2: lapply() on a listExercise 3: lapply() on a data frameExercise 4: FUN argumentsExercise 5: sapply() - simplify it!Exercise 6: sapply() vs. lapply()Exercise 7: Failing to simplifyExercise 8: vapply() - specify your output!Exercise 9: vapply() vs. sapply()Exercise 10: More vapply()Exercise 11: Anonymous functionsExercise 12: CongratulationsWhat is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.