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.
Este exercício faz parte do curso
Intermediate R for Finance
Instruções do exercício
- 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.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
# Print stock_return
___
# lapply to get the average returns
___
# Sharpe ratio
sharpe <- function(returns) {
(___ - .0003) / ___
}
# lapply to get the sharpe ratio
___