lapply() on a list
The first function in the apply family that you will learn is lapply()
, which is short for "list apply." When you have a list, and you want to apply the same function to each element of the list, lapply()
is a potential solution that always returns another list. How might this work?
Let's look at a simple example. Suppose you want to find the length of each vector in the following list.
my_list
$a
[1] 2 4 5
$b
[1] 10 14 5 3 4 5 6
# Using lapply
# Note that you don't need parenthesis when calling length
lapply(my_list, FUN = length)
$a
[1] 3
$b
[1] 7
As noted in the video, if at first you thought about looping over each element in the list, and using length()
at each iteration, you aren't wrong. lapply()
is the vectorized version of this kind of loop, and is often preferred (and simpler) in the R world.
A list of daily stock returns as percentages called stock_return
and the percent_to_decimal()
function have been provided.
This is a part of the course
“Intermediate R for Finance”
Exercise instructions
- Print
stock_return
. - Fill in the
lapply()
function to applypercent_to_decimal()
to each element instock_return
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Print stock_return
___
# lapply to change percents to decimal
lapply(___, FUN = ___)
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.