Next, you break it
A possible solution to the previous exercise has been provided for you. The code loops over the linkedin
vector and prints out different messages depending on the values of li
.
In this exercise, you will use the break
and next
statements:
- The
break
statement abandons the active loop: the remaining code in the loop is skipped and the loop is not iterated over anymore. - The
next
statement skips the remainder of the code in the loop, but continues the iteration.
This exercise is part of the course
Intermediate R
Exercise instructions
Extend the for
loop with two new, separate if
tests as follows:
- If the vector element's value exceeds 16, print out "This is ridiculous, I'm outta here!" and have R abandon the
for
loop (break
). - If the value is lower than 5, print out "This is too embarrassing!" and fast-forward to the next iteration (
next
).
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# The linkedin vector has already been defined for you
linkedin <- c(16, 9, 13, 5, 2, 17, 14)
# Adapt/extend the for loop
for (li in linkedin) {
if (li > 10) {
print("You're popular!")
} else {
print("Be more visible!")
}
# Add if statement with break
# Add if statement with next
print(li)
}