I. Đọc dữ liệu

II. Chọn các biến định tính và kiểm tra lại

##  [1] "X"                 "PurchaseDate"      "CustomerID"       
##  [4] "Gender"            "MaritalStatus"     "Homeowner"        
##  [7] "Children"          "AnnualIncome"      "City"             
## [10] "StateorProvince"   "Country"           "ProductFamily"    
## [13] "ProductDepartment" "ProductCategory"   "UnitsSold"        
## [16] "Revenue"
Gender MaritalStatus Homeowner City StateorProvince Country ProductFamily ProductDepartment ProductCategory
F S Y Los Angeles CA USA Food Snack Foods Snack Foods
M M Y Los Angeles CA USA Food Produce Vegetables
F M N Bremerton WA USA Food Snack Foods Snack Foods
M M Y Portland OR USA Food Snacks Candy
F S Y Beverly Hills CA USA Drink Beverages Carbonated Beverages
F M Y Beverly Hills CA USA Food Deli Side Dishes

III. Lập bảng tần số, tần suất và vẽ biểu đồ

3.1. Biến Gender

table(d$Gender)
## 
##    F    M 
## 7170 6889
tmp <- table(d$Gender)/sum(nrow(d))
tmp
## 
##         F         M 
## 0.5099936 0.4900064

Vậy bộ dữ liệu này có 50.9993598 % là nữ và 49.0006402 % là nam

# Tính tần suất và phần trăm
df_gender <- d %>%
  count(Gender) %>%
  mutate(prop = n / sum(n),
         pct = paste0(round(prop * 100), "%"))

# Vẽ biểu đồ cột
ggplot(df_gender, aes(x = Gender, y = n, fill = Gender)) +
  geom_bar(stat = "identity", width = 0.6, color = "black") +  # Viền đen quanh cột
  scale_fill_manual(values = c("M" = "yellow", "F" = "pink")) +  # Màu theo Gender
  geom_text(aes(label = pct), vjust = -0.5, size = 5) +  # Hiển thị % trên cột
  labs(title = "Bar Plot - Gender", x = "Gender", y = "Frequency") +
  theme_minimal(base_size = 14) +
  theme(
    plot.title = element_text(face = "bold", hjust = 0.5)
  )

# Tính tần suất
df_gender <- d %>%
  count(Gender) %>%
  mutate(prop = n / sum(n),
         pct = paste0(round(prop * 100), "%"))

# Vẽ biểu đồ tròn
ggplot(df_gender, aes(x = "", y = prop, fill = Gender)) +
  geom_bar(stat = "identity", width = 1, color = "black") +  # Viền đen quanh miếng
  coord_polar("y", start = 0) +  # Biểu đồ hình tròn
  scale_fill_manual(values = c("M" = "yellow", "F" = "pink")) +  # Màu theo Gender
  geom_text(aes(label = pct), position = position_stack(vjust = 0.5)) +  # Hiện % ở giữa
  labs(title = "Pie Chart - Gender", x = NULL, y = NULL, fill = "Gender") +
  theme_minimal(base_size = 14) +
  theme(
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    panel.grid = element_blank(),
    plot.title = element_text(face = "bold", hjust = 0.5)
  )

Biến Gender: Biến này phản ánh giới tính của khách hàng với hai giá trị: nam (M) và nữ (F). Trong tổng số 14.059 quan sát, số lượng nữ là 7.170 người (chiếm 51%), còn nam là 6.889 người (49%). Tỷ lệ này cho thấy giới tính trong mẫu dữ liệu khá cân đối, không có sự chênh lệch đáng kể giữa hai nhóm.

3.2. Biến MaritalStatus

table(d$MaritalStatus)
## 
##    M    S 
## 6866 7193
tmp <- table(d$MaritalStatus)/sum(nrow(d))
tmp
## 
##         M         S 
## 0.4883704 0.5116296
df_marital <- d %>%
  count(MaritalStatus)

ggplot(df_marital, aes(x = reorder(MaritalStatus, -n), y = n, fill = MaritalStatus)) +
  geom_bar(stat = "identity", color = "black", width = 0.7) +  # Viền đen
  scale_fill_brewer(palette = "Set2") +  # Màu tự động đẹp
  labs(title = "Bar Plot - Marital Status", x = "Marital Status", y = "Frequency") +
  theme_minimal(base_size = 14) +
  theme(
    legend.position = "none",
    plot.title = element_text(face = "bold", hjust = 0.5),
    axis.text = element_text(color = "black"),
    axis.title = element_text(face = "bold")
  )

