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”
Exercise instructions
- Fill in the blanks in the for loop to make the following true:
price
should hold that iteration's pricedate
should hold that iteration's date- This time, you want to know if
apple
goes above116
. - If it does, print the
date
andprice
. - If it was below
116
, print out thedate
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!"))
}
}