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.
This exercise is part of the course
Intermediate R for Finance
Exercise instructions
- Print
stocks
. - You want to buy
ibm
when it crosses below175
. Use$
to select theibm
column and a logical operator to know when this happens. Add it tostocks
as the column,ibm_buy
. - If
panera
crosses above213
, sell. Use a logical operator to know when this happens. Add it tostocks
as the column,panera_sell
. - Is
ibm
ever abovepanera
? Add the result tostocks
as the column,ibm_vs_panera
. - Print
stocks
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Print stocks
___
# IBM range
___$___ <-
# Panera range
___$___ <-
# IBM vs Panera
___$___ <-
# Print stocks
___