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.
This exercise is part of the course
Intermediate R for Finance
Exercise instructions
- Use
vapply()
to apply an anonymous function that returns a vector of themax()
andmin()
(in that order) of each column ofstock_return
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Max and min
vapply(___,
FUN = function(x) { ___ },
FUN.VALUE = ___)