df_marital <- d %>%
  count(MaritalStatus) %>%
  mutate(Percent = round(100 * n / sum(n), 2))

ggplot(df_marital, aes(x = "", y = n, fill = MaritalStatus)) +
  geom_bar(stat = "identity", width = 1, color = "black") +  # Viền đen
  coord_polar("y", start = 0) +
  theme_void(base_size = 14) +
  scale_fill_brewer(palette = "Set2") +  # Bảng màu tự động đẹp
  labs(title = "Pie Chart - Marital Status") +
  geom_text(aes(label = paste0(Percent, "%")), position = position_stack(vjust = 0.5)) +
  theme(
    plot.title = element_text(face = "bold", hjust = 0.5)
  )

Biến MaritalStatus: Phản ánh tình trạng hôn nhân của khách hàng. Trong dữ liệu, có 7.193 người độc thân (51.16%) và 6.866 người đã kết hôn (48.84%). Mặc dù tỷ lệ khá cân bằng, nhưng nhóm độc thân chiếm ưu thế nhẹ.

3.3. Biến Homeowner

table(d$Homeowner)
## 
##    N    Y 
## 5615 8444
tmp <- table(d$Homeowner)/sum(nrow(d))
tmp
## 
##         N         Y 
## 0.3993883 0.6006117
df_home <- d %>%
  count(Homeowner)

ggplot(df_home, aes(x = reorder(Homeowner, -n), y = n, fill = Homeowner)) +
  geom_bar(stat = "identity", color = "black", width = 0.7) +
  scale_fill_manual(values = c("Y" = "#FFD1DC", "N" = "#D8EEDF")) +
  labs(title = "Bar Plot - Homeowner", x = "Homeowner", y = "Frequency") +
  theme_minimal(base_size = 14) +
  theme(
    legend.position = "none",
    plot.title = element_text(face = "bold", hjust = 0.5)
  )

df_home <- df_home %>%
  mutate(Percent = round(100 * n / sum(n), 2))

ggplot(df_home, aes(x = "", y = n, fill = Homeowner)) +
  geom_bar(stat = "identity", width = 1, color = "black") +
  coord_polar("y") +
  theme_void() +
  scale_fill_manual(values = c("Y" = "#FFD1DC", "N" = "#D8EEDF")) +
  labs(title = "Pie Chart - Homeowner") +
  geom_text(aes(label = paste0(Percent, "%")), position = position_stack(vjust = 0.5))

Biến Homeowner: Thể hiện việc khách hàng có sở hữu nhà ở hay không. Có 8.444 người (60.06%) có nhà và 5.615 người (39.94%) không có nhà. Điều này cho thấy phần lớn khách hàng trong tập dữ liệu có điều kiện kinh tế tương đối ổn định.

3.4. Biến City

table(d$City)
## 
##      Acapulco    Bellingham Beverly Hills     Bremerton       Camacho 
##           383           143           811           834           452 
##   Guadalajara       Hidalgo   Los Angeles        Merida   Mexico City 
##            75           845           926           654           194 
##       Orizaba      Portland         Salem    San Andres     San Diego 
##           464           876          1386           621           866 
## San Francisco       Seattle       Spokane        Tacoma     Vancouver 
##           130           922           875          1257           633 
##      Victoria   Walla Walla        Yakima 
##           176           160           376
tmp <- table(d$City)/sum(nrow(d))
tmp
## 
##      Acapulco    Bellingham Beverly Hills     Bremerton       Camacho 
##   0.027242336   0.010171420   0.057685468   0.059321431   0.032150224 
##   Guadalajara       Hidalgo   Los Angeles        Merida   Mexico City 
##   0.005334661   0.060103848   0.065865282   0.046518245   0.013798990 
##       Orizaba      Portland         Salem    San Andres     San Diego 
##   0.033003770   0.062308841   0.098584537   0.044170994   0.061597553 
## San Francisco       Seattle       Spokane        Tacoma     Vancouver 
##   0.009246746   0.065580767   0.062237712   0.089408920   0.045024539 
##      Victoria   Walla Walla        Yakima 
##   0.012518671   0.011380610   0.026744434
df_city <- d %>%
  count(City)

