Get Started

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.

This is a part of the course

“Intermediate R for Finance”

View Course

Exercise instructions

  • Print stock_return to 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.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Print stock_return
___

# lapply to get the average returns
___

# Sharpe ratio
sharpe <- function(returns) {
    (___ - .0003) / ___
}

# lapply to get the sharpe ratio
___

This exercise is part of the course

Intermediate R for Finance

BeginnerSkill Level
4.7+
11 reviews

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 frame
Exercise 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: Congratulations

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free