packageVersion("rlang")
## [1] '1.3.0'
library(factoextra)
## Warning: package 'factoextra' was built under R version 4.5.3
## Loading required package: ggplot2
## Welcome to factoextra!
## Want to learn more? See two factoextra-related books at https://www.datanovia.com/library/principal-component-methods
library(dplyr)
## Warning: package 'dplyr' was built under R version 4.5.2
## 
## 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
library(tidyr)
## Warning: package 'tidyr' was built under R version 4.5.3
library(ggplot2)
library(corrplot)
## Warning: package 'corrplot' was built under R version 4.5.3
## corrplot 0.95 loaded
library(cluster)
## Warning: package 'cluster' was built under R version 4.5.3
library(factoextra)
library(knitr)
## Warning: package 'knitr' was built under R version 4.5.3

Load Dataset

data_whr <- read.csv(
  "world-happiness-report-2021.csv",
  fileEncoding = "UTF-8-BOM",
  stringsAsFactors = FALSE
)

# Menampilkan dimensi data
cat("Jumlah baris (negara):", nrow(data_whr), "\n")
## Jumlah baris (negara): 149
cat("Jumlah kolom (variabel):", ncol(data_whr), "\n")
## Jumlah kolom (variabel): 20

Pemeriksaan Struktur, Missing Values, dan Duplikasi

# Struktur dataset
str(data_whr)
## 'data.frame':    149 obs. of  20 variables:
##  $ Country.name                              : chr  "Finland" "Denmark" "Switzerland" "Iceland" ...
##  $ Regional.indicator                        : chr  "Western Europe" "Western Europe" "Western Europe" "Western Europe" ...
##  $ Ladder.score                              : num  7.84 7.62 7.57 7.55 7.46 ...
##  $ Standard.error.of.ladder.score            : num  0.032 0.035 0.036 0.059 0.027 0.035 0.036 0.037 0.04 0.036 ...
##  $ upperwhisker                              : num  7.9 7.69 7.64 7.67 7.52 ...
##  $ lowerwhisker                              : num  7.78 7.55 7.5 7.44 7.41 ...
##  $ Logged.GDP.per.capita                     : num  10.8 10.9 11.1 10.9 10.9 ...
##  $ Social.support                            : num  0.954 0.954 0.942 0.983 0.942 0.954 0.934 0.908 0.948 0.934 ...
##  $ Healthy.life.expectancy                   : num  72 72.7 74.4 73 72.4 73.3 72.7 72.6 73.4 73.3 ...
##  $ Freedom.to.make.life.choices              : num  0.949 0.946 0.919 0.955 0.913 0.96 0.945 0.907 0.929 0.908 ...
##  $ Generosity                                : num  -0.098 0.03 0.025 0.16 0.175 0.093 0.086 -0.034 0.134 0.042 ...
##  $ Perceptions.of.corruption                 : num  0.186 0.179 0.292 0.673 0.338 0.27 0.237 0.386 0.242 0.481 ...
##  $ Ladder.score.in.Dystopia                  : num  2.43 2.43 2.43 2.43 2.43 2.43 2.43 2.43 2.43 2.43 ...
##  $ Explained.by..Log.GDP.per.capita          : num  1.45 1.5 1.57 1.48 1.5 ...
##  $ Explained.by..Social.support              : num  1.11 1.11 1.08 1.17 1.08 ...
##  $ Explained.by..Healthy.life.expectancy     : num  0.741 0.763 0.816 0.772 0.753 0.782 0.763 0.76 0.785 0.782 ...
##  $ Explained.by..Freedom.to.make.life.choices: num  0.691 0.686 0.653 0.698 0.647 0.703 0.685 0.639 0.665 0.64 ...
##  $ Explained.by..Generosity                  : num  0.124 0.208 0.204 0.293 0.302 0.249 0.244 0.166 0.276 0.215 ...
##  $ Explained.by..Perceptions.of.corruption   : num  0.481 0.485 0.413 0.17 0.384 0.427 0.448 0.353 0.445 0.292 ...
##  $ Dystopia...residual                       : num  3.25 2.87 2.84 2.97 2.8 ...
# Cek missing values per kolom
missing_count <- colSums(is.na(data_whr))
kable(
  data.frame(Variabel = names(missing_count), Missing_Values = as.numeric(missing_count)),
  caption = "Pemeriksaan Nilai Hilang (Missing Values)"
)
Pemeriksaan Nilai Hilang (Missing Values)
Variabel Missing_Values
Country.name 0
Regional.indicator 0
Ladder.score 0
Standard.error.of.ladder.score 0
upperwhisker 0
lowerwhisker 0
Logged.GDP.per.capita 0
Social.support 0
Healthy.life.expectancy 0
Freedom.to.make.life.choices 0
Generosity 0
Perceptions.of.corruption 0
Ladder.score.in.Dystopia 0
Explained.by..Log.GDP.per.capita 0
Explained.by..Social.support 0
Explained.by..Healthy.life.expectancy 0
Explained.by..Freedom.to.make.life.choices 0
Explained.by..Generosity 0
Explained.by..Perceptions.of.corruption 0
Dystopia…residual 0
# Cek jumlah baris duplikat
cat("Jumlah data duplikat:", sum(duplicated(data_whr)), "\n")
## Jumlah data duplikat: 0
cat("Jumlah negara unik:", n_distinct(data_whr$Country.name), "\n")
## Jumlah negara unik: 149

