
























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:
C ustom e r _ID : Unique identifier for each customer.
P ro d u c t _Ca t eg ory: Category of the purchased product (e.g., Electronics, Clothing, Home Appliances, etc.).
P ur cha s e_A mount: Total amount spent on each purchase, in dollars.
P ur cha s e_Da t e : Date of the transaction
C ustom e r _Age : Age of the customer at the time of purchase.
C ustom e r _Ge n de r: Gender of the customer, Male or Female
S tor e_L o ca t i on: Location of the store where the purchase occurred.
Sa t i s fac t i on _Sc or e ( r e spons e v a r iab l e) : Numeric response variable indicating the customer's satisfaction level
N ot e:
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 [1]:
In [2]:
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
F or t hi s qu e st i on , us e t he "Sa l e s _da t a s e t "
1 a)(4 po i nts ) O utput a t ab l e t ha t ha s b ot h t he a v e r age a n d m edia n P ur cha s e_A mount g roup ed b y P ro d u c t _Ca t eg ory , C ustom e r _Ge n de r a n d bi nn ed C ustom e r _Age. Sh ow t he l a st 15 rows o f t he t ab l e (e x c lu di n g rows w i t h NaN/NA/ null v a lu e s )
N ot e: F or age g roup , us e t he f ollow i n g bi ns
Product_Category Customer_Gender Age_Group Average_Purchase_Amount 67 Home Appliances Male 46-55 1372. 68 Home Appliances Male 56-65 1109. 69 Home Appliances Male 66-75 895. 70 Toys Female 19-25 1013. 71 Toys Female 26-35 1026. 72 Toys Female 36-45 586. 73 Toys Female 46-55 1053. 74 Toys Female 56-65 948. 75 Toys Female 66-75 929. 76 Toys Male 0-18 1114. 77 Toys Male 19-25 1139. 78 Toys Male 26-35 1155. 79 Toys Male 36-45 931. 80 Toys Male 46-55 778. 81 Toys Male 56-65 1008. median_Purchase_Amount 67 1493. 68 1126. 69 965. 70 1069. 71 1040. 72 480. 73 888. 74 810. 75 997. 76 1114. 77 1068. 78 1176. 79 723. 80 545. 81 901.
Q 1 b)(2 po i nts ) Which c ustom e r age g roup ha s t he highe st tot a l sum o f pur cha s e a mount ac ross a ll ca t eg or ie s?
# Calculate the total purchase amount for each age group total_purchase_by_age_group <- Sales_dataset %>% group_by(Age_Group) %>% summarise(Total_Purchase_Amount = sum(Purchase_Amount, na.rm = TRUE ))
# Identify the age group with the highest total purchase amount highest_total_purchase_age_group <- total_purchase_by_age_group %>% filter(Total_Purchase_Amount == max(Total_Purchase_Amount))
# Print the result print(highest_total_purchase_age_group)
Age_Group Total_Purchase_Amount
1 26-35 279 965.
Q 1 c)(2 po i nts ) Which pro d u c t ca t eg ory ha s t he highe st a v e r age s a t i s fac t i on s c or e? F or t he ide nt ified pro d u c t ca t eg ory , i n w hich stor e lo ca t i on i s i t most f r e qu e ntly
In [6]:
pur cha s ed?
# Calculate the average satisfaction score for each product category average_satisfaction_score <- Sales_dataset %>% group_by(Product_Category) %>% summarise(Average_Satisfaction_Score = mean(Satisfaction_Score, na.rm = TR
# Identify the product category with the highest average satisfaction score highest_satisfaction_category <- average_satisfaction_score %>% filter(Average_Satisfaction_Score == max(Average_Satisfaction_Score))
# Get the name of the product category with the highest satisfaction score highest_category <- highest_satisfaction_category $ Product_Category
# Determine the most frequent store location for the identified product cate most_frequent_location <- Sales_dataset %>% filter(Product_Category == highest_category) %>% count(Store_Location) %>% filter(n == max(n))
# Print the results print(highest_satisfaction_category)
Product_Category Average_Satisfaction_Score
1 Electronics 8.
print(most_frequent_location)
Store_Location n 1 Boston 23
F or t hi s qu e st i on , us e "Sa l e s _da t a s e t "
Q 2 a) (3 po i nts ) Ca l c ul a t e t he mont h ly a v e r age s a l e s p e r pro d u c t ca t eg ory a n d plot t he m. C r ea t e on e plot s h ow i n g a ll pro d u c t ca t eg or ie s. Each ca t eg ory s h oul d ha v e i ts own l i n e, c olor a n d l ege n d e ntry.
Hi nt : M ont h ly a v e r age s a l e s a r e t he m ea n s a l e s a mount b y ca t eg ory b y mont h.
library(ggplot2) library(lubridate)
In [7]:
In [8]:
In [9]:
**Month Product_Category Average_Sales **
- A tibble: 72 × - 2024-01-01 Books 997. - 2024-01-01 Clothing 895. - 2024-01-01 Electronics 938. - 2024-01-01 Furniture 813. - 2024-01-01 Home Appliances 930. - 2024-01-01 Toys 649.Attaching package: 'zoo'
The following objects are masked from 'package:base':
as.Date, as.Date.numeric
# Define the window size window_size <- 3
# Calculate rolling mean monthly_avg_sales_per_category <- monthly_avg_sales_per_category %>% group_by(Product_Category) %>% mutate(Rolling_Mean = rollapply(Average_Sales, width = window_size, FUN = mean, align = "center", fill = NA )) ungroup()
print(monthly_avg_sales_per_category)
Month Product_Category Average_Sales Rolling_Mean
1 2024-01-01 Books 997. NA 2 2024-01-01 Clothing 896. NA 3 2024-01-01 Electronics 939. NA 4 2024-01-01 Furniture 814. NA 5 2024-01-01 Home Appliances 930. NA 6 2024-01-01 Toys 649. NA 7 2024-02-01 Books 1 002. 1 022. 8 2024-02-01 Clothing 1 065. 870. 9 2024-02-01 Electronics 1 082. 1 102. 10 2024-02-01 Furniture 837. 883.
# Plot using ggplot ggplot(monthly_avg_sales_per_category, aes(x = Month)) + geom_line(aes(y = Average_Sales, color = "Average Sales"), size = 1 ) + geom_line(aes(y = Rolling_Mean, color = "Rolling Mean"), size = 1 , linetyp facet_wrap( ~ Product_Category, scales = "free_y") + labs(title = "Monthly Average Sales and Rolling Mean by Product Category", x = "Month", y = "Sales Amount", color = "Legend") + theme_minimal() + theme(axis.text.x = element_text(angle = 45 , hjust = 1 ))
Warning message: "Using size aesthetic for lines was deprecated in ggplot2 3.4.0. ℹ Please use linewidth instead." Warning message: "Removed 2 rows containing missing values or values outside the scale range (geom_line())."
In [14]:
In [15]:
Re spons e to Q 2 b
We observe that rolling means smooth out the fluctuations in the data. It is easier to observe trends and patterns more clearly. Rolling means reduce the noise and outliers in the data.
F or t hi s qu e st i on , us e tr ai n Da t a_ s a l e s
Q 3 a)(4 po i nts ) C r ea t e a b oxplot o f t he r e spons e v a r iab l e v e rsus each o f t he f ollow i n g pr edic t i n g v a r iab l e s
i) S tor e_L o ca t i on
ii) P ro d u c t _Ca t eg ory
E xpl ai n t he r e l a t i ons hi p be tw ee n t he r e spons e v a r iab l e a n d each o f t he two v a r iab l e s ba s ed on t he b oxplots.
#Code to create plot library(ggplot2) ggplot(trainData_sales, aes(x = Store_Location, y = Satisfaction_Score, color = St geom_boxplot() + theme(axis.text.x = element_text(angle = 45 , hjust = 1 )) + ggtitle("Box Plot of Store location vs Satisfaction score")
In [16]:
Re spons e to Q 3 a
i) The boxplot shows the highest median satisfaction score for store location in Seattle. Since the boxplots are overlapping, we cannot say that the median scores are statistically significantly different. Further analysis is required. A ny v a l id o b s e rv a t i ons ab out t he b oxplots i s acce pt ab l e a s lon g a s i t not e s t ha t not hi n g st a t i st ica lly s ig n ifica nt ca n be s aid f rom t he g r a p h a lon e
ii) The boxplot shows the highest median satisfaction score for product category electronics. Since the boxplots are overlapping, we cannot say that the median scores are statistically significantly different. Further analysis is required. A ny v a l id o b s e rv a t i ons ab out t he b oxplots i s acce pt ab l e a s lon g a s i t not e s t ha t not hi n g st a t i st ica lly s ig n ifica nt ca n be s aid f rom t he g r a p h a lon e
Q 3 b)(4 po i nts ) C r ea t e s ca tt e rplots o f t he r e spons e v a r iab l e agai nst each o f t he f ollow i n g pr edic tors :
i) C ustom e r _Age
ii) P ur cha s e_A mount
De s c r ibe t he ge n e r a l tr e n d o f each plot.
O utput t he c orr e l a t i on c o efficie nt ( r ) f or each plot. U s e t he f ollow i n g | r | c ut - o ff s w hi l e e xpl ai n i n g if i t i s a w eak, mo de r a t e, or stron g l i n ea r r e l a t i ons hi p.
| r | < 0.4 ( w eak)
0.4 <= | r | <0.7 ( mo de r a t e)
| r | >= 0.7 ( stron g)
# Your code here...
plot(trainData_sales $ Customer_Age, trainData_sales $ Satisfaction_Score , xlab abline(lm(Satisfaction_Score ~ Customer_Age, data = trainData_sales),col = "red"
In [18]:
# Find correlation coefficient for Satisfaction Score ~ Customer Age r_CA <- cor(trainData_sales $ Satisfaction_Score, trainData_sales $ Customer_Age print(paste('r :', r_CA))
[1] "r : 0.0508086867079065"
plot(trainData_sales $ Purchase_Amount, trainData_sales $ Satisfaction_Score , x abline(lm(Satisfaction_Score ~ Purchase_Amount, data = trainData_sales),col = "r
In [19]:
In [20]:
ii) I nt e rpr e t t he c o efficie nt o f t he pr edic tor "P ur cha s e_A mount " i n t he c ont e xt o f t he pro b l e m.
iii) Fi n d a 95 % c on fide n ce i nt e rv a l f or t he c o efficie nt o f "P ur cha s e_A mount ". I s t he c o efficie nt s ig n ifica nt a t t hi s l e v e l?
model1 = lm(Satisfaction_Score ~ Purchase_Amount,data = trainData_sales) summary(model1)
Call: lm(formula = Satisfaction_Score ~ Purchase_Amount, data = trainData_sales)
Residuals: Min 1Q Median 3Q Max -3.9529 -0.8960 -0.0057 0.9767 3.
Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 6.5431520 0.0937456 69.80 <2e-16 *** Purchase_Amount 0.0009585 0.0000818 11.72 <2e-16 ***
Signif. codes: 0 '' 0.001 '' 0.01 '' 0.05 '.' 0.1 ' ' 1
Residual standard error: 1.327 on 798 degrees of freedom Multiple R-squared: 0.1468, Adjusted R-squared: 0. F-statistic: 137.3 on 1 and 798 DF, p-value: < 2.2e-
Re spons e to Q 4 a i) The model parameters are the intercept and its estimate=6.543, ß1(coefficient of PurchaseAmount)=0.0009585 and the variance of the error terms=1.33^2=1.
ii) The coefficient of Purchase_Amount is 0.0009585. For an increase of a dollar in the purchase amount, the satisfaction score increase by 0.0009585.
iii)
confint(model1)
A matrix: 2 × 2 of type dbl 2.5 % 97.5 %
(Intercept) 6.3591349416 6.
Purchase_Amount 0.0007978727 0.
Since the confidence interval does not include zero, the coefficient of purchase_amount is statistically significant.
Q 4 b)(3 po i nts ) I s t he c o efficie nt o f P ur cha s e_A mount st a t i st ica lly s ig n ifica nt?
i) S t a t e t he null h ypot he s i s
In [22]:
In [23]:
ii) S t a t e t he a lt e rn a t i v e h ypot he s i s
iii) Which t e st i s us ed f or t e st i n g t he s ig n ifica n ce o f c o efficie nt?
Re spons e to Q 4 b
i) Null hypothesis: coefficient of Purchase_Amount ( ß1)=
ii) Alternative hypothesis: coefficient of Purchase_Amount ( ß1)!=
iii) t-test is used for testing the significance of coefficient.
Q 4 c)( 4 po i nts ) Pe r f orm a n ANOVA F- t e st on t he m ea n Sa t i s fac t i on Sc or e ac ross P ro d u c t _Ca t eg ory.
i) S t a t e t he null a n d a lt e rn a t i v e h ypot he s e s.
ii) U s i n g a n α- l e v e l o f 0.01, d o w e r ejec t t he null h ypot he s i s t ha t t he m ea ns a r e e qu a l? E xpl ai n your c on c lus i on.
iii) Which m ea ns a r e pl a us ib ly s i m i l a r a t t he c on fide n ce l e v e l o f 99 %?
i v ) C omp a r e t he s a t i s fac t i on s c or e o f t he f ollow i n g p ai r o f pro d u c t ca t eg or ie s :
E l ec tron ic s - C lot hi n g
model_anova = aov(Satisfaction_Score ~ Product_Category,data = trainData_sales) summary(model_anova)
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
Re spons e to Q 4 c
i) Null hypothesis: All the means are equal , Alternative hypothesis: At least two means statistically significant from each other.
ii) The p-value of the F-test is <2e-16 which is less than alpha level of 0.01. We reject the null hypothesis that the means of all the product categories are equal and conclude that at least two means statistically significantly differ from each other.
TukeyHSD(model_anova,conf.level = 0.99)
In [24]:
In [25]:
ggplot(data = trainData_sales,aes(x = trainData_sales $ Purchase_Amount,y = trainDat geom_point(alpha = I(0.4),color = 'orange') + xlab('Purchase Amount') + ylab('Satisfaction score') + ggtitle('Linearity Plot') + geom_smooth(method = "lm", color = "blue")
Warning message: "Use of trainData_sales$Purchase_Amount is discouraged. ℹ Use Purchase_Amount instead." Warning message: "Use of trainData_sales$Satisfaction_Score is discouraged. ℹ Use Satisfaction_Score instead." Warning message: "Use of trainData_sales$Purchase_Amount is discouraged. ℹ Use Purchase_Amount instead." Warning message: "Use of trainData_sales$Satisfaction_Score is discouraged. ℹ Use Satisfaction_Score instead." geom_smooth() using formula = 'y ~ x'
model1_sresids <- rstandard(model1)
# Plotting standardized residuals vs. purchase amount plot(trainData_sales $ Purchase_Amount, model1_sresids, xlab = "Purchase Amount", ylab = "Standardized Residuals", main = "Standardized Residuals vs. Purchase Amount", pch = 19 , col = "blue", cex = 1.2) # Increase point size
In [26]:
In [27]:
# Add a dashed line at y = 0 abline(h = 0 , lty = 2 , col = "black")
lines(lowess(trainData_sales $ Purchase_Amount, model1_sresids), col = "red",
# Your code here ggplot(data = trainData_sales, aes(x = model1 $ fitted.values, y = (model1_sresids)) geom_point(alpha = I(0.4),color = 'orange') + xlab('Fitted Values') + ylab('Residuals') + ggtitle('Residual Plot') + geom_hline(yintercept = 0 )
In [28]: