#Research Question:

What is the impact of Average Rating, Item purchased ,Last Spend Day, Gender and Age on Total Spend by customers in the e-commerce platform?

Total Spend = b0 + b1 average rating + b2 gender+b3 age+ b4 items purchased +b5 Last spebd day

##Data source: https://www.kaggle.com/datasets/uom190346a/e-commerce-customer-behavior-dataset/data

#importing data
rawdata <- read_csv("~/Desktop/E-commerce Customer Behavior .csv")
## Rows: 350 Columns: 11
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (4): Gender, City, Membership Type, Satisfaction Level
## dbl (6): Customer ID, Age, Total Spend, Items Purchased, Average Rating, Day...
## lgl (1): Discount Applied
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
#reviewing first 1o rows
head(rawdata)
## # A tibble: 6 × 11
##   `Customer ID` Gender   Age City          `Membership Type` `Total Spend`
##           <dbl> <chr>  <dbl> <chr>         <chr>                     <dbl>
## 1           101 Female    29 New York      Gold                      1120.
## 2           102 Male      34 Los Angeles   Silver                     780.
## 3           103 Female    43 Chicago       Bronze                     511.
## 4           104 Male      30 San Francisco Gold                      1480.
## 5           105 Male      27 Miami         Silver                     720.
## 6           106 Female    37 Houston       Bronze                     441.
## # ℹ 5 more variables: `Items Purchased` <dbl>, `Average Rating` <dbl>,
## #   `Discount Applied` <lgl>, `Days Since Last Purchase` <dbl>,
## #   `Satisfaction Level` <chr>

Description:

#rename columns
colnames(rawdata)[8]="Average_Rating"
colnames(rawdata)[6]="Total_Spend"
colnames(rawdata)[7]="Item_purchased"
colnames(rawdata)[10]="Last_Purchase_Day"
#dataset for regression
data <- rawdata %>% 
  select(Average_Rating, Total_Spend, Gender, Item_purchased, Age,Last_Purchase_Day)
#data manipulation.changing format
data$Customer_ID <- seq_along(data$Total_Spend)


data$Gender <- factor(data$Gender,
                             levels = c("Female", "Male"),
                             labels = c("Female", "Male"))
head(data)
## # A tibble: 6 × 7
##   Average_Rating Total_Spend Gender Item_purchased   Age Last_Purchase_Day
##            <dbl>       <dbl> <fct>           <dbl> <dbl>             <dbl>
## 1            4.6       1120. Female             14    29                25
## 2            4.1        780. Male               11    34                18
## 3            3.4        511. Female              9    43                42
## 4            4.7       1480. Male               19    30                12
## 5            4          720. Male               13    27                55
## 6            3.1        441. Female              8    37                22
## # ℹ 1 more variable: Customer_ID <int>
library(pastecs)
## 
## Attaching package: 'pastecs'
## The following objects are masked from 'package:dplyr':
## 
##     first, last
round(stat.desc(data[c("Average_Rating", "Total_Spend", "Item_purchased","Age","Last_Purchase_Day")], basic = FALSE), 2)
##              Average_Rating Total_Spend Item_purchased   Age Last_Purchase_Day
## median                 4.10      775.20          12.00 32.50             23.00
## mean                   4.02      845.38          12.60 33.60             26.59
## SE.mean                0.03       19.35           0.22  0.26              0.72
## CI.mean.0.95           0.06       38.06           0.44  0.51              1.41
## var                    0.34   131086.50          17.27 23.73            180.66
## std.dev                0.58      362.06           4.16  4.87             13.44
## coef.var               0.14        0.43           0.33  0.14              0.51

Average_Rating: Median (4.10): The middle value of the “Average_Rating” variable is 4.10, suggesting that half of the customers have a rating lower than 4.10, and half have a rating higher than 4.10. Mean (4.02): The average rating is 4.02, indicating the central tendency of customer ratings. SE.mean (0.03): The small standard error of the mean suggests that the estimate of the average rating is precise.

Total_Spend: Median (775.20): The middle value of the “Total_Spend” variable is 775.20, suggesting that half of the customers spend less than 775.20, and half spend more. Mean (845.38): The average total spend is 845.38, representing the central tendency of customer spending. SE.mean (19.35): The standard error of the mean suggests that the estimate of the average total spend has some degree of variability. Var (131086.50): The large variance suggests a considerable spread or dispersion in total spending values. Std.dev (362.06): The standard deviation is a measure of the average deviation of individual total spending values from the mean. Coef.var (0.43): The coefficient of variation is a relative measure of variability, comparing the standard deviation to the mean. A higher coefficient of variation indicates more relative variability in total spend.

