Get Started

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”

View Course

Exercise instructions

  • Fill in the nested if statement to check if shares is greater than or equal to 1 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 {
        ___
    }
}
Edit and Run Code