#Pemilihan Variabel untuk Clustering

fitur_klaster <- c(
  "Logged.GDP.per.capita",
  "Social.support",
  "Healthy.life.expectancy",
  "Freedom.to.make.life.choices",
  "Generosity",
  "Perceptions.of.corruption"
)

data_fitur <- data_whr %>%
  select(all_of(fitur_klaster))
rownames(data_fitur) <- data_whr$Country.name

#EDA ## Statistik Deskriptif

ringkasan_stat <- data_whr %>%
  select(Ladder.score, all_of(fitur_klaster)) %>%
  pivot_longer(everything(), names_to = "Variabel", values_to = "Nilai") %>%
  group_by(Variabel) %>%
  summarise(
    Min = round(min(Nilai), 3),
    Q1 = round(quantile(Nilai, 0.25), 3),
    Median = round(median(Nilai), 3),
    Mean = round(mean(Nilai), 3),
    Q3 = round(quantile(Nilai, 0.75), 3),
    Max = round(max(Nilai), 3),
    SD = round(sd(Nilai), 3),
    .groups = "drop"
  )

kable(ringkasan_stat, caption = "Statistik Deskriptif Variabel Utama Kebahagiaan Global 2021")
Statistik Deskriptif Variabel Utama Kebahagiaan Global 2021
Variabel Min Q1 Median Mean Q3 Max SD
Freedom.to.make.life.choices 0.382 0.718 0.804 0.792 0.877 0.970 0.113
Generosity -0.288 -0.126 -0.036 -0.015 0.079 0.542 0.151
Healthy.life.expectancy 48.478 59.802 66.603 64.993 69.600 76.953 6.762
Ladder.score 2.523 4.852 5.534 5.533 6.255 7.842 1.074
Logged.GDP.per.capita 6.635 8.541 9.569 9.432 10.421 11.647 1.159
Perceptions.of.corruption 0.082 0.667 0.781 0.727 0.845 0.939 0.179
Social.support 0.463 0.750 0.832 0.815 0.905 0.983 0.115

Distribusi Variabel (Histogram)

data_whr %>%
  select(
    `Ladder Score` = Ladder.score,
    `Logged GDP per Capita` = Logged.GDP.per.capita,
    `Social Support` = Social.support,
    `Healthy Life Expectancy` = Healthy.life.expectancy,
    `Freedom of Choice` = Freedom.to.make.life.choices,
    `Generosity` = Generosity,
    `Perceptions of Corruption` = Perceptions.of.corruption
  ) %>%
  pivot_longer(everything(), names_to = "Variabel", values_to = "Nilai") %>%
  ggplot(aes(x = Nilai)) +
  geom_histogram(bins = 20, fill = "coral3", color = "white", alpha = 0.85) +
  facet_wrap(~ Variabel, scales = "free", ncol = 3) +
  theme_minimal(base_size = 9) +
  theme(
    plot.title = element_text(size = 11, face = "bold", hjust = 0.5),
    strip.text = element_text(size = 8.5, face = "bold")
  ) +
  labs(
    title = "Distribusi Histogram Skor Kebahagiaan\ndan Faktor Penjelasnya",
    x = "Nilai",
    y = "Frekuensi (Jumlah Negara)"
  )

Matriks Korelasi Antar Variabel

data_korelasi <- data_whr %>%
  select(
    Ladder.score,
    all_of(fitur_klaster)
  )

mat_kor <- cor(data_korelasi)
df_kor <- as.data.frame(as.table(mat_kor))
colnames(df_kor) <- c("Var1", "Var2", "Korelasi")

ggplot(df_kor, aes(x = Var1, y = Var2, fill = Korelasi)) +
  geom_tile(color = "white") +
  geom_text(aes(label = sprintf("%.2f", Korelasi)), size = 3.2) +
  scale_fill_gradient2(
    low = "aquamarine3", mid = "white", high = "pink",
    midpoint = 0, limit = c(-1, 1)
  ) +
  theme_minimal(base_size = 10) +
  theme(
    axis.text.x = element_text(angle = 35, hjust = 1),
    axis.title = element_blank()
  ) +
  labs(title = "Matriks Korelasi Variabel Kebahagiaan Global 2021")

