Exercise

Anonymous functions

As a last exercise, you'll learn about a concept called anonymous functions. So far, when calling an apply function like vapply(), you have been passing in named functions to FUN. Doesn't it seem like a waste to have to create a function just for that specific vapply() call? Instead, you can use anonymous functions!

Named function:

percent_to_decimal <- function(percent) {
    percent / 100
}

Anonymous function:

function(percent) { percent / 100 }

As you can see, anonymous functions are basically functions that aren't assigned a name. To use them in vapply() you might do:

vapply(stock_return, FUN = function(percent) { percent / 100 }, 
       FUN.VALUE = numeric(2))
            apple          ibm
[1,]  0.003744634  0.001251408
[2,] -0.007188353 -0.001124859

stock_return is available to use.

Instructions

100 XP
  • Use vapply() to apply an anonymous function that returns a vector of the max() and min() (in that order) of each column of stock_return.