0
0
R Programmingprogramming~30 mins

Apply family vs loops in R Programming - Hands-On Comparison

Choose your learning style9 modes available
Apply Family Functions vs Loops in R
📖 Scenario: You work in a small bakery that tracks daily sales of different bread types. You want to calculate the total sales for each bread type over a week.
🎯 Goal: Build a program that calculates total weekly sales for each bread type using both a for loop and the lapply function, then compare the results.
📋 What You'll Learn
Create a list called daily_sales with 3 named numeric vectors representing sales for 'Sourdough', 'Baguette', and 'Rye' over 7 days
Create a numeric vector called total_sales_loop to store total sales for each bread type using a for loop
Create a numeric vector called total_sales_apply to store total sales for each bread type using lapply
Print both total_sales_loop and total_sales_apply to compare results
💡 Why This Matters
🌍 Real World
Bakeries and small shops often track daily sales data and need to summarize totals quickly to understand performance.
💼 Career
Knowing how to use loops and apply functions in R is essential for data analysts and anyone working with data summaries in real-world business settings.
Progress0 / 4 steps
1
Create the daily sales data
Create a list called daily_sales with these exact entries: Sourdough as c(10, 12, 11, 9, 13, 10, 14), Baguette as c(8, 7, 9, 6, 7, 8, 7), and Rye as c(5, 6, 5, 7, 6, 5, 6).
R Programming
Need a hint?

Use the list() function with named vectors for each bread type.

2
Set up a vector to store totals from the loop
Create a numeric vector called total_sales_loop with length 3 and names matching the names of daily_sales.
R Programming
Need a hint?

Use numeric() to create a vector of zeros and names() to assign names.

3
Calculate totals using a for loop and lapply
Use a for loop with variable bread to iterate over names(daily_sales) and sum each bread's sales into total_sales_loop[bread]. Then create total_sales_apply by applying sum to each element of daily_sales using lapply and unlist the result.
R Programming
Need a hint?

Use for (bread in names(daily_sales)) and sum() inside the loop. Use lapply(daily_sales, sum) and unlist() for the apply method.

4
Print the total sales vectors
Print total_sales_loop and total_sales_apply to display the total weekly sales for each bread type.
R Programming
Need a hint?

Use print(total_sales_loop) and print(total_sales_apply) to show the results.