Docsity

regression analysis homework, Summaries of Statistics

Toggle sidebar
bg1
S
pr
i
n
g
2025-
H
W
2
S
olut
i
ons
-
R
2025-01-01
knitr::opts_chunk$set(echo = TRUE)
T
hi
s
not
eb
oo
k
s
h
oul
d
be
s
e
t
to
t
he
c
orr
ec
t
K
e
rn
e
l
bef
or
e
wor
ki
n
g
on
t
he
qu
e
st
i
ons
.
S
a
l
e
s
a
n
d
C
ustom
e
r
I
nt
e
r
ac
t
i
on
D
a
t
a
s
e
t
I
n
h
om
e
wor
k
2,
w
e
agai
n
v
i
s
i
t
t
he
s
a
l
e
s
da
t
a
s
e
t
us
ed
i
n
h
om
e
wor
k
1.
A
s
a
r
e
m
i
n
de
r
,
t
he
da
t
a
s
e
t
c
ont
ai
ns
t
he
f
ollow
i
n
g
c
olumns
:
1)
C
ustom
e
r
_
ID
:
U
n
i
qu
e
ide
nt
ifie
r
f
or
each
c
ustom
e
r
.
2)
P
ro
d
u
c
t
_
C
a
t
eg
ory
:
C
a
t
eg
ory
o
f
pur
cha
s
ed
pro
d
u
c
t
(
e
.
g
.
'
B
oo
k
s
',
'
E
l
ec
tron
ic
s
',
'
T
oys
',
'
C
lot
hi
n
g
',
e
t
c
.).
3)
P
ur
cha
s
e
_
A
mount
:
T
ot
a
l
a
mount
,
i
n
d
oll
a
rs
,
sp
e
nt
on
each
pur
cha
s
e
.
4)
P
ur
cha
s
e
_
D
a
t
e
:
D
a
t
e
o
f
tr
a
ns
ac
t
i
on
.
5)
C
ustom
e
r
_
A
ge
:
A
ge
o
f
c
ustom
e
r
a
t
t
i
m
e
o
f
pur
cha
s
e
.
6)
C
ustom
e
r
_
G
e
n
de
r
:
G
e
n
de
r
o
f
t
he
c
ustom
e
r
('
M
a
l
e
'
or
'
F
e
m
a
l
e
').
7)
S
tor
e
_
L
o
ca
t
i
on
:
L
o
ca
t
i
on
o
f
stor
e
w
he
r
e
pur
cha
s
e
o
cc
urr
ed
.
8)
S
a
t
i
s
fac
t
i
on
_
S
c
or
e
(
r
e
spons
e
v
a
r
iab
l
e
)
:
N
um
e
r
ic
r
e
spons
e
v
a
r
iab
l
e
i
n
dica
t
i
n
g
c
ustom
e
r
'
s
s
a
t
i
s
fac
t
i
on
l
e
v
e
l
f
rom
0
(
l
ea
st
s
a
t
i
s
fied
)
to
10
(
most
s
a
t
i
s
fied
).
set.seed(17) # Seed set to ensure reproducible results. DO NOT CHANGE SEED O
# Load the dataset
sales_data <- read.csv("cleaned_sales_dataset.csv", header = TRUE)
# Convert specified columns to categorical variables
sales_data$Product_Category <- as.factor(sales_data$Product_Category)
sales_data$Customer_Gender <- as.factor(sales_data$Customer_Gender)
sales_data$Store_Location <- as.factor(sales_data$Store_Location)
# Convert Purchase_Date to Date format
sales_data$Purchase_Date <- as.Date(sales_data$Purchase_Date, format="%m/%d/
# Split the data into 80% training and 20% test sets
In[1]:
In[2]:
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20

Partial preview of the text

Download regression analysis homework and more Summaries Statistics in PDF only on Docsity!

Spring 2025-HW 2 Solutions-R

knitr :: opts_chunk $ set(echo = TRUE )

This notebook should be set to the correct Kernel

before working on the questions.

Sales and Customer Interaction Dataset

In homework 2, we again visit the sales dataset used in homework 1. As a reminder, the dataset contains the following columns:

1) Customer_ID : Unique identifier for each customer.