ggplot(df_city, aes(x = reorder(City, -n), y = n, fill = City)) +
  geom_bar(stat = "identity", width = 1, color = "black") +
  labs(title = "Bar Plot - City", x = "City", y = "Frequency") +
  theme_minimal() +
  theme(
    legend.position = "none",
    axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1, face = "italic")  # xoay 45 độ + nghiêng
  )

df_city <- df_city %>%
  mutate(Percent = round(100 * n / sum(n), 2),
         label = ifelse(Percent > 5, paste0(Percent, "%"), ""))

ggplot(df_city, aes(x = "", y = n, fill = City)) +
  geom_bar(stat = "identity", width = 1) +
  coord_polar("y") +
  theme_void() +
  labs(title = "Pie Chart - City") +
  geom_text(aes(label = label), position = position_stack(vjust = 0.5), size = 3)

Biến City: Phản ánh nơi sinh sống của khách hàng theo thành phố. Dữ liệu ghi nhận 23 thành phố, trong đó Bremerton (5.93%), Beverly Hills (5.77%) và Camacho (3.22%) là các khu vực có lượng khách hàng cao hơn hẳn. Phân bố khách hàng giữa các thành phố cho thấy sự đa dạng về mặt địa lý.

3.5. Biến StateorProvince

table(d$StateorProvince)
## 
##        BC        CA        DF  Guerrero   Jalisco        OR  Veracruz        WA 
##       809      2733       815       383        75      2262       464      4567 
##   Yucatan Zacatecas 
##       654      1297
tmp <- table(d$StateorProvince)/sum(nrow(d))
tmp
## 
##          BC          CA          DF    Guerrero     Jalisco          OR 
## 0.057543211 0.194395049 0.057969984 0.027242336 0.005334661 0.160893378 
##    Veracruz          WA     Yucatan   Zacatecas 
## 0.033003770 0.324845295 0.046518245 0.092254072
# Bước 1: Tạo biến df_state bằng cách đếm số lượng từng bang/tỉnh
df_state <- d%>%
  count(StateorProvince, name = "n")

# Bước 2: Vẽ biểu đồ cột
ggplot(df_state, aes(x = reorder(StateorProvince, -n), y = n, fill = StateorProvince)) +
  geom_bar(stat = "identity", color = "black", width = 0.7) +
  scale_fill_brewer(palette = "Set3") +
  labs(title = "Bar Plot - State or Province", x = "State/Province", y = "Frequency") +
  theme_minimal() +
  theme(
    legend.position = "none",
    plot.title = element_text(face = "bold", hjust = 0.5),
    axis.text.x = element_text(angle = 45, hjust = 1)
  )

Biến StateorProvince: Cho biết tên bang hoặc tỉnh nơi khách hàng cư trú. California (CA) có tỷ lệ cao nhất (19.44%), tiếp theo là Distrito Federal (DF) với 5.8%. Một số khu vực khác như Jalisco hay Guerrero chỉ chiếm tỷ lệ nhỏ, dưới 3%, cho thấy khách hàng tập trung ở một số bang nhất định.

3.6. Biến Country

table(d$Country)
## 
## Canada Mexico    USA 
##    809   3688   9562
tmp <- table(d$Country)/sum(nrow(d))
tmp
## 
##     Canada     Mexico        USA 
## 0.05754321 0.26232307 0.68013372
df_country <- d %>%
  count(Country)

ggplot(df_country, aes(x = reorder(Country, -n), y = n, fill = Country)) +
  geom_bar(stat = "identity", color = "black", width = 0.7) +
  scale_fill_manual(values = c(
    "USA" = "#FFD54F",
    "Mexico" = "#4DB6AC",
    "Canada" = "#BA68C8"
    # Thêm màu cho các nước khác ở đây
  )) +
  labs(title = "Bar Plot - Country", x = "Country", y = "Frequency") +
  theme_minimal() +
  theme(
    legend.position = "none",
    plot.title = element_text(face = "bold", hjust = 0.5)
  )

df_country <- df_country %>%
  mutate(Percent = round(100 * n / sum(n), 2))

ggplot(df_country, aes(x = "", y = n, fill = Country)) +
  geom_bar(stat = "identity", width = 1, color = "black") +
  coord_polar("y") +
  theme_void() +
  scale_fill_manual(values = c(
    "USA" = "#FFD54F",
    "Mexico" = "#4DB6AC",
    "Canada" = "#BA68C8"
    # Thêm màu cho các nước khác ở đây
  )) +
  labs(title = "Pie Chart - Country") +
  geom_text(aes(label = paste0(Percent, "%")), position = position_stack(vjust = 0.5))

