Aan de slagGa gratis aan de slag

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.

Deze oefening maakt deel uit van de cursus

Intermediate R for Finance

Cursus bekijken

Oefeninstructies

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

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

# lapply() on stock_return
___

# sapply() on stock_return
___

# sapply() on stock_return with optional arguments
___
Code bewerken en uitvoeren