2) Product_Category : Category of purchased product (e.g. 'Books', 'Electronics', 'Toys', 'Clothing', etc.).

3) Purchase_Amount : Total amount, in dollars, spent on each purchase.

4) Purchase_Date : Date of transaction.

5) Customer_Age : Age of customer at time of purchase.

6) Customer_Gender : Gender of the customer ('Male' or 'Female').

7) Store_Location : Location of store where purchase occurred.

8) Satisfaction_Score (response variable) : Numeric response variable indicating customer's satisfaction level from 0 (least satisfied) to 10 (most satisfied).

set.seed( 17 ) # Seed set to ensure reproducible results. DO NOT CHANGE SEED O

# Load the dataset sales_data <- read.csv("cleaned_sales_dataset.csv", header = TRUE )

# Convert specified columns to categorical variables sales_data $ Product_Category <- as.factor(sales_data $ Product_Category) sales_data $ Customer_Gender <- as.factor(sales_data $ Customer_Gender) sales_data $ Store_Location <- as.factor(sales_data $ Store_Location)

# Convert Purchase_Date to Date format sales_data $ Purchase_Date <- as.Date(sales_data $ Purchase_Date, format = "%m/%d/

# Split the data into 80% training and 20% test sets

In [1]:

In [2]:

sample_int_ceiling <- sample.int(n = nrow(sales_data), size = ceiling(. 80 ***** nrow(sales_data)), rep train_sales_data <- sales_data[sample_int_ceiling, ] test_sales_data <- sales_data[ - sample_int_ceiling, ]

# Remove row names rownames(train_sales_data) <- NULL rownames(test_sales_data) <- NULL

# Load necessary libraries library(dplyr) library(hexbin) library(ggplot2) library(car)

Attaching package: ‘dplyr’

The following objects are masked from ‘package:stats’:

filter, lag

The following objects are masked from ‘package:base’:

intersect, setdiff, setequal, union

Loading required package: carData

Attaching package: ‘car’

The following object is masked from ‘package:dplyr’:

recode

Question 1: Data Preparation (6 points)

1 a) Using the dataframe, "sales_data", sort by the Satisfaction_Score (from low to high), print the first 10 rows of the dataframe, then print minimum, maximum, 10 th percentile, 25 th percentile, 50 th percentile, 75 th percentile, 90 th percentile, average, and median Satisfaction_Score. Note: the sorting should be permanently (not temporarily) stored unless otherwise stated. (3 points)

# Sort the dataframe by Satisfaction_Score from low to high sales_data <- sales_data[order(sales_data $ Satisfaction_Score), ]

# Print the first 10 rows of the sorted dataframe print(head(sales_data, 10 ))

In [3]:

In [4]:

# Customers with > 5 purchases. frequent_customers <- customer_purchase_count[customer_purchase_count > 5 ]

frequent_customers

199 1058 7 6

Response:

Two customers have made more than 5 purchases. The customers that have made more than 5 purchases are customer_ID 199 and customer_ID 1058.

1 c) If the customers with more than 5 purchases have made more than 5 purchases at a single Store_Location, management would like to exclude these customers from future analyses. For each customer identified in 1 b, list the Store_Location where they made purchases. Have the customers identified in question 1 b made more than 5 purchases at a single Store_Location? (1 point)

# Stores customer_ID 199 made purchases in. customer_199_stores <- subset(sales_data, Customer_ID %in% names(frequent_cu

# Stores customer_ID 1058 made purchases in. customer_1058_stores <- subset(sales_data, Customer_ID %in% names(frequent_c

customer_199_stores customer_1058_stores

A data.frame: 7 × 8 Customer_ID Product_Category Purchase_Amount Purchase_Date Customer_Age

98 199 Clothing 1706.19 2024-02-15 25

93 199 Books 1055.37 2024-01-09 25

95 199 Clothing 517.81 2024-12-29 25

94 199 Clothing 1739.17 2024-07-31 25

96 199 Home Appliances 764.91 2024-11-08 25

97 199 Home Appliances 1022.67 2024-03-21 25

92 199 Furniture 445.02 2024-02-03 25

