ComeçarComece de graça

sapply() vs. lapply()

lapply() is great, but sometimes you might want the returned data in a nicer form than a list. For instance, with the sharpe ratio, wouldn't it be great if the returned sharpe ratios were in a vector rather than a list? Further analysis would likely be easier!

For this, you might want to consider sapply(), or simplify apply. It performs exactly like lapply(), but will attempt to simplify the output if it can. The basic syntax is the same, with a few additional arguments:

sapply(X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE)

These additional optional arguments let you specify if you want sapply() to try and simplify the output, and if you want it to use the names of the object in the output.

In the exercise, you will recalculate sharpe ratios using sapply() to simplify the output. stock_return and the sharpe function are available for you.

Este exercício faz parte do curso

Intermediate R for Finance

Ver curso

Instruções do exercício

  • First, use lapply() on stock_return to get the sharpe ratio again.
  • Now, use sapply() on stock_return to see the simplified sharpe ratio output.
  • Use sapply() on stock_return to get the sharpe ratio with the arguments simplify = FALSE and USE.NAMES = FALSE. This is equivalent to lapply()!

Exercício interativo prático

Experimente este exercício completando este código de exemplo.

# lapply() on stock_return
___

# sapply() on stock_return
___

# sapply() on stock_return with optional arguments
___
Editar e executar o código