#RQ1: Correlation

#Research Question 1: Is there a significant correlation between the “Total Spend” and “Average Rating” variables in the dataset, and does this correlation provide insights into customer behavior on the e-commerce platform? The hypothesis aims to investigate whether customers who spend more also tend to give higher average ratings, indicating a potential correlation between spending and satisfaction.

##Hypothesis:

Null Hypothesis (H0): There is no significant correlation between the “Total Spend” and “Average Rating” variables.

Alternative Hypothesis (H1): There is a significant correlation between the “Total Spend” and “Average Rating” variables.

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

#importing data
rawdata <- read_csv("~/Desktop/E-commerce Customer Behavior - Sheet1.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:

#Use the describe() function to obtain a comprehensive statistical summary
describe (rawdata)
## rawdata 
## 
##  11  Variables      350  Observations
## --------------------------------------------------------------------------------
## Customer ID 
##        n  missing distinct     Info     Mean      Gmd      .05      .10 
##      350        0      350        1    275.5      117    118.5    135.9 
##      .25      .50      .75      .90      .95 
##    188.2    275.5    362.8    415.1    432.6 
## 
## lowest : 101 102 103 104 105, highest: 446 447 448 449 450
## --------------------------------------------------------------------------------
## Gender 
##        n  missing distinct 
##      350        0        2 
##                         
## Value      Female   Male
## Frequency     175    175
## Proportion    0.5    0.5
## --------------------------------------------------------------------------------
## Age 
##        n  missing distinct     Info     Mean      Gmd      .05      .10 
##      350        0       16    0.993     33.6    5.516     27.0     28.0 
##      .25      .50      .75      .90      .95 
##     30.0     32.5     37.0     41.0     43.0 
##                                                                             
## Value         26    27    28    29    30    31    32    33    34    35    36
## Frequency      9    25    24    11    48    25    33    10    24    25    25
## Proportion 0.026 0.071 0.069 0.031 0.137 0.071 0.094 0.029 0.069 0.071 0.071
##                                         
## Value         37    38    41    42    43
## Frequency     24     9    24     9    25
## Proportion 0.069 0.026 0.069 0.026 0.071
## 
## For the frequency table, variable is rounded to the nearest 0
## --------------------------------------------------------------------------------
## City 
##        n  missing distinct 
##      350        0        6 
##                                                                   
## Value            Chicago       Houston   Los Angeles         Miami
## Frequency             58            58            59            58
## Proportion         0.166         0.166         0.169         0.166
##                                       
## Value           New York San Francisco
## Frequency             59            58
## Proportion         0.169         0.166
## --------------------------------------------------------------------------------
## Membership Type 
##        n  missing distinct 
##      350        0        3 
##                                
## Value      Bronze   Gold Silver
## Frequency     116    117    117
## Proportion  0.331  0.334  0.334
## --------------------------------------------------------------------------------
## Total Spend 
##        n  missing distinct     Info     Mean      Gmd      .05      .10 
##      350        0       76    0.999    845.4    403.4    430.8    450.8 
##      .25      .50      .75      .90      .95 
##    502.0    775.2   1160.6   1460.5   1490.1 
## 
## lowest : 410.8  420.8  430.5  430.8  440.5 , highest: 1480.1 1480.3 1490.1 1500.1 1520.1
## --------------------------------------------------------------------------------
## Items Purchased 
##        n  missing distinct     Info     Mean      Gmd      .05      .10 
##      350        0       15    0.992     12.6    4.652        7        8 
##      .25      .50      .75      .90      .95 
##        9       12       15       20       21 
##                                                                             
## Value          7     8     9    10    11    12    13    14    15    16    17
## Frequency     25    33    34    47    28    33    32    11    24    24     1
## Proportion 0.071 0.094 0.097 0.134 0.080 0.094 0.091 0.031 0.069 0.069 0.003
##                                   
## Value         18    19    20    21
## Frequency      9     6    19    24
## Proportion 0.026 0.017 0.054 0.069
## 
## For the frequency table, variable is rounded to the nearest 0
## --------------------------------------------------------------------------------
## Average Rating 
##        n  missing distinct     Info     Mean      Gmd      .05      .10 
##      350        0       20    0.996    4.019   0.6688      3.1      3.2 
##      .25      .50      .75      .90      .95 
##      3.5      4.1      4.5      4.8      4.9 
##                                                                             
## Value        3.0   3.1   3.2   3.3   3.4   3.5   3.6   3.7   3.8   3.9   4.0
## Frequency     12    17    10    25    19     9    24     1    24     8    18
## Proportion 0.034 0.049 0.029 0.071 0.054 0.026 0.069 0.003 0.069 0.023 0.051
##                                                                 
## Value        4.1   4.2   4.3   4.4   4.5   4.6   4.7   4.8   4.9
## Frequency     34    12    20     8    31    11    22    21    24
## Proportion 0.097 0.034 0.057 0.023 0.089 0.031 0.063 0.060 0.069
## 
## For the frequency table, variable is rounded to the nearest 0
## --------------------------------------------------------------------------------
## Discount Applied 
##        n  missing distinct 
##      350        0        2 
##                       
## Value      FALSE  TRUE
## Frequency    175   175
## Proportion   0.5   0.5
## --------------------------------------------------------------------------------
## Days Since Last Purchase 
##        n  missing distinct     Info     Mean      Gmd      .05      .10 
##      350        0       54    0.999    26.59    15.08    10.00    12.00 
##      .25      .50      .75      .90      .95 
##    15.00    23.00    38.00    47.00    53.55 
## 
## lowest :  9 10 11 12 13, highest: 59 60 61 62 63
## --------------------------------------------------------------------------------
## Satisfaction Level 
##        n  missing distinct 
##      348        2        3 
##                                               
## Value          Neutral   Satisfied Unsatisfied
## Frequency          107         125         116
## Proportion       0.307       0.359       0.333
## --------------------------------------------------------------------------------

Explanation of ststistical summary (only relevant variables):

Age: The age distribution is slightly right-skewed with a mean of 33.60 and a median of 32.5. The range spans from 17 to 43, indicating variability. The standard deviation of 4.87 implies that approximately 68% of the data falls within the range of 28.73 to 38.47.

Total Spend: The total spend distribution has a mean of 845.38 and meadian of 775.06. With a substantial standard deviation of 362.06, there is notable variability in customer spending. Approximately 68% of the data falls within the range of 483.32 to 1207.44, highlighting the spread of spending patterns among customers.

Items Purchased: The average number of items purchased is 12.60 and median 12.0, with a moderate standard deviation of 4.16. This indicates a degree of variability. The distribution of items purchased spans from 8.44 to 16.76, demonstrating the range where approximately 68% of the data lies.

Average Rating: The average rating is 4.02 and median is 4.1, with a relatively small standard deviation of 0.58. This suggests a degree of consistency in customer ratings. The distribution spans from 3.44 to 4.60, capturing the range where about 68% of the data falls.

Days Since Last Purchase: On average customers make a purchase approximately every 26.59 days, with a standard deviation of 13.44. This indicates a degree of variability in the frequency of customer transactions. The distribution spans from 13.15 (if down rounded 13 days) to 40.03 (if down rounded 40 days) days, showing the range where approximately 68% of the data lies.

#Exploring structure of dataset
str(rawdata)
## spc_tbl_ [350 × 11] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
##  $ Customer ID             : num [1:350] 101 102 103 104 105 106 107 108 109 110 ...
##  $ Gender                  : chr [1:350] "Female" "Male" "Female" "Male" ...
##  $ Age                     : num [1:350] 29 34 43 30 27 37 31 35 41 28 ...
##  $ City                    : chr [1:350] "New York" "Los Angeles" "Chicago" "San Francisco" ...
##  $ Membership Type         : chr [1:350] "Gold" "Silver" "Bronze" "Gold" ...
##  $ Total Spend             : num [1:350] 1120 780 511 1480 720 ...
##  $ Items Purchased         : num [1:350] 14 11 9 19 13 8 15 12 10 21 ...
##  $ Average Rating          : num [1:350] 4.6 4.1 3.4 4.7 4 3.1 4.5 4.2 3.6 4.8 ...
##  $ Discount Applied        : logi [1:350] TRUE FALSE TRUE FALSE TRUE FALSE ...
##  $ Days Since Last Purchase: num [1:350] 25 18 42 12 55 22 28 14 40 9 ...
##  $ Satisfaction Level      : chr [1:350] "Satisfied" "Neutral" "Unsatisfied" "Satisfied" ...
##  - attr(*, "spec")=
##   .. cols(
##   ..   `Customer ID` = col_double(),
##   ..   Gender = col_character(),
##   ..   Age = col_double(),
##   ..   City = col_character(),
##   ..   `Membership Type` = col_character(),
##   ..   `Total Spend` = col_double(),
##   ..   `Items Purchased` = col_double(),
##   ..   `Average Rating` = col_double(),
##   ..   `Discount Applied` = col_logical(),
##   ..   `Days Since Last Purchase` = col_double(),
##   ..   `Satisfaction Level` = col_character()
##   .. )
##  - attr(*, "problems")=<externalptr>
#rename column
colnames(rawdata)[8]="Average_Rating"
colnames(rawdata)[1]="ID"
colnames(rawdata)[6]="Total_Spend"
#dataset for correltion
data <- rawdata %>% 
  select(ID, Average_Rating, Total_Spend)
scatterplotMatrix(data [,-1], smooth=FALSE) #it is discerned that neither the "Average Rating" nor "Total Spend" data conforms to a normal distribution. In light of this observation, opting for the Spearman Rank Correlation is advisable. Spearman's method, being less susceptible to outliers and not contingent on the assumption of normal distribution, aligns with the non-normal nature of the data and is considered a more suitable approach for the correlation analysis in this context.

#Implementation of this test serves the purpose of demonstrating proficiency and understanding of the testing methodology.

#Null Hypothesis (H0): The population correlation coefficient between the two variables is equal to zero.
#Alternative Hypothesis (H1): The population correlation coefficient between the two variables is not equal to zero.

rcorr(as.matrix(data[,-1],
                type ="pearson"))
##                Average_Rating Total_Spend
## Average_Rating           1.00        0.94
## Total_Spend              0.94        1.00
## 
## n= 350 
## 
## 
## P
##                Average_Rating Total_Spend
## Average_Rating                 0         
## Total_Spend     0

The Pearson correlation coefficient between “Average_Rating” and “Total_Spend” is 0.94. This suggests a strong positive correlation between these two variables. A correlation coefficient close to 1 indicates a strong positive linear relationship, meaning that as one variable increases, the other tends to increase as well.All the p-values are 0. This typically means that the correlation coefficients are statistically significant.

#Performing the Spearman correlation test is rooted in the presence of a non-normal distribution and the potential influence of outliers in the data.

#H0: There is no [monotonic] association between the two variables in the population
#H1: There is no [monotonic] association between the two variables in the population

rcorr(as.matrix(data[,-1],
                type ="spearman"))
##                Average_Rating Total_Spend
## Average_Rating           1.00        0.94
## Total_Spend              0.94        1.00
## 
## n= 350 
## 
## 
## P
##                Average_Rating Total_Spend
## Average_Rating                 0         
## Total_Spend     0

#Conclusion: The correlation between “Total_Spend” and “Average_Rating” is 0.94.This values indicates a strong positive monotonic relationship between the two variables. This implies that as one variable increases, the other tends to increase as well, and vice versa. The fact that the correlations are close to 1 suggests a relatively strong association.All the p-values are reported as 0, which means that the correlations are statistically significant. Given the correlation results obtained from the Spearman rank correlation test, we reject the null hypothesis (H0) that there is no significant correlation between the “Total Spend” and “Average Rating” variables. The alternative hypothesis (H1) is supported, indicating a statistically significant and positive correlation between these two variables.In practical terms, it implies that there is a positive association between the amount spent and the average rating; as customers spend more, there is a trend of higher ratings, and as spending decreases, ratings tend to be lower.

#RQ2: Pearson Chi2

#Research Question: Is there a significant association between “Gender” and “Membership Type” among the customers on the e-commerce platform?

##Hypothesis:

Null Hypothesis (H0): There is no significant association between “Gender” and “Membership Type” variables.

Alternative Hypothesis (H1): There is a significant association between “Gender” and “Membership Type” variables.

#rename column
colnames(rawdata)[5]="Membership_type"
#Random data sampling
set.seed(1)
mydata <- rawdata[sample(nrow(data),150),] #ramdomly selecting 150 samples out of 350
#dataset for our research question
Catdata <- mydata %>% 
  select(ID, Membership_type, Gender)
cont_table <- as.data.frame(table(Catdata$Membership_type, mydata$Gender))
colnames(cont_table) <- c("Membership", "Gender", "Frequency")
cont_table
##   Membership Gender Frequency
## 1     Bronze Female        51
## 2       Gold Female        27
## 3     Silver Female         0
## 4     Bronze   Male         0
## 5       Gold   Male        27
## 6     Silver   Male        45

#Interpretation:

Bronze Category:

Females (116 occurrences): It appears that there are 51 females with Bronze membership. Males (0 occurrences): There are no males with Bronze membership.

Gold Category:

Females (58 occurrences): There are 27 females with Gold membership. Males (59 occurrences): There are 27 males with Gold membership.

Silver Category:

Females (1 occurrence): There are no female with Silver membership. Males (116 occurrences): There are 45 males with Silver membership.

### Person's Chi2 test
#H0:: There is no association between two categorical variables
#H1: There is association between two categorical variables

results <- chisq.test(Catdata$Membership_type, mydata$Gender, 
                      correct = TRUE)

results
## 
##  Pearson's Chi-squared test
## 
## data:  Catdata$Membership_type and mydata$Gender
## X-squared = 95.913, df = 2, p-value < 2.2e-16
addmargins(results$observed)
##                        mydata$Gender
## Catdata$Membership_type Female Male Sum
##                  Bronze     51    0  51
##                  Gold       27   27  54
##                  Silver      0   45  45
##                  Sum        78   72 150
round(results$expected, 2)
##                        mydata$Gender
## Catdata$Membership_type Female  Male
##                  Bronze  26.52 24.48
##                  Gold    28.08 25.92
##                  Silver  23.40 21.60
round(results$res, 2)
##                        mydata$Gender
## Catdata$Membership_type Female  Male
##                  Bronze   4.75 -4.95
##                  Gold    -0.20  0.21
##                  Silver  -4.84  5.03

Test Statistics: The X-squared value is 95.913 with 2 degrees of freedom, and the p-value is practically zero. This indicates a highly significant association between “Membership_type” and “Gender.”

Contingency Table: The observed frequencies show that there are differences in counts across the categories.

Expected Frequencies: These are the frequencies expected if there is no association between the variables. Differences between observed and expected frequencies contribute to the X-squared value.

Pearson Residuals: These standardized residuals indicate how far each observed count is from the expected count. Large positive or negative values suggest a significant contribution to the association.For “Bronze” membership type:The positive residual for “Female” (4.75) suggests a higher observed frequency than expected.The negative residual for “Male” (-4.95) indicates a lower observed frequency than expected.

For “Gold” membership type:Residuals suggest a roughly balanced contribution from both genders.

For “Silver” membership type: The negative residual for “Female” (-4.84) indicates a lower observed frequency than expected.The positive residual for “Male” (5.03) suggests a higher observed frequency than expected.

addmargins(round(prop.table(results$observed), 3)) #The proportion of females in the "Bronze" category is 0.34, meaning that 34% of the total sample consists of females in the "Bronze" category, 18% in "Gold" category and none in "Silver". The proportion of males in the "Bronze" category is o, meaning that 0% of the total sample consists of males in the "Bronze" category, 18% in "Gold" category and 30% of males in "Silver" category. 
##                        mydata$Gender
## Catdata$Membership_type Female Male  Sum
##                  Bronze   0.34 0.00 0.34
##                  Gold     0.18 0.18 0.36
##                  Silver   0.00 0.30 0.30
##                  Sum      0.52 0.48 1.00
addmargins(round(prop.table(results$observed, 1), 3), 2) #"Bronze" category, the proportion of females is 1.0, indicating that all individuals in the "Bronze" category are females and all male individuals are in Silver category
##                        mydata$Gender
## Catdata$Membership_type Female Male Sum
##                  Bronze    1.0  0.0 1.0
##                  Gold      0.5  0.5 1.0
##                  Silver    0.0  1.0 1.0
addmargins(round(prop.table(results$observed, 2), 3), 1) #For females, the proportion in the "Bronze" category is 0.654, meaning that 65.4% of females fall into the "Bronze" category and 62.5% of males fall in "Silver" category.
##                        mydata$Gender
## Catdata$Membership_type Female  Male
##                  Bronze  0.654 0.000
##                  Gold    0.346 0.375
##                  Silver  0.000 0.625
##                  Sum     1.000 1.000
library(DescTools)
## 
## Attaching package: 'DescTools'
## The following objects are masked from 'package:Hmisc':
## 
##     %nin%, Label, Mean, Quantile
## The following objects are masked from 'package:psych':
## 
##     AUC, ICC, SD
## The following object is masked from 'package:car':
## 
##     Recode
CramerV(Catdata$Membership_type, Catdata$Gender)#With a Cramer's V of 0.7996393, there is a very strong association between "Membership_type" and "Gender" in dataset.
## [1] 0.7996393
#Since non of expected frequencies are not less than 1, we could finish our analysis on Pearson Chi2, the fisher test performed to demonstrate knowledge or theorie.

#Null Hypothesis (H0):There is no association or dependency between "Membership_type" and "Gender" in the population; the distribution of these categories is independent.

#Alternative Hypothesis (H1): There is a significant association or dependency between "Membership_type" and "Gender" in the population; the distribution of these categories is not independent.

fisher.test(Catdata$Membership_type, Catdata$Gender) # The result of Fisher's Exact Test for Count Data indicates a p-value less than 2.2e-16. Therefore, we reject the null hypothesis, suggesting that there is a significant association or dependency between "Membership_type" and "Gender" in the population. The low p-value implies that the observed distribution of these categories is not independent, providing evidence in favor of the alternative hypothesis.
## 
##  Fisher's Exact Test for Count Data
## 
## data:  Catdata$Membership_type and Catdata$Gender
## p-value < 2.2e-16
## alternative hypothesis: two.sided

#Conclusion: Based on the very low p-value, you reject the null hypothesis that there is no association between “Membership_type” and “Gender.” The observed differences in counts are statistically significant. The Pearson residuals help identify which categories contribute the most to this association. The effect size, as indicated by Cramer’s V, reinforces the statistical significance observed in the Chi-squared test. The large value of Cramer’s V suggests a substantial association between “Membership_type” and “Gender,” emphasizing the practical significance of the relationship beyond mere statistical significance.