In [6]:

A data.frame: 6 × 8 Customer_ID Product_Category Purchase_Amount Purchase_Date Customer_Age

960 1058 Furniture 67.45 2024-01-25 28

961 1058 Furniture 1499.58 2024-04-08 28

962 1058 Books 721.71 2024-05-20 28

963 1058 Home Appliances 1973.45 2024-03-24 28

964 1058 Books 1919.85 2024-03-05 28

959 1058 Electronics 1736.77 2024-03-20 28

Response:

Customer_ID 199 made purchases in Denver, New York, Seattle, Miami, Dallas, and Chicago. Customer_ID 1058 made purchases in San Francisco, Los Angeles, Denver, New York, and Seattle. Neither of the customers identified in question 1 b made more than 5 purchases in a single store.

Question 2: Data preparation (9 points)

2 a) Create a well-labeled stacked bar chart showing the proportion of purchases from each Product_Category in each Store_Location. Note: Store_Location should be on the x-axis, proportion of purchases should be on the y-axis, and the stacked bar chart should be colored by Product_Category which should also be the legend. The proportion should be based on number of purchases, not on the purchase amount. The proportion is a value between 0 and 1 and is not equal to the number of purchases (3 points)

# Contingency table of product categories and store locations. product_store_cross_tab = xtabs( ~ sales_data $ Product_Category + sales_data $ Stor

# Proportion table. proportion_data <- prop.table(product_store_cross_tab, margin = 2 )

# Stacked bar plot. par(mar = c( 6 , 4 , 4 , 7 )) barplot(proportion_data, main = "Proportion of purchases by product category", col = rainbow(nrow(proportion_data)), legend.text = rownames(proportion_data), args.legend = list(x = "topright", inset = c(-0.25, 0 ), bty = "n", c cex.names = 0.8, cex.axis = 0.8, las = 2 )

In [7]:

2 c) Which Store_Location has the highest proportion of furniture purchases? The proportion should be based on number of purchases, not on purchase amount. ( point)

# Furniture percentages in each store location. furniture_proportions <- proportion_data["Furniture", ]

sort(furniture_proportions, decreasing = TRUE )

Denver: 0.202898550724638 Las Vegas: 0.182926829268293 New York: 0.180722891566265 Seattle: 0.164383561643836 San Francisco: 0. Houston: 0.151515151515152 Miami: 0.142857142857143 Dallas: 0. Atlanta: 0.114754098360656 Chicago: 0.0923076923076923 Los Angeles: 0.0864197530864197 Boston: 0.0824742268041237 San Diego: 0.

Response:

Denver has the largest proportion of furniture purchases.

2 d) Which Store_Location has the lowest total purchases (use amounts in "Purchase_Amount")? (1 point)

total_sales_by_store <- aggregate(Purchase_Amount ~ Store_Location, data = s

total_sales_by_store[order(total_sales_by_store $ Purchase_Amount), ]

In [9]:

In [10]:

A data.frame: 13 × 2 Store_Location Purchase_Amount

1 Atlanta 56866.

5 Denver 59561.

3 Chicago 63450.

6 Houston 64143.

11 San Diego 69391.

9 Miami 74986.

7 Las Vegas 80970.

13 Seattle 81080.

10 New York 81236.

12 San Francisco 82676.

4 Dallas 88589.

8 Los Angeles 90356.

2 Boston 99292.

Response:

Atlanta has the lowest total purchases.

2 e) Unfortunately, let's imagine that management has decided to close the Denver store location and also stop selling furniture across all store locations. Create a new dataframe called "filtered_sales_data", where rows that contain "Denver" in "Store_Location" or "Furniture" in "Product_Category" are removed. The resulting dataframe must have 812 observation rows and 8 variables. Sort filtered_sales_data by Customer_ID in descending order and print rows 150 to 160 of the resulting dataframe. Note: the sorting should be permanently (not temporarily) stored unless otherwise stated. (2 points)

# Assuming your original dataframe is called sales_data

# Filter out rows where Store_Location is "Denver" or Product_Category is "F filtered_sales_data <- sales_data[! (sales_data $ Store_Location == "Denver" |

