Session Ready
Exercise

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.

Instructions
100 XP

stock_return and the sharpe function are in your workspace.

  • 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()!