lapply() on a data frame
If, instead of a list, you had a data frame of stock returns, could you still use lapply()? Yes! Perhaps surprisingly, data frames are actually lists under the hood, and an lapply() call would apply the function to each column of the data frame.
df
a b
1 1 4
2 2 6
class(df)
[1] "data.frame"
lapply(df, FUN = sum)
$a
[1] 3
$b
[1] 10
lapply() summed each column in the data frame, but still follows its convention of always returning a list. A data frame of daily stock returns as decimals called stock_return has been provided.
Deze oefening maakt deel uit van de cursus
Intermediate R for Finance
Oefeninstructies
- Print
stock_returnto see the data frame. - Use
lapply()to get the average (mean) of each column. - Create a function for the sharpe ratio. It should take the average of the returns, subtract the risk free rate (
.03%) from it, and then divide by the standard deviation of the returns. - Use
lapply()to calculate the sharpe ratio of each column.
Praktische interactieve oefening
Probeer deze oefening eens door deze voorbeeldcode in te vullen.
# Print stock_return
___
# lapply to get the average returns
___
# Sharpe ratio
sharpe <- function(returns) {
(___ - .0003) / ___
}
# lapply to get the sharpe ratio
___