# Check the number of rows to ensure it has 812 rows if (nrow(filtered_sales_data) == 812 ) { # Sort the dataframe by Customer_ID in descending order filtered_sales_data <- filtered_sales_data[order(filtered_sales_data $ Custo

# Print rows 150 to 160 print(filtered_sales_data[ 150 : 160 , ])

In [11]:

does not significantly alter the overall satisfaction trend. However, it may matter for localized analyses (e.g., Denver store performance).

Question 3: Exploratory Data Analysis (

points)

We will be using the split data sets, "train_sales_data" and "test_sales_data," creating in the starter code in the beginning of this document going forward.

3 a) Using "train_sales_data", create an Hexbin Plot of the response, "Satisfaction_Score" against "Purchase_Amount". Calculate then output the R- squared and comment on the direction (positive or negative) and strength of the correlation (<=0.3: weak; >0.3 and <0.7: moderate; >=0.7: strong). (5 points)

# Hexbin plot for Satisfaction_Score vs Purchase_Amount hexbin_plot <- ggplot(train_sales_data, aes(x = Purchase_Amount, y = Satisfa geom_hex(bins = 30 ) + labs(title = "Hexbin Plot: Satisfaction Score vs Purchase Amount", x = "Pu theme_minimal()

# Print the Hexbin plot print(hexbin_plot)

# Calculate R-squared for Satisfaction_Score vs Purchase_Amount model <- lm(Satisfaction_Score ~ Purchase_Amount, data = train_sales_data) r_squared <- summary(model) $ r.squared

# Output the R-squared value print(paste("R-squared for Satisfaction_Score vs Purchase_Amount:", round(r_

# Comment on the direction and strength of the correlation if (r_squared <= 0.3) { strength <- "weak" } else if (r_squared > 0.3 & r_squared < 0.7) { strength <- "moderate" } else { strength <- "strong" }

direction <- ifelse(coef(model)[ 2 ] > 0 , "positive", "negative")

