Get startedGet started for free

And / Or

You might want to check multiple relational conditions at once. What if you wanted to know if Apple stock was above 120, but below 121? Simple relational operators are not enough! For multiple conditions, you need the And operator &, and the Or operator |.

  • & (And): An intersection. a & b is true only if both a and b are true.
  • | (Or): A union. a | b is true if either a or b is true.
apple <- c(120.00, 120.08, 119.97, 121.88)

# Both conditions must hold
(apple > 120) & (apple < 121)
[1] FALSE  TRUE FALSE FALSE

# Only one condition has to hold
(apple <= 120) | (apple > 121)
[1]  TRUE FALSE  TRUE  TRUE

The stocks data frame is available for you to use.

This exercise is part of the course

Intermediate R for Finance

View Course

Exercise instructions

  • When is ibm between 171 and 176? Add the logical vector to stocks as ibm_buy_range.
  • Check if panera drops below 213.20 or rises above 216.50, then add it to stocks as the column panera_spike.
  • Suppose you are interested in dates after 2017-01-21 but before 2017-01-25, exclusive. Use as.Date() and & for this. Add the result to stocks as good_dates.
  • Print stocks.

Hands-on interactive exercise

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

# IBM buy range	
___

# Panera spikes	
___

# Date range
___

# Print stocks	
___
Edit and Run Code