1. Load Packages

library(tidyverse)
library(readr)
library(stringr)

2. Read Dataset

df <- read_csv("The impacts of COVID-19 policy on peoples SWB.csv")
## Warning: One or more parsing issues, call `problems()` on your data frame for details,
## e.g.:
##   dat <- vroom(...)
##   problems(dat)
## Rows: 9285 Columns: 33
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (18): Life Satisfaction, wea, web, wec, wed, wee, wef, weg, weh, wei, we...
## dbl (15): OldChild, SmallChild, confirmed_x, deaths_x, school_closing_x, wor...
## 
## ℹ 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.

3. Select Clustering Variables

vars <- c('Life Satisfaction', 'wea', 'web', 'wec', 'wed', 'wee', 
          'wef', 'weg', 'weh', 'wei', 'wej')

4. Clean Data

df_sub <- df %>%
  select(all_of(vars)) %>%
  mutate(across(wea:wej, ~ifelse(. == "Yes", 1, 0))) %>%
  mutate(`Life Satisfaction` = as.numeric(str_extract(`Life Satisfaction`, "\\d+")))

5. Standardize Data

df_scaled <- scale(df_sub)

6. Run K-means Clustering

set.seed(42)
km <- kmeans(df_scaled, centers = 3, nstart = 10)
df_sub$Cluster <- as.factor(km$cluster)

7. Cluster Summary Table

Below is the table showing the mean values of each variable across the three clusters. This summary is useful for interpreting the characteristics of each group.

cluster_summary <- df_sub %>%
  group_by(Cluster) %>%
  summarise(across(everything(), mean))

cluster_summary
## # A tibble: 3 × 12
##   Cluster `Life Satisfaction`   wea    web    wec   wed    wee   wef   weg
##   <fct>                 <dbl> <dbl>  <dbl>  <dbl> <dbl>  <dbl> <dbl> <dbl>
## 1 1                      6.82 0.751 0.857  0.259  0.911 0.305  0.833 0.243
## 2 2                      5.36 0.190 0.852  0.779  0.887 0.540  0.258 0.474
## 3 3                      7.52 0.844 0.0713 0.0503 0.194 0.0808 0.865 0.233
## # ℹ 3 more variables: weh <dbl>, wei <dbl>, wej <dbl>