



















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




















--- title: "Fall2025-HW1" output: html_document date: "2025-08-05" ---
knitr :: opts_chunk $ set(echo = TRUE )
In this homework, you have been given a dataset that captures comprehensive details of 1,000 sales transactions made in 2024, focusing on various aspects of customer interactions and sales dynamics. It includes a mix of numeric and categorical variables, allowing for in-depth analysis.
Key features of the dataset include:
Customer_ID : Unique identifier for each customer.
Product_Category : Category of the purchased product (e.g., Electronics, Clothing, Home Appliances, etc.).
Purchase_Amount : Total amount spent on each purchase, in dollars.
Purchase_Date : Date of the transaction
Customer_Age : Age of the customer at the time of purchase.
Customer_Gender : Gender of the customer, Male or Female
Store_Location : Location of the store where the purchase occurred.
Satisfaction_Score (response variable) : Numeric response variable indicating the customer's satisfaction level
Note:
For the first homework assignment, we have provided the pre-processing steps for the variables. Kindly ensure you understand and can modify these steps as needed. In future homework and exams, students will be expected to handle data pre- processing independently, and no code will be provided. The only aspect that should remain unchanged is the seed setting to 100.
set.seed( 100 ) #this seed has been set to 100 to ensure results are reproduci
Sales_dataset = read.csv("large_sales_dataset.csv", header =TRUE ) #reads data Sales_dataset $ Product_Category = as.factor(Sales_dataset $ Product_Category) Sales_dataset $ Purchase_Date = as.Date(Sales_dataset $ Purchase_Date, format = "%m/ Sales_dataset $ Customer_Gender = as.factor(Sales_dataset $ Customer_Gender)
In [251…
In [252…
Sales_dataset $ Store_Location = as.factor(Sales_dataset $ Store_Location)
head(Sales_dataset)
#Dividing the dataset into training and testing datasets testRows_sales = sample(nrow(Sales_dataset),0.2 ***** nrow(Sales_dataset)) testData_sales = Sales_dataset[testRows_sales, ] trainData_sales = Sales_dataset[ - testRows_sales, ] row.names(trainData_sales) <- NULL head(trainData_sales)
A data.frame: 6 × 8 Customer_ID Product_Category Purchase_Amount Purchase_Date Customer_Age
1 101 Books 1091.97 2024-07-24 62
2 102 Furniture 869.33 2024-05-04 62
3 102 Books 1592.04 2024-12-29 62
4 102 Electronics 1600.56 2024-12-07 62
5 105 Toys 1030.42 2024-02-20 35
6 105 Books 383.44 2024-11-25 35
A data.frame: 6 × 8 Customer_ID Product_Category Purchase_Amount Purchase_Date Customer_Age
1 102 Furniture 869.33 2024-05-04 62
2 102 Books 1592.04 2024-12-29 62
3 102 Electronics 1600.56 2024-12-07 62
4 105 Toys 1030.42 2024-02-20 35
5 105 Books 383.44 2024-11-25 35
6 109 Electronics 1632.42 2024-04-12 27
For this question, use the "Sales_dataset"
1 a)(4 points) Output a table that has both the average and median Purchase_Amount grouped by Product_Category, Customer_Gender and binned Customer_Age. Show the last 15 rows of the table (excluding rows with NaN/NA/null values)
Note: For age group, use the following bins
A tibble: 6 × 5 Product_Category Customer_Gender Customer_Age Avg_Purchase_Amount Median_Pu
Books Female 0-18 48.
Books Female 19-25 1006.
Books Female 26-35 1062.
Books Female 36-45 1046.
Books Female 46-55 1119.
Books Female 56-65 1046.
Q 1 b)(2 points) Which customer age group has the highest total sum of purchase amount across all categories?
#group customer age group by sum of purchase amount sales_agegroups %>% group_by(Customer_Age) %>% summarise(sum(Purchase_Amount))
A tibble: 7 × 2 Customer_Age sum(Purchase_Amount)
0-18 28610.
19-25 205891.
26-35 279964.
36-45 186526.
46-55 147993.
56-65 104559.
66-75 39056.
The 26 - 35 age group has the highest total sum of purchases.
Q 1 c)(2 points) Which product category has the highest average satisfaction score? For the identified product category, in which store location is it most frequently purchased?
top_category <- Sales_dataset %>% group_by(Product_Category) %>% summarise(avg_satisfaction = mean(Satisfaction_Score))
top_category
In [254…
In [255…
A tibble: 6 × 2 Product_Category avg_satisfaction
Books 7.
Clothing 7.
Electronics 8.
Furniture 7.
Home Appliances 7.
Toys 6.
Electronics has the highest average satisfaction store.
sales_agegroups %>% filter(Product_Category == 'Electronics') %>% group_by(Store_Location) %>% count(Store_Location)
A grouped_df: 13 × 2 Store_Location n
Atlanta 14
Boston 23
Chicago 15
Dallas 15
Denver 5
Houston 14
Las Vegas 11
Los Angeles 12
Miami 21
New York 12
San Diego 16
San Francisco 9
Seattle 9
Electronics are most frequently purchased in Boston.
In [256…
Q 2 b)(5 points) Calculate the rolling means of average monthly sales (calculated in 2 a) using a 3 month window. Use the center alignment to calculate the rolling means.
Now again plot the monthly average sales of each product category along with the rolling means. Create one plot for each product category showing both average sales and rolling means sales.
i) What difference do you observe? How are the rolling means beneficial as compared to simple averages?
library(zoo)
monthly_avg_sales $ rolling_mean <- rollmean(monthly_avg_sales $ avg_sales, k = 3 , align = "center", fill =NA ) head(monthly_avg_sales)
ggplot(monthly_avg_sales, aes(x = Month, y = rolling_mean, color = Product_Category)) + labs( title = "3 Month Rolling Mean per Product Category", x = "Month", y = "Rolling Mean ($)" ) + geom_line()
In [258…
#One plot for each product category showing both avg sales and rolling means
#create new variables for each product category books_rolling <- monthly_avg_sales %>% filter(Product_Category == 'Books') clothing_rolling <- monthly_avg_sales %>% filter(Product_Category == 'Clothing') electronics_rolling <- monthly_avg_sales %>% filter(Product_Category == 'Electronics') furniture_rolling <- monthly_avg_sales %>% filter(Product_Category == 'Furniture') homeappliances_rolling <- monthly_avg_sales %>% filter(Product_Category == 'Home Appliances') toys_rolling <- monthly_avg_sales %>% filter(Product_Category == 'Toys')
#plot each category w/ avg sales and rolling means #books ggplot(books_rolling, aes(x = Month)) + geom_line(aes(y = avg_sales, color = "Average Sales")) + geom_line(aes(y = rolling_mean, color = "Rolling Mean")) + labs(x = "Month", y = "Sales", title = "Books: Monthly Average Sale and Rolling Mean")
#clothing ggplot(clothing_rolling, aes(x = Month)) + geom_line(aes(y = avg_sales, color = "Average Sales")) + geom_line(aes(y = rolling_mean, color = "Rolling Mean")) + labs(x = "Month", y = "Sales", title = "Clothing: Monthly Average Sale and Rolling Mean")
#electronics ggplot(electronics_rolling, aes(x = Month)) + geom_line(aes(y = avg_sales, color = "Average Sales")) + geom_line(aes(y = rolling_mean, color = "Rolling Mean")) + labs(x = "Month", y = "Sales", title = "Electronics: Monthly Average Sale and Rolling Mean")
#furniture ggplot(furniture_rolling, aes(x = Month)) + geom_line(aes(y = avg_sales, color = "Average Sales")) + geom_line(aes(y = rolling_mean, color = "Rolling Mean")) + labs(x = "Month", y = "Sales", title = "Furniture: Monthly Average Sale and Rolling Mean")
#Home appliances ggplot(homeappliances_rolling, aes(x = Month)) + geom_line(aes(y = avg_sales, color = "Average Sales")) + geom_line(aes(y = rolling_mean, color = "Rolling Mean")) + labs(x = "Month", y = "Sales", title = "Home Appliances: Monthly Average Sale and Rolling Mean")
#Toys ggplot(toys_rolling, aes(x = Month)) + geom_line(aes(y = avg_sales, color = "Average Sales")) +
Warning message: “Removed 1 row containing missing values (geom_line()).”
see that the rolling mean plot seems to have peaks around May and August. This might mean seasonal buying habits among customers. Increasing the rolling average window might give us a better picture and smoother trends.
For this question, use trainData_sales
Q 3 a)(4 points) Create a boxplot of the response variable versus each of the following predicting variables
i) Store_Location
ii) Product_Category
Explain the relationship between the response variable and each of the two variables based on the boxplots.
location_boxplot <- ggplot(trainData_sales, aes(x = Store_Location, y = Satisfaction_Score)) + geom_boxplot() + labs(title = "Satisfaction Score by Store Location") + guides(x = guide_axis(n.dodge = 2 )) #fix overcrowded x labels
location_boxplot
product_boxplot <- ggplot(trainData_sales, aes(x = Product_Category, y = Satisfaction_Score)) + geom_boxplot() + labs(title = "Satisfaction Score by Product Category")
product_boxplot
In [259…
Based on the boxplots, the satisfaction level of the customer does not seem to vary by
store location. Although there are a couple of outlying satisfaction scores in Boston and
Denver, for the most part, the median satisfaction scores are about the same at 7-8 for
#r age_model <- summary(lm(Satisfaction_Score ~ Customer_Age, data = trainData_sales))
age_r <- sqrt(age_model $ r.squared)
In [261…
age_r #0.0508086867079065 < 0.4, weak
purchase_model <- summary(lm(Satisfaction_Score ~ Purchase_Amount, data = trainData_sales)) purchase_r <- sqrt(purchase_model $ r.squared) purchase_r #0.383114837770035 < 0.4, weak
Looking at the scatter plot, there does not seem to be a general trend between customer age and satisfaction score. The scores are evenly distributed for each age. The r value is 0.05, indicating there is a very weak linear relationship between the two variables.
The scatter plot of purchase amount vs satisfaction score seems to show a positive relationship. As purchase amount increases, the satisfaction score also seems to increase. The dots of the graph have an upward movement to the right. The r value of this model is 0.38. The linear relationship is still weak, but much stronger than that of customer age and satisfaction.
For this question, use trainData_sales
Q 4 a) (5 points) Create a simple linear regression model using the predictor "Purchase_Amount". Call it model1. Display the summary.
i) What are the model parameters and their estimates?
ii) Interpret the coefficient of the predictor "Purchase_Amount" in the context of the problem.
iii) Find a 95 % confidence interval for the coefficient of "Purchase_Amount". Is the coefficient significant at this level?
model1 <- lm(Satisfaction_Score ~ Purchase_Amount, data = trainData_sales) summary(model1)
In [262…
i) State the null and alternative hypotheses.
ii) Using an α-level of 0.01, do we reject the null hypothesis that the means are equal? Explain your conclusion.
iii) Which means are plausibly similar at the confidence level of 99 %?
iv) Compare the satisfaction score of the following pair of product categories:
Electronics-Clothing
anova_model <- aov(Satisfaction_Score ~ Product_Category, data = trainData_sales) summary(anova_model)
Df Sum Sq Mean Sq F value Pr(>F) Product_Category 5 674.9 134.97 110.2 <2e-16 *** Residuals 794 972.5 1.
Signif. codes: 0 ‘’ 0.001 ‘’ 0.01 ‘’ 0.05 ‘.’ 0.1 ‘ ’ 1
Response to Q 4 ci H0: The means of satisfaction scores across product categories are equal. H1: The means of satisfaction scores across product categories are not equal.
Response to Q 4 cii Because the p-value is approximately equal to zero and less than alpha=0.01, we reject the null hypothesis of equal means for satisfaction scores across product categories, concluding that there are significant differences in satisfaction scores across product categories.
model.tables(anova_model, type = "means")
Tables of means Grand mean
Product_Category Books Clothing Electronics Furniture Home Appliances Toys 7.065 7.102 8.865 7.961 7.983 5. rep 140.000 131.000 142.000 112.000 139.000 136.
Response to Q 4 ciii The mean satisfaction scores between Books and Clothing are similar, and the means between Furniture and Home appliances are similar.
TukeyHSD(aov(Satisfaction_Score ~ Product_Category, data = trainData_sales))
In [264…
In [265…
In [266…
Tukey multiple comparisons of means 95% family-wise confidence level
Fit: aov(formula = Satisfaction_Score ~ Product_Category, data = trainData_s ales)
$Product_Category diff lwr upr p adj Clothing-Books 0.03700886 -0.3472997 0.4213175 0. Electronics-Books 1.79972660 1.4231863 2.1762669 0. Furniture-Books 0.89568210 0.4948870 1.2964772 0. Home Appliances-Books 0.91781089 0.5392587 1.2963631 0. Toys-Books -1.06748120 -1.4481227 -0.6868397 0. Electronics-Clothing 1.76271774 1.3797196 2.1457158 0. Furniture-Clothing 0.85867325 0.4518052 1.2655413 0. Home Appliances-Clothing 0.88080203 0.4958258 1.2657783 0. Toys-Clothing -1.10449006 -1.4915210 -0.7174591 0. Furniture-Electronics -0.90404450 -1.3035831 -0.5045058 0. Home Appliances-Electronics -0.88191572 -1.2591375 -0.5046940 0. Toys-Electronics -2.86720780 -3.2465262 -2.4878894 0. Home Appliances-Furniture 0.02212878 -0.3793065 0.4235641 0. Toys-Furniture -1.96316330 -2.3665694 -1.5597572 0. Toys-Home Appliances -1.98529208 -2.3666077 -1.6039764 0.
Response to Q 4 civ There is a 1.76271774 difference between the mean satisfaction scores between Electronics and Clothing. The p-value is 0, meaning we reject the null hypothesis and conclude that the means of satisfaction scores between these 2 categories are significantly different.
Q 5 a)(4 points) Perform the following model diagnostics on model 1 created in Q 4 a.
i) Check for linearity assumption
ii) Check for constant variance
iii) Check for normality
Note: Both a histogram and a normal QQ plot with a pointwise confidence envelope must be plotted. Hint: qqPlot() from the car package can generate a pointwise confidence envelope.
Explain your conclusion
#model 1 is satisfaction score ~ purchase amt library(car)
par(mfrow = c( 2 , 2 )) #linearity assumption plot(fitted(model1), resid(model1), main = "Fitted vs Residuals",
In [267…