Get startedGet started for free

Repeat, repeat, repeat

Loops are a core concept in programming. They are used in almost every language. In R, there is another way of performing repeated actions using apply functions, but we will save those until chapter 5. For now, let's look at the repeat loop!

This is the simplest loop. You use repeat, and inside the curly braces perform some action. You must specify when you want to break out of the loop. Otherwise it runs for eternity!

repeat {
    code
    if(condition) {
        break
    }
}

Do not do the following. This is an infinite loop! In words, you are telling R to repeat your code for eternity.

repeat {
    code
}

This exercise is part of the course

Intermediate R for Finance

View Course

Exercise instructions

  • A repeat loop has been created for you. Run the script and see what happens.
  • Change the condition in the if statement to break when stock_price is below 125.
  • Update the stock price value in the print statement to be consistent with the change.
  • Rerun the script again. Then press Submit Answer.

Hands-on interactive exercise

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

# Stock price
stock_price <- 126.34

repeat {
  # New stock price
  stock_price <- stock_price * runif(1, .985, 1.01)
  print(stock_price)
  
  # Check
  if(stock_price < 124.5) {
    print("Stock price is below 124.5! Buy it while it's cheap!")
    break
  }
}
Edit and Run Code