Session Ready
Exercise

Vectorized operations

You can extend the concept of relational operators to vectors of any arbitrary length. Compare two vectors using > to get a logical vector back of the same length, holding TRUE when the first is greater than the second, and FALSE otherwise.

apple <- c(120.00, 120.08, 119.97, 121.88)
datacamp  <- c(118.5, 124.21, 125.20, 120.22)

apple > datacamp
[1]  TRUE FALSE FALSE  TRUE

Comparing a vector and a single number works as well. R will recycle the number to be the same length as the vector:

apple > 120
[1] FALSE  TRUE FALSE  TRUE

Imagine how this could be used as a buy/sell signal in stock analysis!

Instructions
100 XP

A data.frame, stocks is in your workspace.

  • Print stocks.
  • You want to buy ibm when it crosses below 175. Use $ to select the ibm column and a logical operator to know when this happens. Add it to stocks as the column, ibm_buy.
  • If panera crosses above 213, sell. Use a logical operator to know when this happens. Add it to stocks as the column, panera_sell.
  • Is ibm ever above panera? Add the result to stocks as the column, ibm_vs_panera.
  • Print stocks.