FUN arguments
Often, the function that you want to apply will have other optional arguments that you may want to tweak. Consider the percent_to_decimal()
function that allows the user to specify the number of decimal places.
percent_to_decimal(5.4, digits = 3)
[1] 0.054
In the call to lapply()
you can specify the named optional arguments after the FUN argument, and they will get passed to the function that you are applying.
my_list
$a
[1] 2.444 3.500
$b
[1] 1.100 2.678 3.450
lapply(my_list, FUN = percent_to_decimal, digits = 4)
$a
[1] 0.0244 0.0350
$b
[1] 0.0110 0.0268 0.0345
In the exercise, you will extend the capability of your sharpe ratio function to allow the user to input the risk free rate as an argument, and then use this with lapply()
. A data frame of daily stock returns as decimals called stock_return
is available.
This is a part of the course
“Intermediate R for Finance”
Exercise instructions
- Extend
sharpe
to allow the input of the risk free rate as an optional argument. The default should be set at.0003
. - Use
lapply()
onstock_return
to find the sharpe ratio if the risk free rate is.0004
. - Use
lapply()
onstock_return
to find the sharpe ratio if the risk free rate is.0009
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Extend sharpe() to allow optional argument
sharpe <- function(returns, rf = ___) {
(mean(returns) - ___) / sd(returns)
}
# First lapply()
___
# Second lapply()
___
This exercise is part of the course
Intermediate R for Finance
Learn about how dates work in R, and explore the world of if statements, loops, and functions using financial examples.
A popular alternative to loops in R are the apply functions. These are often more readable than loops, and are incredibly useful for scaling the data science workflow to perform a complicated calculation on any number of observations. Learn about them here!
Exercise 1: Why use apply?Exercise 2: lapply() on a listExercise 3: lapply() on a data frameExercise 4: FUN argumentsExercise 5: sapply() - simplify it!Exercise 6: sapply() vs. lapply()Exercise 7: Failing to simplifyExercise 8: vapply() - specify your output!Exercise 9: vapply() vs. sapply()Exercise 10: More vapply()Exercise 11: Anonymous functionsExercise 12: CongratulationsWhat is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.