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.
This exercise is part of the course
Intermediate R for Finance
Exercise instructions
- Use
ifelse()
to test ifmicr
is above60
but below62
. When true, return a1
and when false return a0
. Add the result tostocks
as the column,micr_buy
. - Use
ifelse()
to test ifapple
is greater than117
. The returned value should be thedate
column ifTRUE
, andNA
otherwise. - Print
stocks
.date
became a numeric!ifelse()
strips the date of its attribute before returning it, so it becomes a numeric. - Assigning the
apple_date
column theclass()
of"Date"
. - Print
stocks
again.
Hands-on interactive exercise
Have a go at this exercise by completing this sample 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
___