LoslegenKostenlos loslegen

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.

Diese Übung ist Teil des Kurses

Intermediate R for Finance

Kurs anzeigen

Anleitung zur Übung

  • Print stock_return.
  • Fill in the lapply() function to apply percent_to_decimal() to each element in stock_return.

Interaktive Übung

Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.

# Print stock_return
___

# lapply to change percents to decimal
lapply(___, FUN = ___)
Code bearbeiten und ausführen