Can you If inside an If?
Sometimes it makes sense to have nested if statements to add even more control. In the following exercise, you will add an if statement that checks if you are holding a share of the Microsoft stock before you attempt to sell it.
Here is the structure of nested if statements, it should look somewhat familiar:
if(condition1) {
if(condition2) {
code if both pass
} else {
code if 1 passes, 2 fails
}
} else {
code if 1 fails
}
The variables, micr
and shares
, have been created for you.
This is a part of the course
“Intermediate R for Finance”
Exercise instructions
- Fill in the nested if statement to check if
shares
is greater than or equal to1
before you decide to sell. - If this is true, then print
"Sell!"
. - Else, print
"Not enough shares to sell!"
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
micr <- 105.67
shares <- 1
# Fill in the blanks
if( micr < 55 ) {
print("Buy!")
} else if( micr >= 55 & micr < 75 ) {
print("Do nothing!")
} else {
if( ___ ) {
___
} else {
___
}
}
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.
Imagine you own stock in a company. If the stock goes above a certain price, you might want to sell. If the stock drops below a certain price, you might want to buy it while it's cheap! This kind of thinking can be implemented using operators and if statements. In this chapter, you will learn all about them, and create a program that tells you to buy or sell a stock.
Exercise 1: Relational operatorsExercise 2: Relational practiceExercise 3: Vectorized operationsExercise 4: Logical operatorsExercise 5: And / OrExercise 6: Not!Exercise 7: Logicals and subset()Exercise 8: All together now!Exercise 9: If statementsExercise 10: If thisExercise 11: If this, Else thatExercise 12: If this, Else If that, Else that other thingExercise 13: Can you If inside an If?Exercise 14: ifelse()What is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.