Item_purchased: Median (12.00): The middle value of the “Item_purchased” variable is 12.00, indicating that half of the customers purchased fewer than 12 items, and half purchased more. Mean (12.60): The average number of items purchased is 12.60, representing the central tendency of item purchase. SE.mean (0.22): The standard error of the mean suggests some variability in the estimate of the average number of items purchased. CI.mean.0.95 (0.44): The 95% confidence interval for the mean number of items purchased is relatively wide, indicating some uncertainty in the estimated mean. Var (17.27): The variance suggests a moderate spread or dispersion in the number of items purchased. Std.dev (4.16): The standard deviation is a measure of the average deviation of individual item purchase values from the mean. Coef.var (0.33): The coefficient of variation is a relative measure of variability, comparing the standard deviation to the mean. A higher coefficient of variation indicates more relative variability in the number of items purchased.

summary (data$Gender)
## Female   Male 
##    175    175
data_num<-data [,c("Average_Rating", "Total_Spend", "Item_purchased","Age","Last_Purchase_Day")] 
scatterplotMatrix(data_num, smooth=FALSE)

#Hypothesis:

Hypothesis for Average_Rating and Item_purchased:

Null Hypothesis (Ho): Average Rating and the number of items purchased have no significant effect on Total Spend. Alternative Hypothesis (Ha): Average Rating and the number of items purchased have a significant effect on Total Spend.

Hypothesis for Gender and Last_Purchase_Day:

Null Hypothesis (Ho): Gender and the number of days since the last purchase have no significant effect on Total Spend. Alternative Hypothesis (Ha): Gender and the number of days since the last purchase have a significant effect on Total Spend.

Hypothesis for Age:

Null Hypothesis (Ho): Age has no significant effect on Total Spend. Alternative Hypothesis (Ha): Age has a significant effect on Total Spend.

fit <- lm (Total_Spend ~ Average_Rating+Item_purchased+Gender+Last_Purchase_Day+Age,
           data=data)
vif(fit)
##    Average_Rating    Item_purchased            Gender Last_Purchase_Day 
##          7.829854          6.804281          1.567178          1.317520 
##               Age 
##          2.621403

#Results: Average_Rating and Item_purchased: Both variables have moderate collinearity.More than 5,one of them should be excluded

fit2<- lm (Total_Spend ~ Last_Purchase_Day+Age+Average_Rating,
           data=data)

vif(fit2) #results are below 5, we can continue our analysis
## Last_Purchase_Day               Age    Average_Rating 
##          1.295208          2.205409          2.630732
#check outliers for normality of errors
data$stdres <- round(rstandard(fit2),3)
data$cookD <- round(cooks.distance(fit2),3)
hist(data$stdres,
     xlab="Standart Residuals",
     ylab= "Frequency",
     main=" Histogram of standart residuals")

Not reliable since the data size 350

#Ho: Errors are normally distributed
#Ha: Errors are not normly distributed
shapiro.test(data$stdres)
## 
##  Shapiro-Wilk normality test
## 
## data:  data$stdres
## W = 0.97334, p-value = 4.679e-06

Given the very small p-value of 4.679e-06 I have enough evidence to reject the null hypothesis. This suggests that the distribution of standardized residuals significantly deviates from normality

#Checking units of high impact

hist(data$cookD,
     xlab="Cook distances",
     ylab="Frequency",
     main="Histogra of Cook distances")

Gap after 0.015 suggest a subgroup of observations with notable influence on the regression model.

