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! A data frame, stocks, is available for you to use.
Cet exercice fait partie du cours
Intermediate R for Finance
Instructions
- Print
stocks. - You want to buy
ibmwhen it crosses below175. Use$to select theibmcolumn and a logical operator to know when this happens. Add it tostocksas the column,ibm_buy. - If
paneracrosses above213, sell. Use a logical operator to know when this happens. Add it tostocksas the column,panera_sell. - Is
ibmever abovepanera? Add the result tostocksas the column,ibm_vs_panera. - Print
stocks.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
# Print stocks
___
# IBM range
___$___ <-
# Panera range
___$___ <-
# IBM vs Panera
___$___ <-
# Print stocks
___