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 = ___)