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.
Cet exercice fait partie du cours
Intermediate R for Finance
Instructions
- First, use
lapply()onstock_returnto get the sharpe ratio again. - Now, use
sapply()onstock_returnto see the simplified sharpe ratio output. - Use
sapply()onstock_returnto get the sharpe ratio with the argumentssimplify = FALSEandUSE.NAMES = FALSE. This is equivalent tolapply()!
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
# lapply() on stock_return
___
# sapply() on stock_return
___
# sapply() on stock_return with optional arguments
___