ifelse()
A powerful function to know about is ifelse(). It creates an if statement in 1 line of code, and more than that, it works on entire vectors!
Suppose you have a vector of stock prices. What if you want to return "Buy!" each time apple > 110, and "Do nothing!", otherwise? A simple if statement would not be enough to solve this problem. However, with ifelse() you can do:
apple
[1] 109.49 109.90 109.11 109.95 111.03 112.12
ifelse(test = apple > 110, yes = "Buy!", no = "Do nothing!")
[1] "Do nothing!" "Do nothing!" "Do nothing!" "Do nothing!" "Buy!"
[6] "Buy!"
ifelse() evaluates the test to get a logical vector, and where the logical vector is TRUE it replaces TRUE with whatever is in yes. Similarly, FALSE is replaced by no.
The stocks data frame is available for you to use.
Cet exercice fait partie du cours
Intermediate R for Finance
Instructions
- Use
ifelse()to test ifmicris above60but below62. When true, return a1and when false return a0. Add the result tostocksas the column,micr_buy. - Use
ifelse()to test ifappleis greater than117. The returned value should be thedatecolumn ifTRUE, andNAotherwise. - Print
stocks.datebecame a numeric!ifelse()strips the date of its attribute before returning it, so it becomes a numeric. - Assigning the
apple_datecolumn theclass()of"Date". - Print
stocksagain.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
# Microsoft test
stocks$micr_buy <- ifelse(test = ___, yes = ___, no = ___)
# Apple test
stocks$apple_date <- ifelse(test = ___, yes = stocks$date, no = NA)
# Print stocks
___
# Change the class() of apple_date.
class(___) <- ___
# Print stocks again
___