# Displaying Top 3 Observations with Highest Standardized Residuals
head(data[order(data$stdres), c("Customer_ID","stdres")],3)
## # A tibble: 3 × 2
##   Customer_ID stdres
##         <int>  <dbl>
## 1          14  -2.56
## 2          26  -2.19
## 3          56  -2.19
# Displaying Top 6 Observations with Highest Standardized Residuals
head(data[order(-data$stdres), c("Customer_ID","stdres")],6) #within 3 std deviations
## # A tibble: 6 × 2
##   Customer_ID stdres
##         <int>  <dbl>
## 1         327   2.13
## 2         303   2.09
## 3         279   2.04
## 4         255   1.95
## 5         201   1.93
## 6           4   1.84
head(data[order(-data$cookD), c("Customer_ID","cookD")],8) #no high impact units
## # A tibble: 8 × 2
##   Customer_ID cookD
##         <int> <dbl>
## 1         205 0.017
## 2         350 0.015
## 3         201 0.014
## 4         326 0.013
## 5         338 0.013
## 6         302 0.011
## 7         323 0.011
## 8         347 0.011
data$stdfitted <-scale(fit$fitted.values)
scatterplot(stdres ~ stdfitted,
            ylab= "Standart residuals",
            xlab= "Standart fitted values",
            smooth =FALSE,
            regline=FALSE,
            boxplots=FALSE,
            data=data) 
## Warning in plot.window(...): "regline" is not a graphical parameter
## Warning in plot.xy(xy, type, ...): "regline" is not a graphical parameter
## Warning in axis(side = side, at = at, labels = labels, ...): "regline" is not a
## graphical parameter

## Warning in axis(side = side, at = at, labels = labels, ...): "regline" is not a
## graphical parameter
## Warning in box(...): "regline" is not a graphical parameter
## Warning in title(...): "regline" is not a graphical parameter

Model is non linear. Homoskedasticity violeted

#H0: We have homoscedasticity
#H1: We have heteroskedasticity

ols_test_breusch_pagan(fit)
## 
##  Breusch Pagan Test for Heteroskedasticity
##  -----------------------------------------
##  Ho: the variance is constant            
##  Ha: the variance is not constant        
## 
##                  Data                   
##  ---------------------------------------
##  Response : Total_Spend 
##  Variables: fitted values of Total_Spend 
## 
##          Test Summary          
##  ------------------------------
##  DF            =    1 
##  Chi2          =    8.784336 
##  Prob > Chi2   =    0.003038281

We reject H0. Heterescedasticity is present.

summary (fit)
## 
## Call:
## lm(formula = Total_Spend ~ Average_Rating + Item_purchased + 
##     Gender + Last_Purchase_Day + Age, data = data)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -153.473  -33.413   -5.524   30.747  112.396 
## 
## Coefficients:
##                    Estimate Std. Error t value Pr(>|t|)    
## (Intercept)       -245.2475    55.6224  -4.409 1.39e-05 ***
## Average_Rating     172.4011    11.9792  14.392  < 2e-16 ***
## Item_purchased      56.8899     1.5599  36.470  < 2e-16 ***
## GenderMale         -77.8329     6.2137 -12.526  < 2e-16 ***
## Last_Purchase_Day   -4.2554     0.2122 -20.050  < 2e-16 ***
## Age                 -4.9714     0.8261  -6.018 4.53e-09 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 46.43 on 344 degrees of freedom
## Multiple R-squared:  0.9838, Adjusted R-squared:  0.9836 
## F-statistic:  4176 on 5 and 344 DF,  p-value: < 2.2e-16

Standart errors are biased.Considering the heteroscedasticity, we will use heteroscedasticity-robust standard errors

library (estimatr)
fit3 <-lm_robust (Total_Spend~Last_Purchase_Day + Age + Average_Rating, 
                  se_type="HC1",
                  data = data)

summary (fit3)
## 
## Call:
## lm_robust(formula = Total_Spend ~ Last_Purchase_Day + Age + Average_Rating, 
##     data = data, se_type = "HC1")
## 
## Standard error type:  HC1 
## 
## Coefficients:
##                   Estimate Std. Error t value   Pr(>|t|)  CI Lower  CI Upper
## (Intercept)       -999.389   109.4028  -9.135  5.618e-18 -1214.567 -784.2106
## Last_Purchase_Day   -4.672     0.4342 -10.760  1.744e-23    -5.526   -3.8184
## Age                 -3.513     1.6093  -2.183  2.971e-02    -6.678   -0.3478
## Average_Rating     519.273    14.6086  35.546 1.537e-117   490.540  548.0054
##                    DF
## (Intercept)       346
## Last_Purchase_Day 346
## Age               346
## Average_Rating    346
## 
## Multiple R-squared:  0.9096 ,    Adjusted R-squared:  0.9088 
## F-statistic:  1252 on 3 and 346 DF,  p-value: < 2.2e-16