Biến Country: Thể hiện quốc gia cư trú của khách hàng. Hoa Kỳ chiếm đa số với 68.01%, kế đến là Mexico (26.23%) và Canada (5.75%). Sự chênh lệch lớn giữa các quốc gia cho thấy mẫu dữ liệu nghiêng về phía khách hàng từ Mỹ, điều này cần lưu ý trong quá trình phân tích.

3.7. Biến ProductFamily

table(d$ProductFamily)
## 
##          Drink           Food Non-Consumable 
##           1250          10153           2656
tmp <- table(d$ProductFamily)/sum(nrow(d))
tmp
## 
##          Drink           Food Non-Consumable 
##     0.08891102     0.72217085     0.18891813
df_family <- d %>%
  count(ProductFamily)

ggplot(df_family, aes(x = reorder(ProductFamily, -n), y = n, fill = ProductFamily)) +
  geom_bar(stat = "identity", width = 1, color = "black") +
  labs(title = "Bar Plot - Product Family", x = "Product Family", y = "Frequency") +
  theme_minimal() + theme(legend.position = "none")

df_family <- df_family %>%
  mutate(Percent = round(100 * n / sum(n), 2))

ggplot(df_family, aes(x = "", y = n, fill = ProductFamily)) +
  geom_bar(stat = "identity", width = 1, color = "black") +
  coord_polar("y") + theme_void() +
  labs(title = "Pie Chart - Product Family") +
  geom_text(aes(label = paste0(Percent, "%")), position = position_stack(vjust = 0.5))

Biến ProductFamily: Chia sản phẩm thành ba nhóm chính: Food, Drink và Non-Consumable. Nhóm Food chiếm tỷ lệ cao nhất với 72.22%, tiếp theo là Non-Consumable (18.89%) và Drink (8.89%). Đây là dấu hiệu cho thấy sản phẩm thực phẩm đóng vai trò chủ đạo trong tiêu dùng.

3.8. Biến ProductDepartment

table(d$ProductDepartment)
## 
## Alcoholic Beverages         Baked Goods        Baking Goods           Beverages 
##                 356                 425                1072                 680 
##     Breakfast Foods        Canned Foods     Canned Products            Carousel 
##                 188                 977                 109                  59 
##            Checkout               Dairy                Deli                Eggs 
##                  82                 903                 699                 198 
##        Frozen Foods  Health and Hygiene           Household                Meat 
##                1382                 893                1420                  89 
##         Periodicals             Produce             Seafood         Snack Foods 
##                 202                1994                 102                1600 
##              Snacks       Starchy Foods 
##                 352                 277
tmp <- table(d$ProductDepartment)/sum(nrow(d))
tmp
## 
## Alcoholic Beverages         Baked Goods        Baking Goods           Beverages 
##         0.025321858         0.030229746         0.076250089         0.048367594 
##     Breakfast Foods        Canned Foods     Canned Products            Carousel 
##         0.013372217         0.069492852         0.007753041         0.004196600 
##            Checkout               Dairy                Deli                Eggs 
##         0.005832563         0.064229319         0.049719041         0.014083505 
##        Frozen Foods  Health and Hygiene           Household                Meat 
##         0.098300021         0.063518031         0.101002916         0.006330464 
##         Periodicals             Produce             Seafood         Snack Foods 
##         0.014368020         0.141830856         0.007255139         0.113806103 
##              Snacks       Starchy Foods 
##         0.025037343         0.019702682
df_department <- d %>%
  count(ProductDepartment)

# Tạo màu cho từng nhóm
colors <- setNames(scales::hue_pal()(nrow(df_department)), df_department$ProductDepartment)

# Biểu đồ cột màu đầy đủ
ggplot(df_department, aes(x = reorder(ProductDepartment, -n), y = n, fill = ProductDepartment)) +
  geom_bar(stat = "identity", color = "black") +
  scale_fill_manual(values = colors) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  labs(title = "Bar Plot - Product Department", x = "Product Department", y = "Frequency")

Biến Product Department: Cho thấy Produce (Rau củ quả) là nhóm sản phẩm có tần suất cao nhất (14.18%), tiếp theo là Snack Foods (11.38%) và Frozen Foods (9.83%), phản ánh nhu cầu tiêu dùng lớn và thường xuyên. Các nhóm như Household (10.1%) và Baking Goods (7.63%) cũng có mức tiêu thụ khá. Ngược lại, các nhóm như Meat (0.63%), Checkout (0.58%), và Seafood (0.73%) có tần suất thấp, cho thấy mức độ mua sắm hạn chế. Sự phân bố này giúp doanh nghiệp xác định các nhóm sản phẩm chủ lực để ưu tiên phát triển, đồng thời cân nhắc chiến lược với các nhóm ít phổ biến.