print(paste("The correlation between Satisfaction_Score and Purchase_Amount

[1] "R-squared for Satisfaction_Score vs Purchase_Amount: 0.132" [1] "The correlation between Satisfaction_Score and Purchase_Amount is posit ive and the strength of the correlation is weak ."

In [13]:

3 b)Using "train_sales_data", create a boxplot of the response, Satisfaction_Score, vs. Purchase_Month. You will have to calculate Purchase_Month by using Purchase_Date. Ensure Purchase_Month is a categorical variable and ranges from 01 - 12. From observation of the boxplot, what month has the highest median satisfaction score? Using just the resulting boxplot, is the satisfaction score for any of the month significantly different from the satisfaction scores of the other months? Note: we will now have 9 variables (since we added Purchase_Month) in the resulting train and test dataframes (3 points)

# Column for month of purchase. train_sales_data $ Purchase_Month <- format(train_sales_data $ Purchase_Date, "% train_sales_data $ Purchase_Month = as.factor(train_sales_data $ Purchase_Month)

# Boxplot. boxplot(Satisfaction_Score ~ Purchase_Month, data = train_sales_data, xlab = "Purchase_Month", ylab = "Satisfaction_Score", main = "Boxplot of Purchase_Month vs. Satisfaction_Score", col = rainbow(length(unique(train_sales_data $ Purchase_Month))))

In [14]:

elements of the test of overall regression of the model: null hypothesis H0, alternative hypothesis Ha, F-statistic or p-value, and conclusion (3 points)

model1 <- lm(Satisfaction_Score ~ Product_Category + Purchase_Amount + Custo + Store_Location + Purchase_Month, data = train_sales_data) summary(model1)

In [15]:

Call: lm(formula = Satisfaction_Score ~ Product_Category + Purchase_Amount + Customer_Age + Customer_Gender + Store_Location + Purchase_Month, data = train_sales_data)

Residuals: Min 1Q Median 3Q Max -2.9013 -0.6519 -0.0141 0.6243 3.

Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 6.180e+00 2.125e-01 29.086 < 2e-16 *** Product_CategoryClothing -3.004e-02 1.151e-01 -0.261 0. Product_CategoryElectronics 1.939e+00 1.153e-01 16.818 < 2e-16 *** Product_CategoryFurniture 9.941e-01 1.241e-01 8.010 4.27e-15 *** Product_CategoryHome Appliances 8.500e-01 1.148e-01 7.401 3.54e-13 *** Product_CategoryToys -9.957e-01 1.153e-01 -8.634 < 2e-16 *** Purchase_Amount 1.031e-03 6.144e-05 16.784 < 2e-16 *** Customer_Age -1.699e-03 2.457e-03 -0.691 0. Customer_GenderMale -3.552e-02 6.956e-02 -0.511 0. Store_LocationBoston -1.588e-01 1.803e-01 -0.881 0. Store_LocationChicago -7.093e-03 1.951e-01 -0.036 0. Store_LocationDallas -1.870e-01 1.870e-01 -1.000 0. Store_LocationDenver -1.812e-01 1.927e-01 -0.940 0. Store_LocationHouston -1.103e-01 1.949e-01 -0.566 0. Store_LocationLas Vegas -1.725e-01 1.839e-01 -0.938 0. Store_LocationLos Angeles -1.341e-01 1.870e-01 -0.717 0. Store_LocationMiami -1.685e-01 1.901e-01 -0.886 0. Store_LocationNew York -6.727e-02 1.869e-01 -0.360 0. Store_LocationSan Diego -3.251e-01 1.912e-01 -1.701 0.. Store_LocationSan Francisco -3.385e-01 1.835e-01 -1.845 0.. Store_LocationSeattle -1.570e-02 1.893e-01 -0.083 0. Purchase_Month02 1.802e-01 1.655e-01 1.089 0. Purchase_Month03 -9.526e-02 1.590e-01 -0.599 0. Purchase_Month04 1.529e-01 1.747e-01 0.875 0. Purchase_Month05 -3.615e-02 1.592e-01 -0.227 0. Purchase_Month06 -1.521e-02 1.563e-01 -0.097 0. Purchase_Month07 6.859e-04 1.521e-01 0.005 0. Purchase_Month08 1.928e-01 1.574e-01 1.225 0. Purchase_Month09 9.427e-02 1.603e-01 0.588 0. Purchase_Month10 1.315e-01 1.598e-01 0.822 0. Purchase_Month11 -2.318e-02 1.572e-01 -0.147 0. Purchase_Month12 5.099e-02 1.610e-01 0.317 0.

Signif. codes: 0 ‘’ 0.001 ‘’ 0.01 ‘’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 0.9507 on 768 degrees of freedom Multiple R-squared: 0.5737, Adjusted R-squared: 0. F-statistic: 33.34 on 31 and 768 DF, p-value: < 2.2e-

Response:

We can conduct an F-Test in order to assess the overall adequacy of the model The elements of the test of overall regression are as follows: H 0 : β 1 = ... = β 29 = 0 Ha: At least one of the slope coefficients is nonzero Test statistic: F(31, 768) = 33.34 p-value: <

xlab = "Purchase_Amount", ylab = "Standardized residuals", abline(h = 0 , col = "red") ) plot(train_sales_data $ Customer_Age, model1_sresids, xlab = "Customer_Age", ylab = "Standardized residuals", abline(h = 0 , col = "red") )

Response:

When assessing linearity assumptions, we examine the standardized residuals (i.e., the differences between observed and predicted values) in a regression model. The residual plot helps us identify patterns or deviations from linearity. If the relationship between predictors and the response is linear, we expect the residuals to be randomly scattered around zero. Non-random patterns (e.g., U-shaped, funnel-shaped, or curvilinear) in the residual plot suggest violations of linearity assumptions. Hence, for the plots we have created above, the linearity assumption appears to hold for Purchase_Amount and Customer_Age as the residuals are randomly scattered about the horizontal axis.

4 f) Create a scatterplot of the standardized residuals vs. the fitted values of model1. Does the constant variance assumption hold? Does the assumption of uncorrelated errors hold? (2 points)

plot(model1 $ fitted.values, model1_sresids, xlab = "Fitted values",

In [17]:

ylab = "Standardized residulas", abline(h = 0 , col = "red") )