Analisis Clustering (K-Means)

Standardisasi Data

data_scaled <- scale(data_fitur)

Penentuan Jumlah Klaster Optimal

Metode Elbow (WCSS / Inertia)

set.seed(42)
wss <- sapply(1:10, function(k) {
  kmeans(data_scaled, centers = k, nstart = 25)$tot.withinss
})

df_elbow <- data.frame(k = 1:10, WCSS = wss)

ggplot(df_elbow, aes(x = k, y = WCSS)) +
  geom_line(color = "pink", linewidth = 1) +
  geom_point(color = "pink", size = 3) +
  geom_vline(xintercept = 3, linetype = 2, color = "red") +
  scale_x_continuous(breaks = 1:10) +
  theme_minimal() +
  labs(
    title = "Metode Elbow untuk Menentukan Jumlah Klaster Optimal",
    subtitle = "Garis putus-putus menunjukkan titik siku pada k = 3",
    x = "Jumlah Klaster (k)",
    y = "Total Within-Cluster Sum of Squares (WCSS)"
  )

### Metode Silhouette

set.seed(42)
dist_mat <- dist(data_scaled)
sil_avg <- sapply(2:10, function(k) {
  km <- kmeans(data_scaled, centers = k, nstart = 25)
  ss <- silhouette(km$cluster, dist_mat)
  mean(ss[, 3])
})

df_sil <- data.frame(k = 2:10, Silhouette = sil_avg)

ggplot(df_sil, aes(x = k, y = Silhouette)) +
  geom_line(color = "coral", linewidth = 1) +
  geom_point(color = "coral", size = 3) +
  scale_x_continuous(breaks = 2:10) +
  theme_minimal() +
  labs(
    title = "Evaluasi Average Silhouette Width untuk Berbagai Nilai k",
    x = "Jumlah Klaster (k)",
    y = "Average Silhouette Width"
  )

#Pemodelan K-Means Clustering (k=3)

set.seed(42)
kmeans_model <- kmeans(data_scaled, centers = 3, nstart = 25)

# Menambahkan label klaster ke dataset asli
data_clustered <- data_whr %>%
  mutate(Cluster = factor(kmeans_model$cluster))

# Menampilkan jumlah negara pada setiap klaster
kable(
  as.data.frame(table(Cluster = data_clustered$Cluster)),
  col.names = c("Klaster", "Jumlah Negara"),
  caption = "Distribusi Jumlah Anggota per Klaster"
)
Distribusi Jumlah Anggota per Klaster
Klaster Jumlah Negara
1 83
2 44
3 22

Visualisasi dan Evaluasi Hasil Clustering

Visualisasi Klaster pada Ruang PCA (2 Dimensi)

pca_res <- prcomp(data_scaled)
var_exp <- round(100 * summary(pca_res)$importance[2, 1:2], 1)

df_pca <- data.frame(
  PC1 = pca_res$x[, 1],
  PC2 = pca_res$x[, 2],
  Cluster = data_clustered$Cluster
)

ggplot(df_pca, aes(x = PC1, y = PC2, color = Cluster, fill = Cluster)) +
  geom_point(size = 2.8, alpha = 0.85) +
  stat_ellipse(geom = "polygon", alpha = 0.15, level = 0.90) +
  scale_color_brewer(palette = "Dark2") +
  scale_fill_brewer(palette = "Dark2") +
  theme_minimal() +
  labs(
    title = "Visualisasi Klaster K-Means (k = 3) Menggunakan Reduksi Dimensi PCA",
    subtitle = "Pengelompokan 149 Negara Berdasarkan 6 Faktor Kebahagiaan",
    x = paste0("PC1 (", var_exp[1], "%)"),
    y = paste0("PC2 (", var_exp[2], "%)")
  )

Visualisasi Sebaran pada Variabel Ekonomi dan Dukungan Sosial

ggplot(data_clustered, aes(x = Logged.GDP.per.capita, y = Social.support, color = Cluster)) +
  geom_point(size = 3, alpha = 0.85) +
  scale_color_brewer(palette = "Dark2") +
  theme_minimal() +
  labs(
    title = "Sebaran Klaster Negara: Logged GDP per Capita vs Social Support",
    x = "Logged GDP per capita",
    y = "Social support",
    color = "Klaster"
  )

## Evaluasi Kualitas Klaster dengan Silhouette Plot (k=3)

sil <- silhouette(kmeans_model$cluster, dist(data_scaled))

df_sil_k3 <- data.frame(
  cluster = factor(sil[, 1]),
  sil_width = sil[, 3]
) %>%
  arrange(cluster, sil_width) %>%
  mutate(order = row_number())

