0
0
R Programmingprogramming~30 mins

lapply and sapply in R Programming - Mini Project: Build & Apply

Choose your learning style9 modes available
Using lapply and sapply in R
📖 Scenario: You are working with a list of numeric vectors representing daily sales for different stores. You want to calculate the total sales and average sales for each store using R.
🎯 Goal: Build a small R script that uses lapply and sapply to calculate total and average sales for each store from a list of sales data.
📋 What You'll Learn
Create a list called store_sales with three numeric vectors named store1, store2, and store3 with exact values
Create a variable called sales_threshold set to 100
Use lapply to calculate total sales for each store
Use sapply to calculate average sales for each store
Print the total sales list and average sales vector
💡 Why This Matters
🌍 Real World
Analyzing sales data from multiple stores to quickly calculate totals and averages helps businesses make informed decisions.
💼 Career
Data analysts and R programmers often use <code>lapply</code> and <code>sapply</code> to efficiently process lists of data without writing loops.
Progress0 / 4 steps
1
Create the sales data list
Create a list called store_sales with three numeric vectors: store1 with values c(120, 130, 110), store2 with values c(90, 100, 95), and store3 with values c(150, 160, 170).
R Programming
Need a hint?

Use the list() function to create store_sales with named vectors for each store.

2
Set the sales threshold
Create a variable called sales_threshold and set it to 100.
R Programming
Need a hint?

Just assign the number 100 to the variable sales_threshold.

3
Calculate total and average sales
Use lapply on store_sales with the function sum to calculate total sales for each store and save it in total_sales. Then use sapply on store_sales with the function mean to calculate average sales for each store and save it in average_sales.
R Programming
Need a hint?

Use lapply(store_sales, sum) and sapply(store_sales, mean) to get totals and averages.

4
Print the results
Print the total_sales list and the average_sales vector using two separate print() statements.
R Programming
Need a hint?

Use print(total_sales) and print(average_sales) to show the results.