library(readxl)
library(psych)
Data_analisis_faktor <- read_excel("C:/Users/oktav/Documents/Data analisis faktor.xlsx")
## New names:
## • `` -> `...21`
## • `` -> `...22`
View(Data_analisis_faktor)
# 2. Lihat nama kolom
names(Data_analisis_faktor)
##  [1] "Kabupaten/Kota Se Jawa Timur" "X1"                          
##  [3] "X2"                           "X3"                          
##  [5] "X4"                           "X5"                          
##  [7] "X6"                           "X7"                          
##  [9] "X8"                           "X9"                          
## [11] "X10"                          "X11"                         
## [13] "X12"                          "X13"                         
## [15] "X14"                          "X15"                         
## [17] "X16"                          "X17"                         
## [19] "X18"                          "X19"                         
## [21] "...21"                        "...22"
# 3. Pilih kolom numerik
fitur <- Data_analisis_faktor[
  , sapply(Data_analisis_faktor, is.numeric),
  drop = FALSE
]
# 4. Hapus kolom ID jika ada
fitur$ID <- NULL
# 5. Hapus data kosong dan standardisasi
fitur <- na.omit(fitur)
X_baru <- scale(fitur)
# 6. Bandingkan K = 3 dan K = 5
set.seed(42)

for (k in c(3, 5)) {
  hasil <- kmeans(X_baru, centers = k, nstart = 10)

  cat("\nHasil K =", k, "\n")
  print(table(hasil$cluster))
}
## 
## Hasil K = 3 
## 
##  1  2  3 
## 10  9 19 
## 
## Hasil K = 5 
## 
##  1  2  3  4  5 
## 15  6  4  5  8
# Plot clustering K = 3 dan K = 5

set.seed(42)

par(mfrow = c(1, 2))

for (k in c(3, 5)) {
  hasil <- kmeans(X_baru, centers = k, nstart = 10)

  plot(
    X_baru[, 1], X_baru[, 2],
    col = hasil$cluster,
    pch = 19,
    main = paste("Clustering K =", k),
    xlab = colnames(X_baru)[1],
    ylab = colnames(X_baru)[2]
  )
}

par(mfrow = c(1, 1))
# Parallel Analysis Scree Plot
fa.parallel(
  X_baru,
  fa = "pc",
  n.iter = 100,
  main = "Parallel Analysis Scree Plot"
)
## Warning in cor.smooth(r): Matrix was not positive definite, smoothing was done
## In factor.scores, the correlation matrix is singular, the pseudo inverse is  used

## Parallel analysis suggests that the number of factors =  NA  and the number of components =  2