#Explanation:

Last_Purchase_Day (-4.672):

For each additional day since the last purchase, Total Spend is estimated to decrease by 4.672 USD

Age (-3.513):

The coefficient for Age is -3.513, suggesting a negative relationship with Total Spend. It is statistically significant, indicating that a 1year increase in Age is associated with an estimated decrease in Total Spend by 3.513 USD

Average_Rating (519.273):

For each additional point in Average Rating, Total Spend is estimated to increase by 519.273 USD

Model Fit: Multiple R-squared (0.9096):

The model explains approximately 90.96% of the variance in Total Spend. This is a measure of how well the independent variables explain the variability in the dependent variable.

Adjusted R-squared (0.9088):

Adjusted for the number of predictors in the model.

F-statistic (1252): The F-statistic is highly significant with a very low p-value (< 2.2e-16), indicating that the overall model is statistically significant.

fit4 <-lm_robust (Total_Spend~Last_Purchase_Day + Age + Average_Rating +Gender,
                  se_type="HC1",
                  data = data)

summary (fit4)
## 
## Call:
## lm_robust(formula = Total_Spend ~ Last_Purchase_Day + Age + Average_Rating + 
##     Gender, data = data, se_type = "HC1")
## 
## Standard error type:  HC1 
## 
## Coefficients:
##                   Estimate Std. Error t value   Pr(>|t|)  CI Lower CI Upper  DF
## (Intercept)       -812.001   111.1370  -7.306  1.921e-12 -1030.593 -593.410 345
## Last_Purchase_Day   -4.975     0.3736 -13.317  6.198e-33    -5.709   -4.240 345
## Age                 -8.436     1.8655  -4.522  8.424e-06   -12.106   -4.767 345
## Average_Rating     527.840    13.0954  40.307 1.463e-132   502.083  553.597 345
## GenderMale         -96.754    12.6937  -7.622  2.436e-13  -121.721  -71.787 345
## 
## Multiple R-squared:  0.9211 ,    Adjusted R-squared:  0.9202 
## F-statistic:  1036 on 4 and 345 DF,  p-value: < 2.2e-16

#Explanation:

Last_Purchase_Day (-4.975):

For each additional day since the last purchase, Total Spend is estimated to decrease by 4.975 USD

Age (-8.436):

The coefficient for Age is -8.436, suggesting a negative relationship with Total Spend. It is statistically significant, indicating that a 1year increase in Age is associated with an estimated decrease in Total Spend by 8.436 USD

Average_Rating (527.840):

For each additional point in Average Rating, Total Spend is estimated to increase by 527.840 USD

GenderMale (-96.754):

This coefficient represents the estimated difference in Total Spend between male and female customers. In this case, male customers are estimated to spend 96.754 USD less compared to female customers, holding other variables constant.

Model Fit: Multiple R-squared (0.9211):

The model explains approximately 92.11% of the variance in Total Spend.

Adjusted R-squared (0.9202):

Adjusted for the number of predictors in the model.

F-statistic (1036): The F-statistic is highly significant with a very low p-value (< 2.2e-16), indicating that the overall model is statistically significant.

#Assesing which model is better
#Ho: The third model is better
#H1: the forth model is better


library (lmtest)
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
waldtest (fit3,fit4, test="F")
## Wald test
## 
## Model 1: Total_Spend ~ Last_Purchase_Day + Age + Average_Rating
## Model 2: Total_Spend ~ Last_Purchase_Day + Age + Average_Rating + Gender
##   Res.Df Df      F    Pr(>F)    
## 1    346                        
## 2    345  1 58.098 2.436e-13 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Based on p-value of2.436e-13 we rejevt null hypothesis and conclude that the forth model is better

#Conclusion: When customers give higher ratings, they tend to spend more. For each additional rating point, we see an increase of about 527.840 USD in their total spending. As time passes since a customer’s last purchase, their spending tends to decrease. For every extra day, we observe a decrease of 4.975 USD in total spending. Interestingly, male customers, on average, spend significantly less than female customers. This difference is substantial, with males spending about 96.754 USD less, keeping other factors constant. Age plays a role too. Older customers tend to spend less. With each additional year, we see a decrease of about 8.436 USD total spending. The overall model is strong, explaining around 92.11% of the variation in total spending. The statistical tests confirm that these results are not by chance.