1. Why use apply?
Most experienced R users prefer to use the family of apply functions over loops in most circumstances. What are these functions, what makes them so special, and why would you use them over loops? That's what this chapter is all about! Let's find out.
2. Meet the apply family
The idea behind apply is that you have a dataset that is somehow split into distinct groups, and you want to apply a function to each of those groups separately, then collect the results. This table lists all of the apply functions that come with base R. That's a big family! Don't worry, in this course, we will only discuss
3. Meet the apply family
three of them, lapply, sapply, and vapply. These three all apply a function over a list, or vector, but return slightly different output. Once you understand the
4. Meet the apply family
thinking behind them, the ability to use the others comes naturally. Why might you want to use these functions instead of a loop? As you will see, they often end up as more readable code, in a compact form.
5. lapply()
First up is lapply, short for list apply. This function takes a list as input, performs a function on each element of that list, and returns a list as output. To see how this works consider the stock_list that was used in the "for loop" video of chapter 3. Here it is again. There, we wanted to print the class of each element in the list, so we created a for loop. We can simplify our code by using lapply. The first argument to lapply is a list that we want to iterate over, and the second argument, FUN, is the function that we want to apply to each element of the list, here, class. Running this code returns a named list containing the classes.
6. Break it down
Understandably, apply functions can be a source of confusion for R users the first time they see them. Let's break down what happened even further using a diagram. First, stock_list is broken apart into its 4 elements, then class is called on each of
7. Break it down
the 4 elements separately and an appropriate class is returned,
8. Break it down
and finally the results are recombined as a list that gets returned.
9. Sharpe ratio
One last thing, in the exercises, you'll be creating a function to calculate sharpe ratio. A sharpe ratio is a measure of risk-adjusted return, calculated by taking the average of your returns, subtracting the risk free rate, and dividing by the standard deviation of returns. The risk free rate is normally the "riskless" return on an asset, such as a treasury bill, for the same time period as your returns. Sharpe ratios are a way of normalizing returns by their risk to be able to more fairly compare returns among multiple stocks. The higher the sharpe ratio, the more return that stock earned per unit of risk.
10. Let's practice!
Alright, now you're ready to get started with the exercises. Good luck!