Break and next
To finish your lesson on loops, let's return to the concept of break, and the related concept of next. Just like with repeat and while loops, you can break out of a for loop completely by using the break statement. Additionally, if you just want to skip the current iteration, and continue the loop, you can use the next statement. This can be useful if your loop encounters an error, but you don't want it to break everything.
for (value in sequence) {
if(next_condition) {
next
}
code
if(breaking_condition) {
break
}
}
You don't have to use both break and next at the same time, this simply shows the general structure of using them.
The point of using next at the beginning, before the code runs, is to check for a problem before it happens.
This is a part of the course
“Intermediate R for Finance”
Exercise instructions
The apple
vector is in your workspace.
- Print out
apple
. You have some missing values! - Fill in the blanks in the loop to do the following:
- Check if
value
isNA
. If so, go to the next iteration. - Check if
value
is above117
. If so, break and sell! - Else print
"Nothing to do here!"
.
- Check if
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Print apple
___
# Loop through apple. Next if NA. Break if above 117.
for (value in apple) {
if(is.na(___)) {
print("Skipping NA")
next
}
if(value > ___) {
print("Time to sell!")
break
} else {
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.
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 nextWhat is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.