Get startedGet started for free

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.

This exercise is part of the course

Intermediate R for Finance

View Course

Exercise instructions

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

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# lapply() on stock_return
___

# sapply() on stock_return
___

# sapply() on stock_return with optional arguments
___
Edit and Run Code