Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
The lapply() function
4. The lapply() function
Other apply() functions
The split-apply-combine pattern
Summary

Instruction

Yes, that's correct! If you wanted to calculate the total sales for other days, you would have to type six additional function calls (because there are seven days in a week, one of which we've already analyzed).

Is there an easier way? Of course! You can use the lapply() function (the name is short for "list apply").

lapply() applies a given function to each list or vector member separately. With lapply(), you don't have to repeatedly type the function!

If we wanted to calculate the total number of bracelets sold each day, we would simply use the following:

lapply(sales, sum)

Notice that lapply() takes two arguments: the name of the vector or list, and the name of the function to apply to each member of the vector or list. The function returns a list; each element of this list is the result of applying the given function to the corresponding element of the given vector/list argument:

> lapply(sales, sum)
$monday
[1] 3581
$tuesday
[1] 2684
$wednesday
[1] 2820
$thursday
[1] 2162
$friday
[1] 2364
$saturday
[1] 2443
$sunday
[1] 3115

Exercise

Use lapply() to calculate the max number of pieces sold in one hour, for each day.