Get Started

Loop over data frame rows

Imagine that you are interested in the days where the stock price of Apple rises above 117. If it goes above this value, you want to print out the current date and stock price. If you have a stock data frame with a date and apple price column, could you loop over the rows of the data frame to accomplish this? You certainly could!

Before you do so, note that you can get the number of rows in your data frame using nrow(stock). Then, you can create a sequence to loop over from 1:nrow(stock).

for (row in 1:nrow(stock)) {
    price <- stock[row, "apple"]
    date  <- stock[row, "date"]

    if(price > 117) {
        print(paste("On", date, 
                    "the stock price was", price))
    }
}
[1] "On 2016-12-21 the stock price was 117.06"
[1] "On 2016-12-27 the stock price was 117.26"

This incorporates a number of things we have learned so far. If statements, subsetting vectors, conditionals, and loops! Congratulations for learning so much!

The stocks data frame is available for you to use.

This is a part of the course

“Intermediate R for Finance”

View Course

Exercise instructions

  • Fill in the blanks in the for loop to make the following true:
    • price should hold that iteration's price
    • date should hold that iteration's date
    • This time, you want to know if apple goes above 116.
    • If it does, print the date and price.
    • If it was below 116, print out the date and print that it was not an important day!

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Loop over stock rows
for (row in 1:___) {
    price <- stock[___, "___"]
    date  <- stock[___, "___"]

    if(___ > ___) {
        print(paste("On", ___, 
                    "the stock price was", ___))
    } else {
        print(paste("The date:", ___, 
                    "is not an important day!"))
    }
}

This exercise is part of the course

Intermediate R for Finance

BeginnerSkill Level
4.7+
11 reviews

Learn about how dates work in R, and explore the world of if statements, loops, and functions using financial examples.

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 rows
Exercise 11: Loop over matrix elementsExercise 12: Break and next

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free