Rainbow Deals - hours only!Up to 80% off on all courses and bundles.-Close
The lapply() function
5. lapply() and your own functions
Other apply() functions
The split-apply-combine pattern


Great! Of course, you can also create your own function and pass it in to the lapply() function.

Let's say you want to count the number of one-hour slots in which more than 100 bracelets were sold:

more_than_100 <- function(vector){
  sum(vector > 100)

This function can be applied to each member like this:

lapply(sales, more_than_100)

After executing the above line, R returns the following:

> lapply(sales, more_than_100)
[1] 24
[1] 24
[1] 24
[1] 0
[1] 9
[1] 15
[1] 24

As you can see, for the first three days of Monday through Wednesday, more than 100 bracelets were sold each hour. But on Thursday, the goal of more than 100 bracelets in an hour was not achieved.


For each day of the week, we would like to see the morning sales (between 6 a.m. and 11 a.m.). This data is stored between indexes 7 and 12, inclusive (because the sales for a given day start at midnight, 12 a.m.).

Create a function named morning_sales that takes one argument named vector and returns the sum of the elements from positions 7 to 12, inclusive.