Assignment 3: Prac0cal Group Assignment Based on Case Studies (80 marks, 40%

# Load necessary libraries
library(ggplot2)
Warning: package 'ggplot2' was built under R version 4.3.3
library(dplyr)

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
# Set the path to the CSV file
file_path <- read.csv(file.choose())

# Read the CSV file
brand_data <- file_path

# Display the structure of the dataset
str(brand_data)
'data.frame':   1000 obs. of  10 variables:
 $ performance  : int  2 1 2 1 1 2 1 2 2 3 ...
 $ leadership   : int  4 1 3 6 1 8 1 1 1 1 ...
 $ productLatest: int  8 4 5 10 5 9 5 7 8 9 ...
 $ fun          : int  8 7 9 8 8 5 7 5 10 8 ...
 $ serious      : int  2 1 2 3 1 3 1 2 1 1 ...
 $ bargain      : int  9 1 9 4 9 8 5 8 7 3 ...
 $ bestValue    : int  7 1 5 5 9 7 1 7 7 3 ...
 $ trendiness   : int  4 2 1 2 1 1 1 7 5 4 ...
 $ repeatBuy    : int  6 2 6 1 1 2 1 1 1 1 ...
 $ name         : chr  "a" "a" "a" "a" ...
# Summary statistics of the dataset
summary(brand_data)
  performance       leadership     productLatest         fun        
 Min.   : 1.000   Min.   : 1.000   Min.   : 1.000   Min.   : 1.000  
 1st Qu.: 1.000   1st Qu.: 2.000   1st Qu.: 4.000   1st Qu.: 4.000  
 Median : 4.000   Median : 4.000   Median : 7.000   Median : 6.000  
 Mean   : 4.488   Mean   : 4.417   Mean   : 6.195   Mean   : 6.068  
 3rd Qu.: 7.000   3rd Qu.: 6.000   3rd Qu.: 9.000   3rd Qu.: 8.000  
 Max.   :10.000   Max.   :10.000   Max.   :10.000   Max.   :10.000  
    serious          bargain         bestValue        trendiness   
 Min.   : 1.000   Min.   : 1.000   Min.   : 1.000   Min.   : 1.00  
 1st Qu.: 2.000   1st Qu.: 2.000   1st Qu.: 2.000   1st Qu.: 3.00  
 Median : 4.000   Median : 4.000   Median : 4.000   Median : 5.00  
 Mean   : 4.323   Mean   : 4.259   Mean   : 4.337   Mean   : 5.22  
 3rd Qu.: 6.000   3rd Qu.: 6.000   3rd Qu.: 6.000   3rd Qu.: 7.00  
 Max.   :10.000   Max.   :10.000   Max.   :10.000   Max.   :10.00  
   repeatBuy          name          
 Min.   : 1.000   Length:1000       
 1st Qu.: 1.000   Class :character  
 Median : 3.000   Mode  :character  
 Mean   : 3.727                     
 3rd Qu.: 5.000                     
 Max.   :10.000                     
# Generate a correlation matrix
cor_matrix <- cor(brand_data[ ,1:9])
print(cor_matrix)
               performance  leadership productLatest        fun      serious
performance    1.000000000  0.50020206  -0.122445813 -0.2563323  0.359172206
leadership     0.500202058  1.00000000   0.026890447 -0.2903576  0.571215126
productLatest -0.122445813  0.02689045   1.000000000  0.2451545  0.009951527
fun           -0.256332316 -0.29035764   0.245154457  1.0000000 -0.281097443
serious        0.359172206  0.57121513   0.009951527 -0.2810974  1.000000000
bargain        0.057129372  0.03309405  -0.254419016 -0.0665528 -0.002655590
bestValue      0.101946104  0.11831017  -0.342713717 -0.1452185  0.023756556
trendiness     0.008733494  0.06651244   0.627627667  0.1279736  0.121009377
repeatBuy      0.306658801  0.20870036  -0.397180225 -0.2371607  0.180702720
                  bargain   bestValue   trendiness  repeatBuy
performance    0.05712937  0.10194610  0.008733494  0.3066588
leadership     0.03309405  0.11831017  0.066512436  0.2087004
productLatest -0.25441902 -0.34271372  0.627627667 -0.3971802
fun           -0.06655280 -0.14521849  0.127973639 -0.2371607
serious       -0.00265559  0.02375656  0.121009377  0.1807027
bargain        1.00000000  0.73962672 -0.350533746  0.4673811
bestValue      0.73962672  1.00000000 -0.434534536  0.5059617
trendiness    -0.35053375 -0.43453454  1.000000000 -0.2982462
repeatBuy      0.46738109  0.50596166 -0.298246195  1.0000000
# Plot correlation matrix
corrplot::corrplot(cor_matrix, method = "circle")

# Create histograms for each numeric column
for (col in names(brand_data)[1:9]) {
  ggplot(brand_data, aes_string(col)) + 
    geom_histogram(binwidth = 1, fill = "blue", color = "black") + 
    labs(title = paste("Histogram of", col), x = col, y = "Frequency") +
    theme_minimal()
}
Warning: `aes_string()` was deprecated in ggplot2 3.0.0.
ℹ Please use tidy evaluation idioms with `aes()`.
ℹ See also `vignette("ggplot2-in-packages")` for more information.
# Boxplot for all numeric columns
melted_data <- reshape2::melt(brand_data, id.vars = "name")
ggplot(melted_data, aes(x = variable, y = value)) +
  geom_boxplot() +
  labs(title = "Boxplot of All Numeric Columns", x = "Attributes", y = "Values") +
  theme_minimal()

Perform relevant pre-processing to con0nue with the unsupervised and supervised

learning methods men0oned in the next few sec0ons.

# Load necessary libraries
library(dplyr)
library(caret)
Loading required package: lattice
library(ggplot2)
library(reshape2)



# Display the structure of the dataset
str(brand_data)
'data.frame':   1000 obs. of  10 variables:
 $ performance  : int  2 1 2 1 1 2 1 2 2 3 ...
 $ leadership   : int  4 1 3 6 1 8 1 1 1 1 ...
 $ productLatest: int  8 4 5 10 5 9 5 7 8 9 ...
 $ fun          : int  8 7 9 8 8 5 7 5 10 8 ...
 $ serious      : int  2 1 2 3 1 3 1 2 1 1 ...
 $ bargain      : int  9 1 9 4 9 8 5 8 7 3 ...
 $ bestValue    : int  7 1 5 5 9 7 1 7 7 3 ...
 $ trendiness   : int  4 2 1 2 1 1 1 7 5 4 ...
 $ repeatBuy    : int  6 2 6 1 1 2 1 1 1 1 ...
 $ name         : chr  "a" "a" "a" "a" ...
# Check for missing values
sum(is.na(brand_data))
[1] 0
# Handle missing values (if any)
# For simplicity, we will remove rows with missing values
brand_data <- na.omit(brand_data)

# Encode categorical variables (if any)
# In this case, 'name' is a categorical variable
# Convert 'name' to a factor
brand_data$name <- as.factor(brand_data$name)

# Normalize the numeric data
numeric_columns <- names(brand_data)[1:9]
preProc <- preProcess(brand_data[, numeric_columns], method = c("center", "scale"))
brand_data[, numeric_columns] <- predict(preProc, brand_data[, numeric_columns])

# Verify normalization
summary(brand_data)
  performance        leadership      productLatest          fun          
 Min.   :-1.0888   Min.   :-1.3100   Min.   :-1.6878   Min.   :-1.84677  
 1st Qu.:-1.0888   1st Qu.:-0.9266   1st Qu.:-0.7131   1st Qu.:-0.75358  
 Median :-0.1523   Median :-0.1599   Median : 0.2615   Median :-0.02478  
 Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.00000  
 3rd Qu.: 0.7842   3rd Qu.: 0.6069   3rd Qu.: 0.9113   3rd Qu.: 0.70402  
 Max.   : 1.7206   Max.   : 2.1404   Max.   : 1.2362   Max.   : 1.43281  
                                                                         
    serious           bargain           bestValue         trendiness      
 Min.   :-1.1961   Min.   :-1.22196   Min.   :-1.3912   Min.   :-1.53897  
 1st Qu.:-0.8362   1st Qu.:-0.84701   1st Qu.:-0.9743   1st Qu.:-0.80960  
 Median :-0.1163   Median :-0.09711   Median :-0.1405   Median :-0.08023  
 Mean   : 0.0000   Mean   : 0.00000   Mean   : 0.0000   Mean   : 0.00000  
 3rd Qu.: 0.6036   3rd Qu.: 0.65279   3rd Qu.: 0.6933   3rd Qu.: 0.64914  
 Max.   : 2.0434   Max.   : 2.15258   Max.   : 2.3610   Max.   : 1.74319  
                                                                          
   repeatBuy            name    
 Min.   :-1.0717   a      :100  
 1st Qu.:-1.0717   b      :100  
 Median :-0.2857   c      :100  
 Mean   : 0.0000   d      :100  
 3rd Qu.: 0.5003   e      :100  
 Max.   : 2.4652   f      :100  
                   (Other):400  
# Visualize the normalized data
melted_data <- melt(brand_data, id.vars = "name")
ggplot(melted_data, aes(x = variable, y = value)) +
  geom_boxplot() +
  labs(title = "Boxplot of Normalized Numeric Columns", x = "Attributes", y = "Values") +
  theme_minimal()

# Save the preprocessed data to a new CSV file
write.csv(brand_data, "preprocessed_brand_data.csv", row.names = FALSE)

Perform an appropriate unsupervised learning technique (only from the ones you have

learned in this course) to group respondents according to the brand percep0on variables. Describe the groups of respondents according to their ra0ng of the percep0on variables and their likelihood to buy the brand again.

# Load necessary libraries
library(dplyr)
library(ggplot2)
library(caret)
library(cluster)
Warning: package 'cluster' was built under R version 4.3.3
library(factoextra)
Warning: package 'factoextra' was built under R version 4.3.3
Welcome! Want to learn more? See two factoextra-related books at https://goo.gl/ve3WBa
# Normalize the numeric data
numeric_columns <- names(brand_data)[1:9]
preProc <- preProcess(brand_data[, numeric_columns], method = c("center", "scale"))
brand_data[, numeric_columns] <- predict(preProc, brand_data[, numeric_columns])

# Determine the optimal number of clusters using the elbow method
set.seed(123)
fviz_nbclust(brand_data[, numeric_columns], kmeans, method = "wss")

# Perform K-means clustering with the chosen number of clusters
set.seed(123)
kmeans_result <- kmeans(brand_data[, numeric_columns], centers = 3, nstart = 25)

# Add the cluster assignments to the dataset
brand_data$cluster <- as.factor(kmeans_result$cluster)

# Summarize the clusters
cluster_summary <- brand_data %>%
  group_by(cluster) %>%
  summarise(across(everything(), mean))
Warning: There were 3 warnings in `summarise()`.
The first warning was:
ℹ In argument: `across(everything(), mean)`.
ℹ In group 1: `cluster = 1`.
Caused by warning in `mean.default()`:
! argument is not numeric or logical: returning NA
ℹ Run `dplyr::last_dplyr_warnings()` to see the 2 remaining warnings.
# Print the cluster summary
print(cluster_summary)
# A tibble: 3 × 11
  cluster performance leadership productLatest    fun serious bargain bestValue
  <fct>         <dbl>      <dbl>         <dbl>  <dbl>   <dbl>   <dbl>     <dbl>
1 1             0.818     1.09           0.275 -0.702   1.08   -0.234    -0.179
2 2             0.226    -0.0417        -1.09  -0.237  -0.128   0.990     1.13 
3 3            -0.536    -0.551          0.378  0.481  -0.504  -0.354    -0.448
# ℹ 3 more variables: trendiness <dbl>, repeatBuy <dbl>, name <dbl>
# Visualize the clusters
fviz_cluster(kmeans_result, data = brand_data[, numeric_columns])

# Analyze the likelihood to buy the brand again for each cluster
repeat_buy_summary <- brand_data %>%
  group_by(cluster) %>%
  summarise(mean_repeatBuy = mean(repeatBuy))

# Print the repeat buy summary
print(repeat_buy_summary)
# A tibble: 3 × 2
  cluster mean_repeatBuy
  <fct>            <dbl>
1 1               0.0606
2 2               1.16  
3 3              -0.587 

perform an appropriate unsupervised learning

technique (only from the ones you have learned in this course) to reduce the dimension of the brand percep0on variables into a smaller number of components. Describe the components based on the variables used to combine them.

library(factoextra)
library(ggplot2)
library(corrplot)
corrplot 0.92 loaded
library(dplyr)
library(tidyr)
Warning: package 'tidyr' was built under R version 4.3.3

Attaching package: 'tidyr'
The following object is masked from 'package:reshape2':

    smiths
library(tibble)

# Handle missing values (if any)
brand_data <- na.omit(brand_data)

# Select only the numeric columns for PCA
brand_numeric <- brand_data %>%
  select(performance, leadership, productLatest, fun, serious, bargain, bestValue, trendiness, repeatBuy)

# Normalize the numeric data
normalized_data <- scale(brand_numeric)

# Perform PCA
pca_model <- prcomp(normalized_data, center = TRUE, scale. = TRUE)

# Summary of PCA
pca_summary <- summary(pca_model)
print(pca_summary)
Importance of components:
                         PC1    PC2    PC3    PC4     PC5     PC6     PC7
Standard deviation     1.726 1.4479 1.0389 0.8528 0.79846 0.73133 0.62458
Proportion of Variance 0.331 0.2329 0.1199 0.0808 0.07084 0.05943 0.04334
Cumulative Proportion  0.331 0.5640 0.6839 0.7647 0.83554 0.89497 0.93831
                           PC8     PC9
Standard deviation     0.55861 0.49310
Proportion of Variance 0.03467 0.02702
Cumulative Proportion  0.97298 1.00000
# Scree plot to determine the number of components
scree_plot <- fviz_eig(pca_model, addlabels = TRUE)
print(scree_plot)

# Get the PCA loadings
pca_loadings <- pca_model$rotation

# Print the PCA loadings
print(pca_loadings)
                     PC1         PC2         PC3         PC4         PC5
performance    0.2374679  0.41991179  0.03854006 -0.52630873 -0.46793435
leadership     0.2058257  0.52381901 -0.09512739 -0.08923461  0.29452974
productLatest -0.3703806  0.20145317 -0.53273054  0.21410754 -0.10586676
fun           -0.2510601 -0.25037973 -0.41781346 -0.75063952  0.33149429
serious        0.1597402  0.51047254 -0.04067075  0.09893394  0.55515540
bargain        0.3991731 -0.21849698 -0.48989756  0.16734345  0.01257429
bestValue      0.4474562 -0.18980822 -0.36924507  0.15118500  0.06327757
trendiness    -0.3510292  0.31849032 -0.37090530  0.16764432 -0.36649697
repeatBuy      0.4390184  0.01509832 -0.12461593 -0.13031231 -0.35568769
                     PC6          PC7         PC8         PC9
performance    0.3370676 -0.364179109 -0.14444718 -0.05223384
leadership     0.2968860  0.613674301  0.28766118  0.17889453
productLatest  0.1742059  0.185480310 -0.64290436 -0.05750244
fun           -0.1405367  0.007114761  0.07461259 -0.03153306
serious       -0.3924874 -0.445302862 -0.18354764 -0.09072231
bargain        0.1393966 -0.288264900  0.05789194  0.64720849
bestValue      0.2195327 -0.017163011  0.14829295 -0.72806108
trendiness    -0.2658186 -0.153572108  0.61450289 -0.05907022
repeatBuy     -0.6751400  0.388656160 -0.20210688  0.01720236
# Visualize the PCA loadings
loadings_plot <- corrplot(pca_loadings, is.corr = FALSE)

print(loadings_plot)
$corr
                     PC1         PC2         PC3        PC4         PC5
performance    0.3163541  0.55940538  0.05134297 -0.7011471 -0.62338091
leadership     0.2742004  0.69783030 -0.12672846 -0.1188781  0.39237174
productLatest -0.4934201  0.26837539 -0.70970223  0.2852335 -0.14103541
fun           -0.3344616 -0.33355521 -0.55660999 -1.0000000  0.44161583
serious        0.2128055  0.68005018 -0.05418147  0.1317995  0.73957657
bargain        0.5317773 -0.29108111 -0.65264024  0.2229345  0.01675144
bestValue      0.5961000 -0.25286201 -0.49190731  0.2014083  0.08429821
trendiness    -0.4676402  0.42429197 -0.49411906  0.2233353 -0.48824629
repeatBuy      0.5848592  0.02011394 -0.16601302 -0.1736017 -0.47384620
                     PC6          PC7         PC8         PC9
performance    0.4490405 -0.485158452 -0.19243215 -0.06958578
leadership     0.3955107  0.817535290  0.38322146  0.23832282
productLatest  0.2320766  0.247096381 -0.85647549 -0.07660460
fun           -0.1872226  0.009478266  0.09939870 -0.04200826
serious       -0.5228707 -0.593231302 -0.24452169 -0.12086002
bargain        0.1857038 -0.384025742  0.07712349  0.86220944
bestValue      0.2924609 -0.022864518  0.19755548 -0.96992105
trendiness    -0.3541228 -0.204588358  0.81863914 -0.07869320
repeatBuy     -0.8994197  0.517766714 -0.26924626  0.02291694

$corrPos
   xName         yName x y         corr
1    PC1   performance 1 9  0.316354078
2    PC1    leadership 1 8  0.274200406
3    PC1 productLatest 1 7 -0.493420105
4    PC1           fun 1 6 -0.334461629
5    PC1       serious 1 5  0.212805473
6    PC1       bargain 1 4  0.531777306
7    PC1     bestValue 1 3  0.596099956
8    PC1    trendiness 1 2 -0.467640236
9    PC1     repeatBuy 1 1  0.584859184
10   PC2   performance 2 9  0.559405378
11   PC2    leadership 2 8  0.697830302
12   PC2 productLatest 2 7  0.268375386
13   PC2           fun 2 6 -0.333555213
14   PC2       serious 2 5  0.680050178
15   PC2       bargain 2 4 -0.291081106
16   PC2     bestValue 2 3 -0.252862013
17   PC2    trendiness 2 2  0.424291968
18   PC2     repeatBuy 2 1  0.020113944
19   PC3   performance 3 9  0.051342965
20   PC3    leadership 3 8 -0.126728462
21   PC3 productLatest 3 7 -0.709702226
22   PC3           fun 3 6 -0.556609995
23   PC3       serious 3 5 -0.054181468
24   PC3       bargain 3 4 -0.652640242
25   PC3     bestValue 3 3 -0.491907313
26   PC3    trendiness 3 2 -0.494119063
27   PC3     repeatBuy 3 1 -0.166013018
28   PC4   performance 4 9 -0.701147101
29   PC4    leadership 4 8 -0.118878106
30   PC4 productLatest 4 7  0.285233501
31   PC4           fun 4 6 -1.000000000
32   PC4       serious 4 5  0.131799529
33   PC4       bargain 4 4  0.222934501
34   PC4     bestValue 4 3  0.201408265
35   PC4    trendiness 4 2  0.223335322
36   PC4     repeatBuy 4 1 -0.173601719
37   PC5   performance 5 9 -0.623380909
38   PC5    leadership 5 8  0.392371743
39   PC5 productLatest 5 7 -0.141035414
40   PC5           fun 5 6  0.441615827
41   PC5       serious 5 5  0.739576565
42   PC5       bargain 5 4  0.016751439
43   PC5     bestValue 5 3  0.084298209
44   PC5    trendiness 5 2 -0.488246293
45   PC5     repeatBuy 5 1 -0.473846205
46   PC6   performance 6 9  0.449040534
47   PC6    leadership 6 8  0.395510737
48   PC6 productLatest 6 7  0.232076577
49   PC6           fun 6 6 -0.187222632
50   PC6       serious 6 5 -0.522870729
51   PC6       bargain 6 4  0.185703796
52   PC6     bestValue 6 3  0.292460920
53   PC6    trendiness 6 2 -0.354122798
54   PC6     repeatBuy 6 1 -0.899419696
55   PC7   performance 7 9 -0.485158452
56   PC7    leadership 7 8  0.817535290
57   PC7 productLatest 7 7  0.247096381
58   PC7           fun 7 6  0.009478266
59   PC7       serious 7 5 -0.593231302
60   PC7       bargain 7 4 -0.384025742
61   PC7     bestValue 7 3 -0.022864518
62   PC7    trendiness 7 2 -0.204588358
63   PC7     repeatBuy 7 1  0.517766714
64   PC8   performance 8 9 -0.192432148
65   PC8    leadership 8 8  0.383221462
66   PC8 productLatest 8 7 -0.856475494
67   PC8           fun 8 6  0.099398696
68   PC8       serious 8 5 -0.244521685
69   PC8       bargain 8 4  0.077123488
70   PC8     bestValue 8 3  0.197555481
71   PC8    trendiness 8 2  0.818639137
72   PC8     repeatBuy 8 1 -0.269246256
73   PC9   performance 9 9 -0.069585784
74   PC9    leadership 9 8  0.238322817
75   PC9 productLatest 9 7 -0.076604600
76   PC9           fun 9 6 -0.042008261
77   PC9       serious 9 5 -0.120860018
78   PC9       bargain 9 4  0.862209445
79   PC9     bestValue 9 3 -0.969921054
80   PC9    trendiness 9 2 -0.078693198
81   PC9     repeatBuy 9 1  0.022916936

$arg
$arg$type
[1] "full"
# Get the PCA scores
pca_scores <- as.data.frame(pca_model$x)

# Add PCA scores to the original data
brand_data <- cbind(brand_data, pca_scores)

# Describe the components
components_summary <- as_tibble(pca_loadings, rownames = "Variable") %>%
  pivot_longer(cols = -Variable, names_to = "Component", values_to = "Loading") %>%
  group_by(Component) %>%
  top_n(3, wt = abs(Loading)) %>%
  arrange(Component, desc(abs(Loading)))

# Print the components summary
print(components_summary)
# A tibble: 27 × 3
# Groups:   Component [9]
   Variable      Component Loading
   <chr>         <chr>       <dbl>
 1 bestValue     PC1         0.447
 2 repeatBuy     PC1         0.439
 3 bargain       PC1         0.399
 4 leadership    PC2         0.524
 5 serious       PC2         0.510
 6 performance   PC2         0.420
 7 productLatest PC3        -0.533
 8 bargain       PC3        -0.490
 9 fun           PC3        -0.418
10 fun           PC4        -0.751
# ℹ 17 more rows
# Visualize the PCA scores
pca_plot <- ggplot(brand_data, aes(x = PC1, y = PC2, color = name)) +
  geom_point() +
  labs(title = "PCA of Brand Perception Variables", x = "PC1", y = "PC2") +
  theme_minimal()

print(pca_plot)

Obtain and interpret a descrip0ve analysis table or graph to compare the scores of the

components obtained in (iii) by groups obtained in (ii). Compare your interpreta0on of the results in (iv) with the interpreta0on in (iii)

::: {.cell}

```{.r .cell-code}
library(factoextra)
library(ggplot2)
library(corrplot)
library(dplyr)
library(tidyr)
library(tibble)
# Handle missing values (if any)
brand_data <- na.omit(brand_data)

# Select only the numeric columns for PCA
brand_numeric <- brand_data %>%
  select(performance, leadership, productLatest, fun, serious, bargain, bestValue, trendiness, repeatBuy)

# Normalize the numeric data
normalized_data <- scale(brand_numeric)

# Perform PCA
pca_model <- prcomp(normalized_data, center = TRUE, scale. = TRUE)

# Get the PCA scores
pca_scores <- as.data.frame(pca_model$x)

# Ensure unique column names for PCA scores
colnames(pca_scores) <- paste0("PC", 1:ncol(pca_scores))

# Remove any existing PCA score columns if they exist
brand_data <- brand_data %>%
  select(-starts_with("PC"))

# Add PCA scores to the original data
brand_data <- cbind(brand_data, pca_scores)

# Perform K-means clustering with 3 clusters (as an example)
set.seed(123)
kmeans_result <- kmeans(normalized_data, centers = 3, nstart = 25)

# Add the cluster assignment to the original data
brand_data$cluster <- as.factor(kmeans_result$cluster)

# Descriptive analysis of component scores by clusters
component_means <- brand_data %>%
  group_by(cluster) %>%
  summarise(across(starts_with("PC"), list(mean = mean, sd = sd)))

# Print the descriptive analysis table
print(component_means)

# Visualize the PCA scores by clusters
pca_plot <- ggplot(brand_data, aes(x = PC1, y = PC2, color = cluster)) +
  geom_point() +
  labs(title = "PCA of Brand Perception Variables by Cluster", x = "PC1", y = "PC2") +
  theme_minimal()

print(pca_plot)

# Visualize the component scores by clusters
component_scores_plot <- brand_data %>%
  pivot_longer(cols = starts_with("PC"), names_to = "Component", values_to = "Score") %>%
  ggplot(aes(x = Component, y = Score, fill = cluster)) +
  geom_boxplot() +
  labs(title = "Component Scores by Cluster", x = "Component", y = "Score") +
  theme_minimal()

print(component_scores_plot)
```
:::

After conducting the

unsupervised learning method in (iii), conduct a supervised learning method to determine the factors influencing repeatBuy. To develop your supervised learning model, you do not need to split your data into training and tes0ng as you are required to use the en0re dataset to develop your model. Your independent variables should consist of the components developed from the unsupervised learning in (iii), the grouping variable obtained from the unsupervised learning in (ii) and the brand names. Interpret the influence of all the independent variables on repeatBuy.

library(factoextra)
library(ggplot2)
library(corrplot)
library(dplyr)
library(tidyr)
library(tibble)
library(broom)


# Handle missing values (if any)
brand_data <- na.omit(brand_data)

# Select only the numeric columns for PCA
brand_numeric <- brand_data %>%
  select(performance, leadership, productLatest, fun, serious, bargain, bestValue, trendiness, repeatBuy)

# Normalize the numeric data
normalized_data <- scale(brand_numeric)

# Perform PCA
pca_model <- prcomp(normalized_data, center = TRUE, scale. = TRUE)

# Get the PCA scores
pca_scores <- as.data.frame(pca_model$x)

# Ensure unique column names for PCA scores
colnames(pca_scores) <- paste0("PC", 1:ncol(pca_scores))

# Remove any existing PCA score columns if they exist
brand_data <- brand_data %>%
  select(-starts_with("PC"))

# Add PCA scores to the original data
brand_data <- cbind(brand_data, pca_scores)

# Perform K-means clustering with 3 clusters (as an example)
set.seed(123)
kmeans_result <- kmeans(normalized_data, centers = 3, nstart = 25)

# Add the cluster assignment to the original data
brand_data$cluster <- as.factor(kmeans_result$cluster)

# Fit a linear regression model to determine factors influencing repeatBuy
lm_model <- lm(repeatBuy ~ PC1 + PC2 + PC3 + PC4 + PC5 + PC6 + PC7 + PC8 + PC9 + cluster + name, data = brand_data)

# Summarize the linear model
lm_summary <- summary(lm_model)
print(lm_summary)

Call:
lm(formula = repeatBuy ~ PC1 + PC2 + PC3 + PC4 + PC5 + PC6 + 
    PC7 + PC8 + PC9 + cluster + name, data = brand_data)

Residuals:
       Min         1Q     Median         3Q        Max 
-3.077e-14 -1.263e-16  1.550e-17  1.670e-16  5.618e-15 

Coefficients:
              Estimate Std. Error    t value Pr(>|t|)    
(Intercept) -1.475e-15  1.851e-16 -7.971e+00 4.37e-15 ***
PC1          4.390e-01  4.565e-17  9.616e+15  < 2e-16 ***
PC2          1.510e-02  4.851e-17  3.112e+14  < 2e-16 ***
PC3         -1.246e-01  3.835e-17 -3.249e+15  < 2e-16 ***
PC4         -1.303e-01  4.621e-17 -2.820e+15  < 2e-16 ***
PC5         -3.557e-01  5.209e-17 -6.829e+15  < 2e-16 ***
PC6         -6.751e-01  5.621e-17 -1.201e+16  < 2e-16 ***
PC7          3.887e-01  6.007e-17  6.470e+15  < 2e-16 ***
PC8         -2.021e-01  6.607e-17 -3.059e+15  < 2e-16 ***
PC9          1.720e-02  7.506e-17  2.292e+14  < 2e-16 ***
cluster2    -5.574e-16  2.141e-16 -2.603e+00 0.009378 ** 
cluster3     5.077e-17  1.694e-16  3.000e-01 0.764425    
nameb        6.035e-16  2.402e-16  2.512e+00 0.012167 *  
namec        5.689e-16  2.351e-16  2.420e+00 0.015701 *  
named        4.343e-16  1.857e-16  2.338e+00 0.019576 *  
namee        6.127e-16  1.756e-16  3.489e+00 0.000506 ***
namef        1.065e-15  2.436e-16  4.372e+00 1.36e-05 ***
nameg        1.036e-15  2.456e-16  4.218e+00 2.69e-05 ***
nameh        4.436e-16  1.897e-16  2.339e+00 0.019554 *  
namei        5.077e-16  1.913e-16  2.654e+00 0.008094 ** 
namej        4.156e-16  1.658e-16  2.507e+00 0.012348 *  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1.117e-15 on 979 degrees of freedom
Multiple R-squared:      1, Adjusted R-squared:      1 
F-statistic: 4e+31 on 20 and 979 DF,  p-value: < 2.2e-16
# Extract and interpret the coefficients
coefficients <- tidy(lm_model)
print(coefficients)
# A tibble: 21 × 5
   term         estimate std.error statistic  p.value
   <chr>           <dbl>     <dbl>     <dbl>    <dbl>
 1 (Intercept) -1.48e-15  1.85e-16  -7.97e 0 4.37e-15
 2 PC1          4.39e- 1  4.57e-17   9.62e15 0       
 3 PC2          1.51e- 2  4.85e-17   3.11e14 0       
 4 PC3         -1.25e- 1  3.84e-17  -3.25e15 0       
 5 PC4         -1.30e- 1  4.62e-17  -2.82e15 0       
 6 PC5         -3.56e- 1  5.21e-17  -6.83e15 0       
 7 PC6         -6.75e- 1  5.62e-17  -1.20e16 0       
 8 PC7          3.89e- 1  6.01e-17   6.47e15 0       
 9 PC8         -2.02e- 1  6.61e-17  -3.06e15 0       
10 PC9          1.72e- 2  7.51e-17   2.29e14 0       
# ℹ 11 more rows
# Visualize the influence of independent variables on repeatBuy
coefficients %>%
  filter(term != "(Intercept)") %>%
  ggplot(aes(x = reorder(term, estimate), y = estimate)) +
  geom_col() +
  coord_flip() +
  labs(title = "Influence of Independent Variables on repeatBuy", x = "Variables", y = "Coefficient Estimate") +
  theme_minimal()