ComenzarEmpieza gratis

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.

Este ejercicio forma parte del curso

Intermediate R for Finance

Ver curso

Instrucciones del ejercicio

  • Use ifelse() to test if micr is above 60 but below 62. When true, return a 1 and when false return a 0. Add the result to stocks as the column, micr_buy.
  • Use ifelse() to test if apple is greater than 117. The returned value should be the date column if TRUE, and NA 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 the class() of "Date".
  • Print stocks again.

Ejercicio interactivo práctico

Prueba este ejercicio y completa el código de muestra.

# 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
___
Editar y ejecutar código