Response:

The residuals vs. fitted values plot is a useful tool for assessing both the constant

variance assumption and the independence assumption in regression models. For the

constant variance assumption, also known as homoscedasticity, this assumption states

that the spread of the residuals (i.e., the differences between observed and predicted

values) should be roughly equal across all levels of the fitted values. In the residuals vs.

fitted values plot, if the spread of residuals remains consistent as the fitted values

change, the constant variance assumption is met. Otherwise, if the spread

systematically increases or decreases, the assumption may be violated. Hence, for the

plot we have created above, the assumption of constant variance appears to not hold as

we do see a slight decrease in variance of the standardized residuals as we move to the

higher fitted values.

We also use the plot to check that the residuals are independent of each other (i.e., not

correlated). Patterns (e.g., U-shape, funnel shape) may indicate a violation of the

assumption. Keep in mind the assumption is independence, but we cannot directly prove

independence. We check for correlated errors (residuals) instead. If there are clumps in

the residual plot, then there is evidence of correlated errors. If you have correlated

errors, you cannot assume independence. If you do not see clumping, then you can say

that the errors are not correlated. However, this is a necessary, but not sufficient,

5 a) Calculate the VIF of each predictor in model1. Using a VIF threshold of what conclusion do you make regarding multicolinearity? ( points)

# VIF threshold. cat("VIF threshold: ", max( 10 , 1 / ( 1 - summary(model1) $ r.squared)), "\n")

# VIF. vif(model1)

VIF threshold: 10 A matrix: 6 × 3 of type dbl GVIF Df GVIF^(1/(2Df))*

Product_Category 1.194839 5 1.

Purchase_Amount 1.051836 1 1.

Customer_Age 1.038019 1 1.

Customer_Gender 1.030120 1 1.

Store_Location 1.322333 12 1.

Purchase_Month 1.292112 11 1.

Response:

The VIFs for the predictors are less than the threshold of 10, suggesting multi- collinearity is not present in model1.

5 b) Create a plot of Cook's distances for model1. Using a threshold of 4/n, print the calculated threshold. Are there any outliers present? How many outliers do we have? Output the highest 5 outlier rows from train_sales_data (since we used train_sales_data to create model1). (4 points)

# Calculate Cook's distances model1_cook <- cooks.distance(model1)

# Get the number of rows in the dataset used to create the model cook_n <- nrow(model1 $ model)

# Calculate threshold cook_threshold <- 4 / cook_n

# Plot Cook's distances plot(model1_cook, main = "Cook's Distance", ylab = "Cook's Distance", xlab = abline(h = cook_threshold, col = "red", lty = 2 )

# Print the calculated threshold print(paste("Cook's distance threshold:", cook_threshold))

# Identify outliers

max (10, 1/(1 − R^2 ))

In [19]:

In [20]:

outliers <- which(model1_cook > cook_threshold)

# Print the number of outliers print(paste("Number of outliers:", length(outliers)))

# Output the highest 5 outlier rows from train_sales_data highest_outliers <- order(model1_cook[outliers], decreasing = TRUE )[ 1 : 5 ] outlier_rows <- train_sales_data[outliers[highest_outliers], ] print(outlier_rows)

[1] "Cook's distance threshold: 0.005" [1] "Number of outliers: 45" Customer_ID Product_Category Purchase_Amount Purchase_Date Customer_Age 120 963 Toys 1143.95 2024-04-07 64 639 898 Books 670.47 2024-11-26 44 216 535 Toys 169.82 2024-12-15 30 91 444 Toys 1567.93 2024-10-24 44 627 317 Home Appliances 1643.77 2024-11-06 18 Customer_Gender Store_Location Satisfaction_Score Purchase_Month 120 Female Chicago 9.236591 04 639 Female Houston 9.896602 11 216 Female San Diego 7.862578 12 91 Female Atlanta 9.531038 10 627 Female Las Vegas 5.597841 11

5 c) Why might removing outliers improve the model, but also risk losing important information? (1 point)

Response: Removing outliers often improves model fit by reducing the undue influence of extreme points, leading to more stable and generalizable coefficients. However,