3.9. Biến ProductCategory

table(d$ProductCategory)
## 
##         Baking Goods    Bathroom Products        Beer and Wine 
##                  484                  365                  356 
##                Bread      Breakfast Foods              Candles 
##                  425                  417                   45 
##                Candy     Canned Anchovies         Canned Clams 
##                  352                   44                   53 
##       Canned Oysters      Canned Sardines        Canned Shrimp 
##                   35                   40                   38 
##          Canned Soup          Canned Tuna Carbonated Beverages 
##                  404                   87                  154 
##    Cleaning Supplies        Cold Remedies                Dairy 
##                  189                   93                  903 
##        Decongestants               Drinks                 Eggs 
##                   85                  135                  198 
##           Electrical      Frozen Desserts       Frozen Entrees 
##                  355                  323                  118 
##                Fruit             Hardware        Hot Beverages 
##                  765                  129                  226 
##              Hygiene     Jams and Jellies     Kitchen Products 
##                  197                  588                  217 
##            Magazines                 Meat        Miscellaneous 
##                  202                  761                   42 
##  Packaged Vegetables       Pain Relievers       Paper Products 
##                   48                  192                  345 
##                Pizza     Plastic Products Pure Juice Beverages 
##                  194                  141                  165 
##              Seafood          Side Dishes          Snack Foods 
##                  102                  153                 1600 
##            Specialty        Starchy Foods           Vegetables 
##                  289                  277                 1728
tmp <- table(d$ProductCategory)/sum(nrow(d))
tmp
## 
##         Baking Goods    Bathroom Products        Beer and Wine 
##          0.034426346          0.025962017          0.025321858 
##                Bread      Breakfast Foods              Candles 
##          0.030229746          0.029660716          0.003200797 
##                Candy     Canned Anchovies         Canned Clams 
##          0.025037343          0.003129668          0.003769827 
##       Canned Oysters      Canned Sardines        Canned Shrimp 
##          0.002489508          0.002845153          0.002702895 
##          Canned Soup          Canned Tuna Carbonated Beverages 
##          0.028736041          0.006188207          0.010953837 
##    Cleaning Supplies        Cold Remedies                Dairy 
##          0.013443346          0.006614980          0.064229319 
##        Decongestants               Drinks                 Eggs 
##          0.006045949          0.009602390          0.014083505 
##           Electrical      Frozen Desserts       Frozen Entrees 
##          0.025250729          0.022974607          0.008393200 
##                Fruit             Hardware        Hot Beverages 
##          0.054413543          0.009175617          0.016075112 
##              Hygiene     Jams and Jellies     Kitchen Products 
##          0.014012376          0.041823743          0.015434953 
##            Magazines                 Meat        Miscellaneous 
##          0.014368020          0.054129028          0.002987410 
##  Packaged Vegetables       Pain Relievers       Paper Products 
##          0.003414183          0.013656732          0.024539441 
##                Pizza     Plastic Products Pure Juice Beverages 
##          0.013798990          0.010029163          0.011736254 
##              Seafood          Side Dishes          Snack Foods 
##          0.007255139          0.010882709          0.113806103 
##            Specialty        Starchy Foods           Vegetables 
##          0.020556227          0.019702682          0.122910591
df_cat <- d %>%
  count(ProductCategory)

ggplot(df_cat, aes(x = reorder(ProductCategory, -n), y = n, fill = ProductCategory)) +
  geom_bar(stat = "identity", color = "black") +
  labs(title = "Bar Plot - Product Category", x = "Product Category", y = "Frequency") +
  theme(
    legend.position = "none",
    axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1, face = "italic")  # xoay 45 độ + nghiêng
  )

Biến ProductCategory: Là cấp độ phân loại chi tiết nhất trong sản phẩm. Các danh mục phổ biến gồm Baking Goods (3.44%), Bread (3.02%) và Beer and Wine (2.53%). Mặc dù tỷ lệ không cao, nhưng tổng thể các danh mục thể hiện cấu trúc sản phẩm phong phú, đáp ứng nhiều loại nhu cầu tiêu dùng.