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

Instruction

Great work! To use the split-apply-combine pattern you can use:

  • tapply() over the column x.
  • split() over x and sapply().
  • split() over x, lapply(), and unlist().

Let's practice the split-apply-combine pattern. Alex, the guy who works as an administrator on the Smartcom website, wants to go on a trip. He has several destinations in mind: Croatia, the USA, and the Netherlands. Alex has calculated his expenses for each trip, splitting them into the following groups: plane ticket, accommodations for 7 days, and daily expenses.

This is what the alex_trips data set looks like:

country cost_type price
1 Croatia plane_ticket 300
2 USA plane_ticket 800
3 Netherlands plane_ticket 600
4 Croatia accommodation 250
5 USA accommodation 650
6 Netherlands accommodation 850
7 Croatia daily_expenses 400
8 USA daily_expenses 700
9 Netherlands daily_expenses 800

Exercise

What are the most expensive and the cheapest trip that Alex is considering? Let's find out! Follow these steps:

  1. Create a list of prices (alex_trips_list) grouped by country.
  2. Calculate Alex's total expenses for each country. Use sapply() to get the result in vector form.