1. vapply() - specify your output!
As you just saw, when sapply fails to simplify, it returns a list just like lapply, without any warnings. If you use this inside a function that expects sapply to return a vector, this could wreak havoc and be a pain to debug when it doesn't work. Instead, there is a more robust version of sapply called vapply.
2. vapply()
The robustness comes from an additional argument to vapply called FUN-dot-VALUE. You specify this using a combination of the type of object that should be returned from each vapply call, along with the length of the object. Compactly, this can be written as, for example, character(1), saying that you expect each call to vapply to return a character vector of length 1, or die trying. That's what we would do here with our stock list example. We expect each call to vapply to return a character vector of length 1. If this is not what get's returned, vapply fails and throws an error, which is exactly what you want. If it succeeds, it simplifies the output like sapply. Here, you can see that it worked as expected. In the exercises, you'll see what happens when vapply fails.
3. Anonymous functions
When you work with vapply in the next few examples, another new concept will be introduced known as anonymous functions. Simply put, this is the ability to call a function without explicitly giving it a name. This can be useful with vapply, and a number of other apply functions, because you often have a custom function that you want to apply, but don't have any reason to name it. We could recreate our simple summary function using anonymous functions so that we don't have to explicitly assign it a name. Notice how FUN is now the entire function that used to be called simple_summary. The argument, x, will contain the columns of stock_return, one at a time, to calculate the mean and standard deviation for. Because we expect each call to the function to return a numeric vector of length 2, we specify that in FUN-dot-VALUE.
4. Let's practice!
Great! You're almost done. Finish strong with these last few exercises on vapply and anonymous functions!