ggplot(df_sil_k3, aes(x = order, y = sil_width, fill = cluster)) +
  geom_col(width = 1) +
  geom_hline(yintercept = mean(df_sil_k3$sil_width), linetype = "dashed", color = "red") +
  scale_fill_brewer(palette = "Dark2") +
  theme_minimal() +
  theme(axis.text.x = element_blank(), axis.ticks.x = element_blank()) +
  labs(
    title = paste0("Silhouette Plot K-Means (k = 3), Rata-rata Silhouette = ", round(mean(df_sil_k3$sil_width), 3)),
    x = "Observasi (Negara)",
    y = "Silhouette Width",
    fill = "Klaster"
  )

# Profil dan Interpretasi Tiap Klaster ## Ringkasan Karakteristik Tiap Klaster

profil_klaster <- data_clustered %>%
  group_by(Cluster) %>%
  summarise(
    N = n(),
    Ladder_Score = round(mean(Ladder.score), 3),
    GDP = round(mean(Logged.GDP.per.capita), 3),
    Social_Support = round(mean(Social.support), 3),
    Life_Exp = round(mean(Healthy.life.expectancy), 3),
    Freedom = round(mean(Freedom.to.make.life.choices), 3),
    Generosity = round(mean(Generosity), 3),
    Corruption = round(mean(Perceptions.of.corruption), 3),
    .groups = "drop"
  ) %>%
  arrange(desc(Ladder_Score))

kable(profil_klaster, caption = "Profil Rata-Rata Karakteristik Setiap Klaster (Diurutkan dari Skor Kebahagiaan Tertinggi)")
Profil Rata-Rata Karakteristik Setiap Klaster (Diurutkan dari Skor Kebahagiaan Tertinggi)
Cluster N Ladder_Score GDP Social_Support Life_Exp Freedom Generosity Corruption
3 22 7.015 10.842 0.929 72.557 0.908 0.068 0.398
1 83 5.711 9.795 0.857 67.327 0.799 -0.079 0.798
2 44 4.455 8.042 0.678 56.808 0.720 0.063 0.760

Visualisasi Perbandingan Profil Klaster (Z-Score)

profil_z <- as.data.frame(data_scaled) %>%
  mutate(Cluster = data_clustered$Cluster) %>%
  group_by(Cluster) %>%
  summarise(across(everything(), mean), .groups = "drop") %>%
  pivot_longer(-Cluster, names_to = "Faktor", values_to = "Rata2_Z_Score")

ggplot(profil_z, aes(x = Faktor, y = Rata2_Z_Score, group = Cluster, color = Cluster)) +
  geom_line(size = 1.1) +
  geom_point(size = 3) +
  geom_hline(yintercept = 0, linetype = "dashed", color = "skyblue") +
  scale_color_brewer(palette = "Dark2") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 25, hjust = 1)) +
  labs(
    title = "Perbandingan Profil Faktor Antar Klaster (Nilai Terstandardisasi / Z-Score)",
    x = "Faktor Penentu Kebahagiaan",
    y = "Rata-rata Z-Score",
    color = "Klaster"
  )
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once per session.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

## Daftar Contoh Negara dan Komposisi Wilayah per Klaster

# Contoh 5 negara dengan Ladder Score tertinggi di masing-masing klaster
contoh_negara <- data_clustered %>%
  group_by(Cluster) %>%
  arrange(desc(Ladder.score)) %>%
  slice_head(n = 5) %>%
  summarise(
    Contoh_5_Negara = paste(Country.name, collapse = ", "),
    .groups = "drop"
  )

kable(contoh_negara, caption = "Contoh 5 Negara dengan Skor Kebahagiaan Tertinggi pada Tiap Klaster")
Contoh 5 Negara dengan Skor Kebahagiaan Tertinggi pada Tiap Klaster
Cluster Contoh_5_Negara
1 Israel, Costa Rica, Czech Republic, United States, Belgium
2 Indonesia, Congo (Brazzaville), Ivory Coast, Nepal, Cameroon
3 Finland, Denmark, Switzerland, Iceland, Netherlands
# Distribusi wilayah (Regional indicator) per klaster
tabel_wilayah <- as.data.frame.matrix(table(data_clustered$Regional.indicator, data_clustered$Cluster))
kable(tabel_wilayah, caption = "Distribusi Jumlah Negara Berdasarkan Wilayah dan Klaster")
Distribusi Jumlah Negara Berdasarkan Wilayah dan Klaster
1 2 3
Central and Eastern Europe 16 0 1
Commonwealth of Independent States 11 0 1
East Asia 5 0 1
Latin America and Caribbean 19 1 0
Middle East and North Africa 12 4 1
North America and ANZ 1 0 3
South Asia 2 5 0
Southeast Asia 5 3 1
Sub-Saharan Africa 5 31 0
Western Europe 7 0 14