R Markdown

# ==========================================================
# PEMODELAN KEMISKINAN KABUPATEN/KOTA DI JAWA TIMUR
# Regresi dependensi spasial - K-Nearest Neighbor (k = 4) - ML
# Adaptasi sintaks teman dan modul praktikum dosen
# ==========================================================

# 1. PERSIAPAN DATA DAN PETA ---------------------------------
library(readxl)
## Warning: package 'readxl' was built under R version 4.4.3
library(sf)
## Warning: package 'sf' was built under R version 4.4.3
## Linking to GEOS 3.13.0, GDAL 3.10.1, PROJ 9.5.1; sf_use_s2() is TRUE
library(spdep)
## Warning: package 'spdep' was built under R version 4.4.3
## Loading required package: spData
## Warning: package 'spData' was built under R version 4.4.3
## To access larger datasets in this package, install the spDataLarge
## package with: `install.packages('spDataLarge',
## repos='https://nowosad.github.io/drat/', type='source')`
library(spatialreg)
## Warning: package 'spatialreg' was built under R version 4.4.3
## Loading required package: Matrix
## 
## Attaching package: 'spatialreg'
## The following objects are masked from 'package:spdep':
## 
##     get.ClusterOption, get.coresOption, get.mcOption,
##     get.VerboseOption, get.ZeroPolicyOption, set.ClusterOption,
##     set.coresOption, set.mcOption, set.VerboseOption,
##     set.ZeroPolicyOption
library(ggplot2)
library(car)
## Warning: package 'car' was built under R version 4.4.3
## Loading required package: carData
## Warning: package 'carData' was built under R version 4.4.3
folder <- "C:/Users/Kasmin Jamain/Downloads/Output_Regresi_Spasial_KNN"
dir.create(folder, showWarnings = FALSE, recursive = TRUE)
alpha <- 0.05

# Membaca Excel dan GeoJSON
data_kemiskinan <- as.data.frame(read_excel(
  "C:/Users/Kasmin Jamain/Downloads/SDM REKENG.xlsx",
  sheet = "Sheet1"
))
peta <- st_read(
  "C:/Users/Kasmin Jamain/Downloads/jatim_kabkota.geojson"
)
## Reading layer `jatim_kabkota' from data source 
##   `C:\Users\Kasmin Jamain\Downloads\jatim_kabkota.geojson' using driver `GeoJSON'
## Simple feature collection with 38 features and 2 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: 110.8987 ymin: -8.78036 xmax: 116.2702 ymax: -5.048857
## Geodetic CRS:  WGS 84
# Nama kolom sesuai urutan Excel
names(data_kemiskinan) <- c("Kab_Kota", "Y", "X1", "X2", "X3",
                            "X4", "X5", "Latitude", "Longitude")
# Y = Persentase penduduk miskin
# X1 = Gini rasio
# X2 = Rata-rata lama sekolah
# X3 = Tingkat pengangguran terbuka
# X4 = Pengeluaran riil per kapita disesuaikan (ribu rupiah/tahun)
# X5 = Umur harapan hidup
kolom <- c("Y", "X1", "X2", "X3", "X4", "X5")
prediktor <- kolom[-1]

# Konversi karena Y dan X2 terbaca sebagai teks di Excel
for (v in kolom) {
  data_kemiskinan[[v]] <- as.numeric(data_kemiskinan[[v]])
}
head(data_kemiskinan)
##      Kab_Kota     Y    X1   X2   X3    X4    X5 Latitude Longitude
## 1     Pacitan 12.97 0.365 7.91 1.40 10756 74.98 -8.19285  111.1035
## 2    Ponorogo  8.86 0.329 7.95 3.85 11561 75.61 -7.86994  111.4628
## 3  Trenggalek 10.29 0.359 8.09 3.86 11322 75.63 -8.04889  111.7106
## 4 Tulungagung  5.96 0.291 8.69 4.03 12505 75.51 -8.06623  111.9027
## 5      Blitar  7.57 0.351 8.01 4.49 12633 75.63 -8.12992  112.2134
## 6      Kediri  9.81 0.334 8.38 4.71 12968 75.41 -7.80915  112.0422
str(data_kemiskinan)
## 'data.frame':    38 obs. of  9 variables:
##  $ Kab_Kota : chr  "Pacitan" "Ponorogo" "Trenggalek" "Tulungagung" ...
##  $ Y        : num  12.97 8.86 10.29 5.96 7.57 ...
##  $ X1       : num  0.365 0.329 0.359 0.291 0.351 0.334 0.35 0.305 0.368 0.29 ...
##  $ X2       : num  7.91 7.95 8.09 8.69 8.01 8.38 7.98 7.28 6.64 7.84 ...
##  $ X3       : num  1.4 3.85 3.86 4.03 4.49 4.71 5 3.08 3.07 3.94 ...
##  $ X4       : num  10756 11561 11322 12505 12633 ...
##  $ X5       : num  75 75.6 75.6 75.5 75.6 ...
##  $ Latitude : num  -8.19 -7.87 -8.05 -8.07 -8.13 ...
##  $ Longitude: num  111 111 112 112 112 ...
dim(data_kemiskinan)
## [1] 38  9
colSums(is.na(data_kemiskinan))
##  Kab_Kota         Y        X1        X2        X3        X4        X5  Latitude 
##         0         0         0         0         0         0         0         0 
## Longitude 
##         0
sum(duplicated(data_kemiskinan$Kab_Kota))
## [1] 0
stopifnot(nrow(data_kemiskinan) == 38,
          !anyNA(data_kemiskinan[kolom]),
          all(is.finite(as.matrix(data_kemiskinan[kolom]))))

# Memeriksa peta. Tidak memperbaiki geometri yang sudah valid.
head(st_drop_geometry(peta))
##      Wilayah KODE
## 1  Bangkalan 3526
## 2 Banyuwangi 3510
## 3  Kota Batu 3579
## 4     Blitar 3505
## 5 Bojonegoro 3522
## 6  Bondowoso 3511
names(peta)
## [1] "Wilayah"  "KODE"     "geometry"
st_crs(peta)
## Coordinate Reference System:
##   User input: WGS 84 
##   wkt:
## GEOGCRS["WGS 84",
##     DATUM["World Geodetic System 1984",
##         ELLIPSOID["WGS 84",6378137,298.257223563,
##             LENGTHUNIT["metre",1]]],
##     PRIMEM["Greenwich",0,
##         ANGLEUNIT["degree",0.0174532925199433]],
##     CS[ellipsoidal,2],
##         AXIS["geodetic latitude (Lat)",north,
##             ORDER[1],
##             ANGLEUNIT["degree",0.0174532925199433]],
##         AXIS["geodetic longitude (Lon)",east,
##             ORDER[2],
##             ANGLEUNIT["degree",0.0174532925199433]],
##     ID["EPSG",4326]]
table(st_geometry_type(peta))
## 
##           GEOMETRY              POINT         LINESTRING            POLYGON 
##                  0                  0                  0                  0 
##         MULTIPOINT    MULTILINESTRING       MULTIPOLYGON GEOMETRYCOLLECTION 
##                  0                  0                 38                  0 
##     CIRCULARSTRING      COMPOUNDCURVE       CURVEPOLYGON         MULTICURVE 
##                  0                  0                  0                  0 
##       MULTISURFACE              CURVE            SURFACE  POLYHEDRALSURFACE 
##                  0                  0                  0                  0 
##                TIN           TRIANGLE 
##                  0                  0
table(st_is_valid(peta))
## 
## TRUE 
##   38
sum(st_is_empty(peta))
## [1] 0
stopifnot(nrow(peta) == 38, all(st_is_valid(peta)),
          !any(st_is_empty(peta)), !anyDuplicated(peta$KODE),
          all(st_geometry_type(peta) %in% c("POLYGON", "MULTIPOLYGON")))

# Menyamakan pengenal wilayah dan mempertahankan urutan Excel
kode_excel <- trimws(as.character(data_kemiskinan$Kab_Kota))
kode_peta <- trimws(as.character(peta$Wilayah))
setdiff(kode_excel, kode_peta)
## character(0)
setdiff(kode_peta, kode_excel)
## character(0)
stopifnot(!anyNA(c(kode_excel, kode_peta)),
          all(nzchar(c(kode_excel, kode_peta))),
          !anyDuplicated(kode_excel), !anyDuplicated(kode_peta),
          setequal(kode_excel, kode_peta))
urut <- match(kode_excel, kode_peta)
peta <- peta[urut, ]
peta$Kab_Kota <- kode_excel
for (v in c(kolom, "Latitude", "Longitude")) peta[[v]] <- data_kemiskinan[[v]]
rownames(peta) <- kode_excel
stopifnot(identical(as.character(peta$Wilayah), kode_excel) ||
            identical(trimws(as.character(peta$Wilayah)), kode_excel))
head(st_drop_geometry(peta)[c("Kab_Kota", kolom)])
##                Kab_Kota     Y    X1   X2   X3    X4    X5
## Pacitan         Pacitan 12.97 0.365 7.91 1.40 10756 74.98
## Ponorogo       Ponorogo  8.86 0.329 7.95 3.85 11561 75.61
## Trenggalek   Trenggalek 10.29 0.359 8.09 3.86 11322 75.63
## Tulungagung Tulungagung  5.96 0.291 8.69 4.03 12505 75.51
## Blitar           Blitar  7.57 0.351 8.01 4.49 12633 75.63
## Kediri           Kediri  9.81 0.334 8.38 4.71 12968 75.41
# 2. EKSPLORASI DATA ----------------------------------------
data_deskriptif <- st_drop_geometry(peta)[kolom]
summary(data_deskriptif)
##        Y                X1               X2               X3       
##  Min.   : 2.860   Min.   :0.2210   Min.   : 5.190   Min.   :1.330  
##  1st Qu.: 6.143   1st Qu.:0.2983   1st Qu.: 7.487   1st Qu.:3.115  
##  Median : 8.825   Median :0.3215   Median : 8.150   Median :3.855  
##  Mean   : 9.481   Mean   :0.3206   Mean   : 8.555   Mean   :3.780  
##  3rd Qu.:11.895   3rd Qu.:0.3493   3rd Qu.: 9.895   3rd Qu.:4.565  
##  Max.   :20.610   Max.   :0.3940   Max.   :12.120   Max.   :5.750  
##        X4              X5       
##  Min.   :10030   Min.   :73.47  
##  1st Qu.:11689   1st Qu.:74.68  
##  Median :12900   Median :75.22  
##  Mean   :13301   Mean   :75.10  
##  3rd Qu.:14465   3rd Qu.:75.63  
##  Max.   :20679   Max.   :76.34
deskriptif <- data.frame(
  Variabel = kolom,
  Minimum = sapply(data_deskriptif, min),
  Maksimum = sapply(data_deskriptif, max),
  Mean = sapply(data_deskriptif, mean),
  Median = sapply(data_deskriptif, median),
  SD = sapply(data_deskriptif, sd), row.names = NULL
)
print(deskriptif, row.names = FALSE)
##  Variabel   Minimum  Maksimum         Mean     Median           SD
##         Y     2.860    20.610 9.480789e+00     8.8250 4.206419e+00
##        X1     0.221     0.394 3.205789e-01     0.3215 3.777575e-02
##        X2     5.190    12.120 8.555000e+00     8.1500 1.702454e+00
##        X3     1.330     5.750 3.779737e+00     3.8550 1.112758e+00
##        X4 10030.000 20679.000 1.330092e+04 12900.0000 2.403498e+03
##        X5    73.470    76.340 7.509658e+01    75.2150 7.948764e-01
write.csv(deskriptif, file.path(folder, "Statistik_Deskriptif.csv"), row.names = FALSE)

# Boxplot masing-masing variabel
satuan <- c(Y = "Persen", X1 = "Indeks", X2 = "Tahun",
            X3 = "Persen", X4 = "Ribu rupiah/tahun", X5 = "Tahun")
par_lama <- par(mfrow = c(2, 3))
for (v in kolom) {
  boxplot(data_deskriptif[[v]], main = v, ylab = satuan[[v]], col = "lightblue")
}

par(par_lama)

# 3. VISUALISASI PETA ---------------------------------------
plot(st_geometry(peta), col = "lightblue", border = "grey40",
     main = "Peta Provinsi Jawa Timur")

judul <- c(Y = "Sebaran Persentase Penduduk Miskin",
           X1 = "Sebaran Gini Rasio",
           X2 = "Sebaran Rata-rata Lama Sekolah",
           X3 = "Sebaran Tingkat Pengangguran Terbuka",
           X4 = "Sebaran Pengeluaran Riil per Kapita",
           X5 = "Sebaran Umur Harapan Hidup")

# Peta tematik dengan gaya gradasi hijau seperti sintaks teman.
# Proyeksi UTM 49S untuk peta dan perhitungan centroid poligon.
peta_visual <- st_transform(peta, 32749)
for (v in names(judul)) {
  gambar <- ggplot(peta_visual) +
    geom_sf(aes(fill = .data[[v]]), colour = "grey40", linewidth = 0.18) +
    scale_fill_gradient(low = "#E5F5E0", high = "#005A32",
                        name = satuan[[v]], na.value = "grey85") +
    labs(title = judul[[v]], subtitle = "Kabupaten/Kota di Jawa Timur") +
    coord_sf(datum = NA) +
    guides(fill = guide_colourbar(title.position = "top", title.hjust = 0.5,
                                  barwidth = grid::unit(7, "cm"),
                                  barheight = grid::unit(0.4, "cm"))) +
    theme_void() +
    theme(legend.position = "bottom",
          plot.title = element_text(face = "bold", size = 15,
                                    colour = "#123B29", hjust = 0.5),
          plot.subtitle = element_text(size = 11, hjust = 0.5),
          plot.margin = margin(15, 15, 15, 15))
  print(gambar)
  ggsave(file.path(folder, paste0("Peta_", v, "_Jawa_Timur.png")),
         plot = gambar, width = 9, height = 6, dpi = 300, bg = "white")
}

## Warning in grDevices::dev.off(): agg could not write to the given file

# 4. REGRESI KLASIK DAN UJI ASUMSI ---------------------------
peta_model <- peta
data_model <- st_drop_geometry(peta_model)
rownames(data_model) <- peta_model$Kab_Kota
rumus <- Y ~ X1 + X2 + X3 + X4 + X5
reg.klasik <- lm(rumus, data = data_model)
galat <- residuals(reg.klasik)
summary(reg.klasik)
## 
## Call:
## lm(formula = rumus, data = data_model)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -5.0021 -1.4694  0.0845  1.4574  4.4518 
## 
## Coefficients:
##               Estimate Std. Error t value Pr(>|t|)  
## (Intercept)  5.327e+01  6.390e+01   0.834   0.4107  
## X1          -1.077e+01  1.243e+01  -0.866   0.3927  
## X2          -1.643e+00  6.364e-01  -2.581   0.0146 *
## X3          -3.844e-01  4.712e-01  -0.816   0.4206  
## X4          -1.463e-05  3.671e-04  -0.040   0.9685  
## X5          -3.281e-01  8.937e-01  -0.367   0.7159  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 2.539 on 32 degrees of freedom
## Multiple R-squared:  0.6848, Adjusted R-squared:  0.6355 
## F-statistic:  13.9 on 5 and 32 DF,  p-value: 3.021e-07
# Korelasi dan multikolinearitas
cor(data_model[prediktor])
##           X1        X2        X3        X4        X5
## X1 1.0000000 0.3885314 0.1725423 0.3849039 0.4174661
## X2 0.3885314 1.0000000 0.5760541 0.8681724 0.7886784
## X3 0.1725423 0.5760541 1.0000000 0.5742175 0.4772212
## X4 0.3849039 0.8681724 0.5742175 1.0000000 0.6316769
## X5 0.4174661 0.7886784 0.4772212 0.6316769 1.0000000
pairs(data_model[prediktor], pch = 19, col = "darkgreen",
      main = "Hubungan Antarvariabel Independen")

car::vif(reg.klasik)
##       X1       X2       X3       X4       X5 
## 1.265622 6.734116 1.577163 4.467279 2.895149
# Normalitas
qqnorm(galat, main = "Q-Q Plot Galat OLS")
qqline(galat, col = "red")

shapiro_ols <- shapiro.test(galat)
print(shapiro_ols)
## 
##  Shapiro-Wilk normality test
## 
## data:  galat
## W = 0.98021, p-value = 0.7251
# Jarque-Bera manual sesuai modul
z <- (galat - mean(galat)) / sqrt(mean((galat - mean(galat))^2))
JB <- length(z) / 6 * (mean(z^3)^2 + (mean(z^4) - 3)^2 / 4)
c(JB = JB, p_value = pchisq(JB, df = 2, lower.tail = FALSE))
##        JB   p_value 
## 0.6724963 0.7144458
# Breusch-Pagan studentized manual sesuai modul
data_bp <- model.frame(reg.klasik)
data_bp$galat2 <- galat^2
reg_bp <- lm(galat2 ~ X1 + X2 + X3 + X4 + X5, data = data_bp)
BP <- nobs(reg_bp) * summary(reg_bp)$r.squared
p_BP <- pchisq(BP, df = 5, lower.tail = FALSE)
c(BP = BP, p_value = p_BP)
##         BP    p_value 
## 9.95898494 0.07640577
# 5. MATRIKS PEMBOBOT K-NEAREST NEIGHBOR ---------------------
# KNN memungkinkan tetangga lintas laut, berbeda dengan Queen.
# Titik acuan adalah centroid poligon terbesar setiap kabupaten/kota,
# sesuai modul hlm. 15-16. Centroid dihitung dalam UTM 49S.
# Jarak KNN dihitung pada koordinat geografis (WGS84/s2).
# Koordinat Excel tidak digunakan untuk W karena dua titik berada
# di luar poligon wilayah masing-masing (Pasuruan dan Mojokerto).
peta_plot <- st_transform(peta_model, 32749)
titik_utm <- st_centroid(st_geometry(peta_plot), of_largest_polygon = TRUE)
titik_knn <- st_transform(titik_utm, 4326)
koordinat <- st_coordinates(titik_utm)
stopifnot(!anyDuplicated(st_coordinates(titik_knn)))

# k = 4 sebagai spesifikasi awal seperti analisis KNN sebelumnya,
# bukan hasil pencarian p-value atau AIC. Cek keterhubungan jaringan.
sf::sf_use_s2(TRUE)
k <- 4
knn_hasil <- spdep::knearneigh(titik_knn, k = k)
knn.nb <- spdep::knn2nb(knn_hasil, row.names = peta_model$Kab_Kota,
                        sym = FALSE)
summary(knn.nb)
## Neighbour list object:
## Number of regions: 38 
## Number of nonzero links: 152 
## Percentage nonzero weights: 10.52632 
## Average number of links: 4 
## Non-symmetric neighbours list
## Link number distribution:
## 
##  4 
## 38 
## 38 least connected regions:
## Pacitan Ponorogo Trenggalek Tulungagung Blitar Kediri Malang Lumajang Jember Banyuwangi Bondowoso Situbondo Probolinggo Pasuruan Sidoarjo Mojokerto Jombang Nganjuk Madiun Magetan Ngawi Bojonegoro Tuban Lamongan Gresik Bangkalan Sampang Pamekasan Sumenep Kota Kediri Kota Blitar Kota Malang Kota Probolinggo Kota Pasuruan Kota Mojokerto Kota Madiun Kota Surabaya Kota Batu with 4 links
## 38 most connected regions:
## Pacitan Ponorogo Trenggalek Tulungagung Blitar Kediri Malang Lumajang Jember Banyuwangi Bondowoso Situbondo Probolinggo Pasuruan Sidoarjo Mojokerto Jombang Nganjuk Madiun Magetan Ngawi Bojonegoro Tuban Lamongan Gresik Bangkalan Sampang Pamekasan Sumenep Kota Kediri Kota Blitar Kota Malang Kota Probolinggo Kota Pasuruan Kota Mojokerto Kota Madiun Kota Surabaya Kota Batu with 4 links
card(knn.nb)
##  [1] 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
peta_model$Kab_Kota[card(knn.nb) == 0]
## character(0)
komponen <- n.comp.nb(knn.nb)
komponen$nc
## [1] 1
split(peta_model$Kab_Kota, komponen$comp.id)
## $`1`
##  [1] "Pacitan"          "Ponorogo"         "Trenggalek"       "Tulungagung"     
##  [5] "Blitar"           "Kediri"           "Malang"           "Lumajang"        
##  [9] "Jember"           "Banyuwangi"       "Bondowoso"        "Situbondo"       
## [13] "Probolinggo"      "Pasuruan"         "Sidoarjo"         "Mojokerto"       
## [17] "Jombang"          "Nganjuk"          "Madiun"           "Magetan"         
## [21] "Ngawi"            "Bojonegoro"       "Tuban"            "Lamongan"        
## [25] "Gresik"           "Bangkalan"        "Sampang"          "Pamekasan"       
## [29] "Sumenep"          "Kota Kediri"      "Kota Blitar"      "Kota Malang"     
## [33] "Kota Probolinggo" "Kota Pasuruan"    "Kota Mojokerto"   "Kota Madiun"     
## [37] "Kota Surabaya"    "Kota Batu"
stopifnot(all(card(knn.nb) == k))

# Pembobot biner dan pembobot terstandardisasi per baris
knn.w <- spdep::nb2listw(knn.nb, style = "W")
W_biner <- nb2mat(knn.nb, style = "B")
W <- listw2mat(knn.w)
dim(W)
## [1] 38 38
round(W, 4)
##                  Pacitan Ponorogo Trenggalek Tulungagung Blitar Kediri Malang
## Pacitan             0.00     0.25       0.25        0.00   0.00   0.00   0.00
## Ponorogo            0.00     0.00       0.25        0.00   0.00   0.00   0.00
## Trenggalek          0.25     0.25       0.00        0.25   0.00   0.00   0.00
## Tulungagung         0.00     0.00       0.25        0.00   0.25   0.00   0.00
## Blitar              0.00     0.00       0.00        0.25   0.00   0.25   0.00
## Kediri              0.00     0.00       0.00        0.00   0.00   0.00   0.00
## Malang              0.00     0.00       0.00        0.00   0.25   0.00   0.00
## Lumajang            0.00     0.00       0.00        0.00   0.00   0.00   0.25
## Jember              0.00     0.00       0.00        0.00   0.00   0.00   0.00
## Banyuwangi          0.00     0.00       0.00        0.00   0.00   0.00   0.00
## Bondowoso           0.00     0.00       0.00        0.00   0.00   0.00   0.00
## Situbondo           0.00     0.00       0.00        0.00   0.00   0.00   0.00
## Probolinggo         0.00     0.00       0.00        0.00   0.00   0.00   0.00
## Pasuruan            0.00     0.00       0.00        0.00   0.00   0.00   0.00
## Sidoarjo            0.00     0.00       0.00        0.00   0.00   0.00   0.00
## Mojokerto           0.00     0.00       0.00        0.00   0.00   0.00   0.00
## Jombang             0.00     0.00       0.00        0.00   0.00   0.25   0.00
## Nganjuk             0.00     0.00       0.00        0.00   0.00   0.25   0.00
## Madiun              0.00     0.25       0.00        0.00   0.00   0.00   0.00
## Magetan             0.00     0.25       0.00        0.00   0.00   0.00   0.00
## Ngawi               0.00     0.00       0.00        0.00   0.00   0.00   0.00
## Bojonegoro          0.00     0.00       0.00        0.00   0.00   0.00   0.00
## Tuban               0.00     0.00       0.00        0.00   0.00   0.00   0.00
## Lamongan            0.00     0.00       0.00        0.00   0.00   0.00   0.00
## Gresik              0.00     0.00       0.00        0.00   0.00   0.00   0.00
## Bangkalan           0.00     0.00       0.00        0.00   0.00   0.00   0.00
## Sampang             0.00     0.00       0.00        0.00   0.00   0.00   0.00
## Pamekasan           0.00     0.00       0.00        0.00   0.00   0.00   0.00
## Sumenep             0.00     0.00       0.00        0.00   0.00   0.00   0.00
## Kota Kediri         0.00     0.00       0.00        0.25   0.00   0.25   0.00
## Kota Blitar         0.00     0.00       0.00        0.25   0.25   0.25   0.00
## Kota Malang         0.00     0.00       0.00        0.00   0.25   0.00   0.25
## Kota Probolinggo    0.00     0.00       0.00        0.00   0.00   0.00   0.00
## Kota Pasuruan       0.00     0.00       0.00        0.00   0.00   0.00   0.00
## Kota Mojokerto      0.00     0.00       0.00        0.00   0.00   0.00   0.00
## Kota Madiun         0.00     0.25       0.00        0.00   0.00   0.00   0.00
## Kota Surabaya       0.00     0.00       0.00        0.00   0.00   0.00   0.00
## Kota Batu           0.00     0.00       0.00        0.00   0.00   0.00   0.25
##                  Lumajang Jember Banyuwangi Bondowoso Situbondo Probolinggo
## Pacitan              0.00   0.00       0.00      0.00      0.00        0.00
## Ponorogo             0.00   0.00       0.00      0.00      0.00        0.00
## Trenggalek           0.00   0.00       0.00      0.00      0.00        0.00
## Tulungagung          0.00   0.00       0.00      0.00      0.00        0.00
## Blitar               0.00   0.00       0.00      0.00      0.00        0.00
## Kediri               0.00   0.00       0.00      0.00      0.00        0.00
## Malang               0.00   0.00       0.00      0.00      0.00        0.00
## Lumajang             0.00   0.00       0.00      0.00      0.00        0.25
## Jember               0.25   0.00       0.25      0.25      0.00        0.25
## Banyuwangi           0.00   0.25       0.00      0.25      0.25        0.25
## Bondowoso            0.00   0.25       0.25      0.00      0.25        0.25
## Situbondo            0.00   0.25       0.25      0.25      0.00        0.25
## Probolinggo          0.25   0.25       0.00      0.00      0.00        0.00
## Pasuruan             0.00   0.00       0.00      0.00      0.00        0.00
## Sidoarjo             0.00   0.00       0.00      0.00      0.00        0.00
## Mojokerto            0.00   0.00       0.00      0.00      0.00        0.00
## Jombang              0.00   0.00       0.00      0.00      0.00        0.00
## Nganjuk              0.00   0.00       0.00      0.00      0.00        0.00
## Madiun               0.00   0.00       0.00      0.00      0.00        0.00
## Magetan              0.00   0.00       0.00      0.00      0.00        0.00
## Ngawi                0.00   0.00       0.00      0.00      0.00        0.00
## Bojonegoro           0.00   0.00       0.00      0.00      0.00        0.00
## Tuban                0.00   0.00       0.00      0.00      0.00        0.00
## Lamongan             0.00   0.00       0.00      0.00      0.00        0.00
## Gresik               0.00   0.00       0.00      0.00      0.00        0.00
## Bangkalan            0.00   0.00       0.00      0.00      0.00        0.00
## Sampang              0.00   0.00       0.00      0.00      0.00        0.00
## Pamekasan            0.00   0.00       0.00      0.00      0.00        0.00
## Sumenep              0.00   0.00       0.00      0.00      0.25        0.00
## Kota Kediri          0.00   0.00       0.00      0.00      0.00        0.00
## Kota Blitar          0.00   0.00       0.00      0.00      0.00        0.00
## Kota Malang          0.00   0.00       0.00      0.00      0.00        0.00
## Kota Probolinggo     0.25   0.00       0.00      0.00      0.00        0.25
## Kota Pasuruan        0.00   0.00       0.00      0.00      0.00        0.00
## Kota Mojokerto       0.00   0.00       0.00      0.00      0.00        0.00
## Kota Madiun          0.00   0.00       0.00      0.00      0.00        0.00
## Kota Surabaya        0.00   0.00       0.00      0.00      0.00        0.00
## Kota Batu            0.00   0.00       0.00      0.00      0.00        0.00
##                  Pasuruan Sidoarjo Mojokerto Jombang Nganjuk Madiun Magetan
## Pacitan              0.00     0.00      0.00    0.00    0.00   0.00    0.25
## Ponorogo             0.00     0.00      0.00    0.00    0.00   0.25    0.25
## Trenggalek           0.00     0.00      0.00    0.00    0.00   0.00    0.00
## Tulungagung          0.00     0.00      0.00    0.00    0.00   0.00    0.00
## Blitar               0.00     0.00      0.00    0.00    0.00   0.00    0.00
## Kediri               0.00     0.00      0.00    0.25    0.25   0.00    0.00
## Malang               0.25     0.00      0.00    0.00    0.00   0.00    0.00
## Lumajang             0.25     0.00      0.00    0.00    0.00   0.00    0.00
## Jember               0.00     0.00      0.00    0.00    0.00   0.00    0.00
## Banyuwangi           0.00     0.00      0.00    0.00    0.00   0.00    0.00
## Bondowoso            0.00     0.00      0.00    0.00    0.00   0.00    0.00
## Situbondo            0.00     0.00      0.00    0.00    0.00   0.00    0.00
## Probolinggo          0.00     0.00      0.00    0.00    0.00   0.00    0.00
## Pasuruan             0.00     0.25      0.00    0.00    0.00   0.00    0.00
## Sidoarjo             0.00     0.00      0.25    0.00    0.00   0.00    0.00
## Mojokerto            0.00     0.25      0.00    0.25    0.00   0.00    0.00
## Jombang              0.00     0.00      0.25    0.00    0.25   0.00    0.00
## Nganjuk              0.00     0.00      0.00    0.25    0.00   0.25    0.00
## Madiun               0.00     0.00      0.00    0.00    0.25   0.00    0.25
## Magetan              0.00     0.00      0.00    0.00    0.00   0.25    0.00
## Ngawi                0.00     0.00      0.00    0.00    0.00   0.25    0.25
## Bojonegoro           0.00     0.00      0.00    0.00    0.25   0.25    0.00
## Tuban                0.00     0.00      0.00    0.00    0.25   0.00    0.00
## Lamongan             0.00     0.00      0.00    0.25    0.00   0.00    0.00
## Gresik               0.00     0.25      0.00    0.00    0.00   0.00    0.00
## Bangkalan            0.00     0.25      0.00    0.00    0.00   0.00    0.00
## Sampang              0.00     0.00      0.00    0.00    0.00   0.00    0.00
## Pamekasan            0.00     0.00      0.00    0.00    0.00   0.00    0.00
## Sumenep              0.00     0.00      0.00    0.00    0.00   0.00    0.00
## Kota Kediri          0.00     0.00      0.00    0.00    0.25   0.00    0.00
## Kota Blitar          0.00     0.00      0.00    0.00    0.00   0.00    0.00
## Kota Malang          0.25     0.00      0.00    0.00    0.00   0.00    0.00
## Kota Probolinggo     0.25     0.00      0.00    0.00    0.00   0.00    0.00
## Kota Pasuruan        0.25     0.25      0.00    0.00    0.00   0.00    0.00
## Kota Mojokerto       0.00     0.25      0.25    0.25    0.00   0.00    0.00
## Kota Madiun          0.00     0.00      0.00    0.00    0.00   0.25    0.25
## Kota Surabaya        0.00     0.25      0.00    0.00    0.00   0.00    0.00
## Kota Batu            0.25     0.00      0.25    0.00    0.00   0.00    0.00
##                  Ngawi Bojonegoro Tuban Lamongan Gresik Bangkalan Sampang
## Pacitan           0.00       0.00  0.00     0.00   0.00      0.00    0.00
## Ponorogo          0.00       0.00  0.00     0.00   0.00      0.00    0.00
## Trenggalek        0.00       0.00  0.00     0.00   0.00      0.00    0.00
## Tulungagung       0.00       0.00  0.00     0.00   0.00      0.00    0.00
## Blitar            0.00       0.00  0.00     0.00   0.00      0.00    0.00
## Kediri            0.00       0.00  0.00     0.00   0.00      0.00    0.00
## Malang            0.00       0.00  0.00     0.00   0.00      0.00    0.00
## Lumajang          0.00       0.00  0.00     0.00   0.00      0.00    0.00
## Jember            0.00       0.00  0.00     0.00   0.00      0.00    0.00
## Banyuwangi        0.00       0.00  0.00     0.00   0.00      0.00    0.00
## Bondowoso         0.00       0.00  0.00     0.00   0.00      0.00    0.00
## Situbondo         0.00       0.00  0.00     0.00   0.00      0.00    0.00
## Probolinggo       0.00       0.00  0.00     0.00   0.00      0.00    0.00
## Pasuruan          0.00       0.00  0.00     0.00   0.00      0.00    0.00
## Sidoarjo          0.00       0.00  0.00     0.00   0.00      0.00    0.00
## Mojokerto         0.00       0.00  0.00     0.00   0.00      0.00    0.00
## Jombang           0.00       0.00  0.00     0.00   0.00      0.00    0.00
## Nganjuk           0.00       0.00  0.00     0.00   0.00      0.00    0.00
## Madiun            0.00       0.00  0.00     0.00   0.00      0.00    0.00
## Magetan           0.25       0.00  0.00     0.00   0.00      0.00    0.00
## Ngawi             0.00       0.25  0.00     0.00   0.00      0.00    0.00
## Bojonegoro        0.00       0.00  0.25     0.00   0.00      0.00    0.00
## Tuban             0.00       0.25  0.00     0.25   0.25      0.00    0.00
## Lamongan          0.00       0.00  0.00     0.00   0.25      0.00    0.00
## Gresik            0.00       0.00  0.00     0.25   0.00      0.00    0.00
## Bangkalan         0.00       0.00  0.00     0.00   0.25      0.00    0.25
## Sampang           0.00       0.00  0.00     0.00   0.00      0.25    0.00
## Pamekasan         0.00       0.00  0.00     0.00   0.00      0.25    0.25
## Sumenep           0.00       0.00  0.00     0.00   0.00      0.25    0.25
## Kota Kediri       0.00       0.00  0.00     0.00   0.00      0.00    0.00
## Kota Blitar       0.00       0.00  0.00     0.00   0.00      0.00    0.00
## Kota Malang       0.00       0.00  0.00     0.00   0.00      0.00    0.00
## Kota Probolinggo  0.00       0.00  0.00     0.00   0.00      0.00    0.00
## Kota Pasuruan     0.00       0.00  0.00     0.00   0.00      0.00    0.00
## Kota Mojokerto    0.00       0.00  0.00     0.00   0.25      0.00    0.00
## Kota Madiun       0.25       0.00  0.00     0.00   0.00      0.00    0.00
## Kota Surabaya     0.00       0.00  0.00     0.00   0.25      0.25    0.00
## Kota Batu         0.00       0.00  0.00     0.00   0.00      0.00    0.00
##                  Pamekasan Sumenep Kota Kediri Kota Blitar Kota Malang
## Pacitan               0.00    0.00        0.00        0.00        0.00
## Ponorogo              0.00    0.00        0.00        0.00        0.00
## Trenggalek            0.00    0.00        0.25        0.00        0.00
## Tulungagung           0.00    0.00        0.25        0.25        0.00
## Blitar                0.00    0.00        0.25        0.25        0.00
## Kediri                0.00    0.00        0.25        0.25        0.00
## Malang                0.00    0.00        0.00        0.00        0.25
## Lumajang              0.00    0.00        0.00        0.00        0.00
## Jember                0.00    0.00        0.00        0.00        0.00
## Banyuwangi            0.00    0.00        0.00        0.00        0.00
## Bondowoso             0.00    0.00        0.00        0.00        0.00
## Situbondo             0.00    0.00        0.00        0.00        0.00
## Probolinggo           0.00    0.00        0.00        0.00        0.00
## Pasuruan              0.00    0.00        0.00        0.00        0.25
## Sidoarjo              0.00    0.00        0.00        0.00        0.00
## Mojokerto             0.00    0.00        0.00        0.00        0.00
## Jombang               0.00    0.00        0.00        0.00        0.00
## Nganjuk               0.00    0.00        0.25        0.00        0.00
## Madiun                0.00    0.00        0.00        0.00        0.00
## Magetan               0.00    0.00        0.00        0.00        0.00
## Ngawi                 0.00    0.00        0.00        0.00        0.00
## Bojonegoro            0.00    0.00        0.00        0.00        0.00
## Tuban                 0.00    0.00        0.00        0.00        0.00
## Lamongan              0.00    0.00        0.00        0.00        0.00
## Gresik                0.00    0.00        0.00        0.00        0.00
## Bangkalan             0.00    0.00        0.00        0.00        0.00
## Sampang               0.25    0.25        0.00        0.00        0.00
## Pamekasan             0.00    0.25        0.00        0.00        0.00
## Sumenep               0.25    0.00        0.00        0.00        0.00
## Kota Kediri           0.00    0.00        0.00        0.25        0.00
## Kota Blitar           0.00    0.00        0.25        0.00        0.00
## Kota Malang           0.00    0.00        0.00        0.00        0.00
## Kota Probolinggo      0.00    0.00        0.00        0.00        0.00
## Kota Pasuruan         0.00    0.00        0.00        0.00        0.00
## Kota Mojokerto        0.00    0.00        0.00        0.00        0.00
## Kota Madiun           0.00    0.00        0.00        0.00        0.00
## Kota Surabaya         0.00    0.00        0.00        0.00        0.00
## Kota Batu             0.00    0.00        0.00        0.00        0.25
##                  Kota Probolinggo Kota Pasuruan Kota Mojokerto Kota Madiun
## Pacitan                      0.00          0.00           0.00        0.25
## Ponorogo                     0.00          0.00           0.00        0.25
## Trenggalek                   0.00          0.00           0.00        0.00
## Tulungagung                  0.00          0.00           0.00        0.00
## Blitar                       0.00          0.00           0.00        0.00
## Kediri                       0.00          0.00           0.00        0.00
## Malang                       0.00          0.00           0.00        0.00
## Lumajang                     0.25          0.00           0.00        0.00
## Jember                       0.00          0.00           0.00        0.00
## Banyuwangi                   0.00          0.00           0.00        0.00
## Bondowoso                    0.00          0.00           0.00        0.00
## Situbondo                    0.00          0.00           0.00        0.00
## Probolinggo                  0.25          0.25           0.00        0.00
## Pasuruan                     0.00          0.25           0.00        0.00
## Sidoarjo                     0.00          0.25           0.25        0.00
## Mojokerto                    0.00          0.00           0.25        0.00
## Jombang                      0.00          0.00           0.25        0.00
## Nganjuk                      0.00          0.00           0.00        0.00
## Madiun                       0.00          0.00           0.00        0.25
## Magetan                      0.00          0.00           0.00        0.25
## Ngawi                        0.00          0.00           0.00        0.25
## Bojonegoro                   0.00          0.00           0.00        0.25
## Tuban                        0.00          0.00           0.00        0.00
## Lamongan                     0.00          0.00           0.25        0.00
## Gresik                       0.00          0.00           0.25        0.00
## Bangkalan                    0.00          0.00           0.00        0.00
## Sampang                      0.00          0.00           0.00        0.00
## Pamekasan                    0.25          0.00           0.00        0.00
## Sumenep                      0.00          0.00           0.00        0.00
## Kota Kediri                  0.00          0.00           0.00        0.00
## Kota Blitar                  0.00          0.00           0.00        0.00
## Kota Malang                  0.00          0.00           0.00        0.00
## Kota Probolinggo             0.00          0.25           0.00        0.00
## Kota Pasuruan                0.25          0.00           0.00        0.00
## Kota Mojokerto               0.00          0.00           0.00        0.00
## Kota Madiun                  0.00          0.00           0.00        0.00
## Kota Surabaya                0.00          0.00           0.25        0.00
## Kota Batu                    0.00          0.00           0.00        0.00
##                  Kota Surabaya Kota Batu
## Pacitan                   0.00      0.00
## Ponorogo                  0.00      0.00
## Trenggalek                0.00      0.00
## Tulungagung               0.00      0.00
## Blitar                    0.00      0.00
## Kediri                    0.00      0.00
## Malang                    0.00      0.25
## Lumajang                  0.00      0.00
## Jember                    0.00      0.00
## Banyuwangi                0.00      0.00
## Bondowoso                 0.00      0.00
## Situbondo                 0.00      0.00
## Probolinggo               0.00      0.00
## Pasuruan                  0.00      0.25
## Sidoarjo                  0.25      0.00
## Mojokerto                 0.00      0.25
## Jombang                   0.00      0.00
## Nganjuk                   0.00      0.00
## Madiun                    0.00      0.00
## Magetan                   0.00      0.00
## Ngawi                     0.00      0.00
## Bojonegoro                0.00      0.00
## Tuban                     0.00      0.00
## Lamongan                  0.25      0.00
## Gresik                    0.25      0.00
## Bangkalan                 0.25      0.00
## Sampang                   0.25      0.00
## Pamekasan                 0.00      0.00
## Sumenep                   0.00      0.00
## Kota Kediri               0.00      0.00
## Kota Blitar               0.00      0.00
## Kota Malang               0.00      0.25
## Kota Probolinggo          0.00      0.00
## Kota Pasuruan             0.00      0.25
## Kota Mojokerto            0.00      0.00
## Kota Madiun               0.00      0.00
## Kota Surabaya             0.00      0.00
## Kota Batu                 0.00      0.00
rowSums(W)
##          Pacitan         Ponorogo       Trenggalek      Tulungagung 
##                1                1                1                1 
##           Blitar           Kediri           Malang         Lumajang 
##                1                1                1                1 
##           Jember       Banyuwangi        Bondowoso        Situbondo 
##                1                1                1                1 
##      Probolinggo         Pasuruan         Sidoarjo        Mojokerto 
##                1                1                1                1 
##          Jombang          Nganjuk           Madiun          Magetan 
##                1                1                1                1 
##            Ngawi       Bojonegoro            Tuban         Lamongan 
##                1                1                1                1 
##           Gresik        Bangkalan          Sampang        Pamekasan 
##                1                1                1                1 
##          Sumenep      Kota Kediri      Kota Blitar      Kota Malang 
##                1                1                1                1 
## Kota Probolinggo    Kota Pasuruan   Kota Mojokerto      Kota Madiun 
##                1                1                1                1 
##    Kota Surabaya        Kota Batu 
##                1                1
# KNN berarah: matriks biner tidak harus simetris.
stopifnot(identical(attr(knn.nb, "region.id"), rownames(data_model)),
          all(diag(W) == 0), all(abs(rowSums(W) - 1) < 1e-10),
          all((W > 0) == (W_biner > 0)))
write.csv(W, file.path(folder, "Matriks_KNN.csv"))
write.csv(data.frame(Kab_Kota = peta_model$Kab_Kota,
                     Jumlah_Tetangga = card(knn.nb),
                     Tetangga = sapply(knn.nb, function(i)
                       paste(peta_model$Kab_Kota[i], collapse = "; "))),
          file.path(folder, "Daftar_Tetangga_KNN.csv"), row.names = FALSE)
# Contoh tetangga Bangkalan (Madura)
peta_model$Kab_Kota[knn.nb[[match("Bangkalan", peta_model$Kab_Kota)]]]
## [1] "Sidoarjo"      "Gresik"        "Sampang"       "Kota Surabaya"
# Visualisasi KNN: garis dan titik memakai centroid yang sama dengan W.
plot(st_geometry(peta_plot), col = "#E5F5E0", border = "grey40",
     main = "Ketetanggaan KNN (k = 4) Jawa Timur")
plot(knn.nb, koordinat, add = TRUE, col = "#B22222", lwd = 0.8,
     pch = 19, cex = 0.5)

png(file.path(folder, "Peta_Ketetanggaan_KNN.png"),
    width = 2700, height = 1800, res = 300)
plot(st_geometry(peta_plot), col = "#E5F5E0", border = "grey40",
     main = "Ketetanggaan KNN (k = 4) Jawa Timur")
plot(knn.nb, koordinat, add = TRUE, col = "#B22222", lwd = 0.8,
     pch = 19, cex = 0.5)
dev.off()
## png 
##   2
# 6. UJI MORAN'S I ------------------------------------------
# Uji residual OLS yang memperhitungkan model regresi
moran_ols <- spdep::lm.morantest(reg.klasik, knn.w,
                                 alternative = "two.sided")
print(moran_ols)
## 
##  Global Moran I for regression residuals
## 
## data:  
## model: lm(formula = rumus, data = data_model)
## weights: knn.w
## 
## Moran I statistic standard deviate = 2.9994, p-value = 0.002705
## alternative hypothesis: two.sided
## sample estimates:
## Observed Moran I      Expectation         Variance 
##      0.238578226     -0.047667306      0.009107803
# Uji pembanding sesuai modul
spdep::moran.test(galat, knn.w, randomisation = FALSE,
                  alternative = "two.sided")
## 
##  Moran I test under normality
## 
## data:  galat  
## weights: knn.w    
## 
## Moran I statistic standard deviate = 2.6683, p-value = 0.007624
## alternative hypothesis: two.sided
## sample estimates:
## Moran I statistic       Expectation          Variance 
##       0.238578226      -0.027027027       0.009908468
# Moran Global untuk Y dan semua X
moran_y <- spdep::moran.test(peta_model$Y, knn.w, randomisation = FALSE, alternative = "two.sided")
moran_x1 <- spdep::moran.test(peta_model$X1, knn.w, randomisation = FALSE, alternative = "two.sided")
moran_x2 <- spdep::moran.test(peta_model$X2, knn.w, randomisation = FALSE, alternative = "two.sided")
moran_x3 <- spdep::moran.test(peta_model$X3, knn.w, randomisation = FALSE, alternative = "two.sided")
moran_x4 <- spdep::moran.test(peta_model$X4, knn.w, randomisation = FALSE, alternative = "two.sided")
moran_x5 <- spdep::moran.test(peta_model$X5, knn.w, randomisation = FALSE, alternative = "two.sided")
print(moran_y)
## 
##  Moran I test under normality
## 
## data:  peta_model$Y  
## weights: knn.w    
## 
## Moran I statistic standard deviate = 2.8798, p-value = 0.003979
## alternative hypothesis: two.sided
## sample estimates:
## Moran I statistic       Expectation          Variance 
##       0.259634057      -0.027027027       0.009908468
print(moran_x1)
## 
##  Moran I test under normality
## 
## data:  peta_model$X1  
## weights: knn.w    
## 
## Moran I statistic standard deviate = 0.43919, p-value = 0.6605
## alternative hypothesis: two.sided
## sample estimates:
## Moran I statistic       Expectation          Variance 
##       0.016690325      -0.027027027       0.009908468
print(moran_x2)
## 
##  Moran I test under normality
## 
## data:  peta_model$X2  
## weights: knn.w    
## 
## Moran I statistic standard deviate = 3.1648, p-value = 0.001552
## alternative hypothesis: two.sided
## sample estimates:
## Moran I statistic       Expectation          Variance 
##       0.288001701      -0.027027027       0.009908468
print(moran_x3)
## 
##  Moran I test under normality
## 
## data:  peta_model$X3  
## weights: knn.w    
## 
## Moran I statistic standard deviate = 3.2303, p-value = 0.001236
## alternative hypothesis: two.sided
## sample estimates:
## Moran I statistic       Expectation          Variance 
##       0.294524892      -0.027027027       0.009908468
print(moran_x4)
## 
##  Moran I test under normality
## 
## data:  peta_model$X4  
## weights: knn.w    
## 
## Moran I statistic standard deviate = 1.6021, p-value = 0.1091
## alternative hypothesis: two.sided
## sample estimates:
## Moran I statistic       Expectation          Variance 
##       0.132445211      -0.027027027       0.009908468
print(moran_x5)
## 
##  Moran I test under normality
## 
## data:  peta_model$X5  
## weights: knn.w    
## 
## Moran I statistic standard deviate = 5.6714, p-value = 1.416e-08
## alternative hypothesis: two.sided
## sample estimates:
## Moran I statistic       Expectation          Variance 
##       0.537509924      -0.027027027       0.009908468
daftar_moran <- list(Y = moran_y, X1 = moran_x1, X2 = moran_x2,
                     X3 = moran_x3, X4 = moran_x4, X5 = moran_x5,
                     Residual_OLS = moran_ols)
hasil_moran <- data.frame(
  Variabel = names(daftar_moran),
  Moran_I = sapply(daftar_moran, function(x) unname(x$estimate[1])),
  P_value = sapply(daftar_moran, function(x) unname(x$p.value)),
  row.names = NULL
)
print(hasil_moran)
##       Variabel    Moran_I      P_value
## 1            Y 0.25963406 3.979011e-03
## 2           X1 0.01669032 6.605252e-01
## 3           X2 0.28800170 1.551871e-03
## 4           X3 0.29452489 1.236443e-03
## 5           X4 0.13244521 1.091399e-01
## 6           X5 0.53750992 1.416479e-08
## 7 Residual_OLS 0.23857823 2.705272e-03
write.csv(hasil_moran, file.path(folder, "Hasil_Uji_Moran.csv"), row.names = FALSE)

moran.plot(peta_model$Y, knn.w, labels = peta_model$Kab_Kota,
           main = "Moran Scatterplot Kemiskinan Jawa Timur",
           xlab = "Persentase Penduduk Miskin", ylab = "Spatial Lag Y")

moran.plot(galat, knn.w, labels = peta_model$Kab_Kota,
           main = "Moran Scatterplot Galat OLS")

# 7. UJI LAGRANGE MULTIPLIER DAN ROBUST LM --------------------
LM <- spdep::lm.RStests(reg.klasik, knn.w, test = "all")
summary(LM)
##  Rao's score (a.k.a Lagrange multiplier) diagnostics for spatial
##  dependence
## data:  
## model: lm(formula = rumus, data = data_model)
## test weights: knn.w
##  
##          statistic parameter  p.value   
## RSerr     4.981325         1 0.025622 * 
## RSlag     0.034788         1 0.852040   
## adjRSerr  8.594994         1 0.003371 **
## adjRSlag  3.648458         1 0.056121 . 
## SARMA     8.629782         2 0.013368 * 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
# RSerr = LM Error; RSlag = LM Lag
# adjRSerr = Robust LM Error; adjRSlag = Robust LM Lag
# SARMA = LM gabungan

# 8. PEMODELAN REGRESI DEPENDENSI SPASIAL (ML) ----------------
# Estimasi kandidat untuk perbandingan, bukan kewajiban memilih semua.
sar <- spatialreg::lagsarlm(rumus, data = data_model, listw = knn.w)
summary(sar)
## 
## Call:spatialreg::lagsarlm(formula = rumus, data = data_model, listw = knn.w)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -5.08424 -1.47908  0.14762  1.42380  4.40213 
## 
## Type: lag 
## Coefficients: (asymptotic standard errors) 
##                Estimate  Std. Error z value Pr(>|z|)
## (Intercept)  4.9890e+01  6.4002e+01  0.7795 0.435682
## X1          -1.0302e+01  1.1405e+01 -0.9033 0.366391
## X2          -1.6433e+00  5.8423e-01 -2.8128 0.004911
## X3          -3.4137e-01  4.6104e-01 -0.7404 0.459027
## X4          -2.3005e-05  3.3881e-04 -0.0679 0.945865
## X5          -2.8985e-01  8.8179e-01 -0.3287 0.742375
## 
## Rho: 0.036006, LR test value: 0.039201, p-value: 0.84305
## Asymptotic standard error: 0.1701
##     z-value: 0.21167, p-value: 0.83236
## Wald statistic: 0.044805, p-value: 0.83236
## 
## Log likelihood: -86.04957 for lag model
## ML residual variance (sigma squared): 5.4239, (sigma: 2.3289)
## Number of observations: 38 
## Number of parameters estimated: 8 
## AIC: 188.1, (AIC for lm: 186.14)
## LM test for residual autocorrelation
## test value: 8.6943, p-value: 0.0031921
sem <- spatialreg::errorsarlm(rumus, data = data_model, listw = knn.w)
summary(sem)
## 
## Call:spatialreg::errorsarlm(formula = rumus, data = data_model, listw = knn.w)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -3.87817 -1.39528  0.25931  1.68178  3.25077 
## 
## Type: error 
## Coefficients: (asymptotic standard errors) 
##                Estimate  Std. Error z value  Pr(>|z|)
## (Intercept)  1.3711e+02  5.6341e+01  2.4336 0.0149500
## X1           2.6379e+00  9.1891e+00  0.2871 0.7740611
## X2          -1.6955e+00  4.5789e-01 -3.7029 0.0002132
## X3          -1.9822e-01  3.7706e-01 -0.5257 0.5990967
## X4           6.5202e-05  2.7873e-04  0.2339 0.8150416
## X5          -1.5176e+00  7.7754e-01 -1.9518 0.0509668
## 
## Lambda: 0.64293, LR test value: 7.8098, p-value: 0.0051962
## Asymptotic standard error: 0.13479
##     z-value: 4.7698, p-value: 1.8442e-06
## Wald statistic: 22.751, p-value: 1.8442e-06
## 
## Log likelihood: -82.16425 for error model
## ML residual variance (sigma squared): 3.9821, (sigma: 1.9955)
## Number of observations: 38 
## Number of parameters estimated: 8 
## AIC: 180.33, (AIC for lm: 186.14)
sac <- spatialreg::sacsarlm(rumus, data = data_model, listw = knn.w)
summary(sac)
## 
## Call:spatialreg::sacsarlm(formula = rumus, data = data_model, listw = knn.w)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -3.42261 -1.44288  0.12629  1.66404  3.24179 
## 
## Type: sac 
## Coefficients: (asymptotic standard errors) 
##                Estimate  Std. Error z value  Pr(>|z|)
## (Intercept)  1.4873e+02  5.5181e+01  2.6953 0.0070333
## X1           5.6113e-01  8.9300e+00  0.0628 0.9498970
## X2          -1.5909e+00  4.4883e-01 -3.5445 0.0003933
## X3          -3.6721e-01  3.7837e-01 -0.9705 0.3317927
## X4           8.1674e-05  2.6732e-04  0.3055 0.7599657
## X5          -1.6384e+00  7.5716e-01 -2.1639 0.0304745
## 
## Rho: -0.24352
## Asymptotic standard error: 0.2049
##     z-value: -1.1885, p-value: 0.23465
## Lambda: 0.69266
## Asymptotic standard error: 0.14694
##     z-value: 4.7138, p-value: 2.4311e-06
## 
## LR test value: 9.5112, p-value: 0.0086035
## 
## Log likelihood: -81.31358 for sac model
## ML residual variance (sigma squared): 3.6858, (sigma: 1.9198)
## Number of observations: 38 
## Number of parameters estimated: 9 
## AIC: 180.63, (AIC for lm: 186.14)
sdm <- spatialreg::lagsarlm(rumus, data = data_model, listw = knn.w, type = "mixed")
summary(sdm)
## 
## Call:spatialreg::lagsarlm(formula = rumus, data = data_model, listw = knn.w, 
##     type = "mixed")
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -2.92776 -1.60215 -0.22775  1.55248  3.67664 
## 
## Type: mixed 
## Coefficients: (asymptotic standard errors) 
##                Estimate  Std. Error z value  Pr(>|z|)
## (Intercept) -1.6168e+02  1.4512e+02 -1.1141  0.265254
## X1          -1.4213e+01  1.0150e+01 -1.4003  0.161423
## X2          -2.0225e+00  5.0843e-01 -3.9780 6.951e-05
## X3          -4.9808e-01  4.0641e-01 -1.2256  0.220366
## X4           3.1290e-04  2.8843e-04  1.0848  0.277993
## X5          -1.3479e+00  8.3317e-01 -1.6177  0.105719
## lag.X1      -6.0643e+01  2.2796e+01 -2.6603  0.007808
## lag.X2      -3.8621e-01  1.4431e+00 -0.2676  0.788983
## lag.X3      -5.6401e-01  8.7948e-01 -0.6413  0.521327
## lag.X4       3.5768e-04  6.4222e-04  0.5569  0.577569
## lag.X5       4.1214e+00  1.8774e+00  2.1953  0.028142
## 
## Rho: 0.27425, LR test value: 1.31, p-value: 0.25239
## Asymptotic standard error: 0.19944
##     z-value: 1.3751, p-value: 0.16909
## Wald statistic: 1.8909, p-value: 0.16909
## 
## Log likelihood: -77.21037 for mixed model
## ML residual variance (sigma squared): 3.3553, (sigma: 1.8317)
## Number of observations: 38 
## Number of parameters estimated: 13 
## AIC: 180.42, (AIC for lm: 179.73)
## LM test for residual autocorrelation
## test value: 7.1309, p-value: 0.0075765
sdem <- spatialreg::errorsarlm(rumus, data = data_model, listw = knn.w, etype = "mixed")
summary(sdem)
## 
## Call:spatialreg::errorsarlm(formula = rumus, data = data_model, listw = knn.w, 
##     etype = "mixed")
## 
## Residuals:
##       Min        1Q    Median        3Q       Max 
## -3.059343 -1.818438  0.050342  1.565527  3.244201 
## 
## Type: error 
## Coefficients: (asymptotic standard errors) 
##                Estimate  Std. Error z value  Pr(>|z|)
## (Intercept) -2.1713e+02  1.4216e+02 -1.5273 0.1266742
## X1          -1.9666e+01  9.9801e+00 -1.9705 0.0487774
## X2          -2.1840e+00  5.1330e-01 -4.2548 2.093e-05
## X3          -5.8689e-01  4.1728e-01 -1.4065 0.1595823
## X4           3.6358e-04  2.9427e-04  1.2355 0.2166452
## X5          -1.0659e+00  8.4351e-01 -1.2637 0.2063553
## lag.X1      -8.1787e+01  2.1457e+01 -3.8116 0.0001381
## lag.X2      -1.2485e+00  1.3839e+00 -0.9022 0.3669765
## lag.X3      -7.1566e-01  8.7943e-01 -0.8138 0.4157744
## lag.X4       5.4098e-04  6.4012e-04  0.8451 0.3980422
## lag.X5       4.8131e+00  1.8762e+00  2.5653 0.0103077
## 
## Lambda: -0.10801, LR test value: 0.089025, p-value: 0.76542
## Asymptotic standard error: 0.25581
##     z-value: -0.42221, p-value: 0.67287
## Wald statistic: 0.17826, p-value: 0.67287
## 
## Log likelihood: -77.82087 for error model
## ML residual variance (sigma squared): 3.5109, (sigma: 1.8737)
## Number of observations: 38 
## Number of parameters estimated: 13 
## AIC: 181.64, (AIC for lm: 179.73)
# 9. UJI LIKELIHOOD RATIO -----------------------------------
# Menguji tambahan WX secara simultan pada model tersarang.
# H0: seluruh koefisien WX = 0.
LR_test <- function(model_kecil, model_besar) {
  ll0 <- logLik(model_kecil)
  ll1 <- logLik(model_besar)
  LR <- 2 * (as.numeric(ll1) - as.numeric(ll0))
  df <- attr(ll1, "df") - attr(ll0, "df")
  stopifnot(df > 0, LR >= -1e-6)
  c(LR = max(0, LR), df = df,
    p_value = pchisq(max(0, LR), df = df, lower.tail = FALSE))
}
# SAR vs SDM
LR_test(sar, sdm)
##           LR           df      p_value 
## 17.678414838  5.000000000  0.003377654
# SEM vs SDEM
LR_test(sem, sdem)
##        LR        df   p_value 
## 8.6867590 5.0000000 0.1222297
# SEM vs GSM: H0 rho = 0
LR_test(sem, sac)
##        LR        df   p_value 
## 1.7013295 1.0000000 0.1921142
# 10. PERBANDINGAN MODEL ------------------------------------
# AIC sebagai kriteria utama modul; BIC dan AICc sebagai pembanding.
# Tidak menggunakan RMSE.
hasil_aic <- AIC(reg.klasik, sar, sem, sac, sdm, sdem)
rownames(hasil_aic) <- c("OLS", "SAR", "SEM", "GSM", "SDM", "SDEM")
print(hasil_aic[order(hasil_aic$AIC), ])
##      df      AIC
## SEM   8 180.3285
## SDM  13 180.4207
## GSM   9 180.6272
## SDEM 13 181.6417
## OLS   7 186.1383
## SAR   8 188.0991
hasil_bic <- BIC(reg.klasik, sar, sem, sac, sdm, sdem)
rownames(hasil_bic) <- rownames(hasil_aic)
print(hasil_bic[order(hasil_bic$BIC), ])
##      df      BIC
## SEM   8 193.4292
## GSM   9 195.3654
## OLS   7 197.6015
## SAR   8 201.1998
## SDM  13 201.7094
## SDEM 13 202.9304
# AICc: koreksi untuk sampel kecil, seperti sintaks teman
n <- nobs(reg.klasik)
hasil_aicc <- hasil_aic
hasil_aicc$AICc <- hasil_aicc$AIC +
  (2 * hasil_aicc$df * (hasil_aicc$df + 1)) / (n - hasil_aicc$df - 1)
print(hasil_aicc[order(hasil_aicc$AICc), ])
##      df      AIC     AICc
## SEM   8 180.3285 185.2940
## GSM   9 180.6272 187.0557
## OLS   7 186.1383 189.8717
## SAR   8 188.0991 193.0647
## SDM  13 180.4207 195.5874
## SDEM 13 181.6417 196.8084
# 11. DIAGNOSTIK SEMUA MODEL ---------------------------------
# Nama model ditulis eksplisit agar tidak berubah menjadi angka 1-5.
# as.numeric() menghapus nama bawaan pada hasil Breusch-Pagan.
models_spasial <- list(SAR = sar, SEM = sem, GSM = sac, SDM = sdm, SDEM = sdem)
hasil_diagnostik <- data.frame(
  Model = c("OLS", names(models_spasial)),
  Shapiro = c(shapiro_ols$p.value,
              sapply(models_spasial, function(m) shapiro.test(residuals(m))$p.value)),
  Breusch_Pagan = c(p_BP,
                    sapply(models_spasial, function(m) as.numeric(spatialreg::bptest.Sarlm(m)$p.value))),
  Moran = c(moran_ols$p.value,
            sapply(models_spasial, function(m) spdep::moran.test(
              residuals(m), knn.w, alternative = "two.sided")$p.value)),
  row.names = NULL
)
print(hasil_diagnostik)
##   Model   Shapiro Breusch_Pagan       Moran
## 1   OLS 0.7250649    0.07640577 0.002705272
## 2   SAR 0.7269793    0.08300315 0.011943560
## 3   SEM 0.1229577    0.76418134 0.944123626
## 4   GSM 0.1370217    0.43294929 0.825129374
## 5   SDM 0.1007459    0.26140452 0.480519082
## 6  SDEM 0.1097441    0.13901712 0.811803540
# Urutan model sudah sama pada semua tabel; tidak perlu merge/menu.
stopifnot(identical(hasil_diagnostik$Model, rownames(hasil_aic)))
hasil_evaluasi <- data.frame(
  Model = hasil_diagnostik$Model,
  AIC = hasil_aic$AIC,
  BIC = hasil_bic$BIC,
  AICc = hasil_aicc$AICc,
  Shapiro = hasil_diagnostik$Shapiro,
  Breusch_Pagan = hasil_diagnostik$Breusch_Pagan,
  Moran = hasil_diagnostik$Moran
)
print(hasil_evaluasi[order(hasil_evaluasi$AIC), ], row.names = FALSE)
##  Model      AIC      BIC     AICc   Shapiro Breusch_Pagan       Moran
##    SEM 180.3285 193.4292 185.2940 0.1229577    0.76418134 0.944123626
##    SDM 180.4207 201.7094 195.5874 0.1007459    0.26140452 0.480519082
##    GSM 180.6272 195.3654 187.0557 0.1370217    0.43294929 0.825129374
##   SDEM 181.6417 202.9304 196.8084 0.1097441    0.13901712 0.811803540
##    OLS 186.1383 197.6015 189.8717 0.7250649    0.07640577 0.002705272
##    SAR 188.0991 201.1998 193.0647 0.7269793    0.08300315 0.011943560
write.csv(hasil_evaluasi[order(hasil_evaluasi$AIC), ],
          file.path(folder, "Evaluasi_Seluruh_Model.csv"), row.names = FALSE)

# 12. UJI ASUMSI MODEL TERPILIH (SEM) -------------------------
# Jalankan setelah meninjau tabel evaluasi dan LM di atas.
# SEM adalah kandidat awal berdasarkan perhitungan independen
# KNN centroid k=4. Konfirmasi AIC, BIC, AICc, parameter lambda,
# dan diagnostik dari output R sebelum menetapkan model akhir.
summary(sem)
## 
## Call:spatialreg::errorsarlm(formula = rumus, data = data_model, listw = knn.w)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -3.87817 -1.39528  0.25931  1.68178  3.25077 
## 
## Type: error 
## Coefficients: (asymptotic standard errors) 
##                Estimate  Std. Error z value  Pr(>|z|)
## (Intercept)  1.3711e+02  5.6341e+01  2.4336 0.0149500
## X1           2.6379e+00  9.1891e+00  0.2871 0.7740611
## X2          -1.6955e+00  4.5789e-01 -3.7029 0.0002132
## X3          -1.9822e-01  3.7706e-01 -0.5257 0.5990967
## X4           6.5202e-05  2.7873e-04  0.2339 0.8150416
## X5          -1.5176e+00  7.7754e-01 -1.9518 0.0509668
## 
## Lambda: 0.64293, LR test value: 7.8098, p-value: 0.0051962
## Asymptotic standard error: 0.13479
##     z-value: 4.7698, p-value: 1.8442e-06
## Wald statistic: 22.751, p-value: 1.8442e-06
## 
## Log likelihood: -82.16425 for error model
## ML residual variance (sigma squared): 3.9821, (sigma: 1.9955)
## Number of observations: 38 
## Number of parameters estimated: 8 
## AIC: 180.33, (AIC for lm: 186.14)
galat_sem <- residuals(sem)
par_lama <- par(mfrow = c(1, 2))
hist(galat_sem, main = "Histogram Sisaan SEM", xlab = "Sisaan", col = "lightblue")
qqnorm(galat_sem, main = "Q-Q Plot Sisaan SEM")
qqline(galat_sem, col = "red")

par(par_lama)
shapiro.test(galat_sem)
## 
##  Shapiro-Wilk normality test
## 
## data:  galat_sem
## W = 0.95425, p-value = 0.123
spatialreg::bptest.Sarlm(sem)
## 
##  studentized Breusch-Pagan test
## 
## data:  
## BP = 2.5815, df = 5, p-value = 0.7642
spdep::moran.test(galat_sem, knn.w, alternative = "two.sided")
## 
##  Moran I test under randomisation
## 
## data:  galat_sem  
## weights: knn.w    
## 
## Moran I statistic standard deviate = 0.070088, p-value = 0.9441
## alternative hypothesis: two.sided
## sample estimates:
## Moran I statistic       Expectation          Variance 
##       -0.01995895       -0.02702703        0.01016988
# 13. INTERPRETASI KOEFISIEN SEM ------------------------------
# SEM: Y = X beta + u; u = lambda W u + epsilon.
# Tidak ada WY atau WX pada persamaan rata-rata bersyarat.
# Karena itu efek marginal langsung adalah beta; efek tidak
# langsung prediktor = 0 menurut spesifikasi SEM.
# Lambda menunjukkan ketergantungan pada galat, bukan spillover X.
sem$lambda
##    lambda 
## 0.6429303
summary(sem)$Coef
##                  Estimate   Std. Error    z value     Pr(>|z|)
## (Intercept)  1.371105e+02 5.634088e+01  2.4335872 0.0149500348
## X1           2.637880e+00 9.189079e+00  0.2870669 0.7740611059
## X2          -1.695499e+00 4.578893e-01 -3.7028574 0.0002131847
## X3          -1.982203e-01 3.770598e-01 -0.5256999 0.5990967101
## X4           6.520158e-05 2.787261e-04  0.2339271 0.8150415825
## X5          -1.517567e+00 7.775379e-01 -1.9517594 0.0509667722
beta <- sem$coefficients[prediktor]
efek_sem <- data.frame(Variabel = prediktor, Direct = as.numeric(beta),
                       Indirect = rep(0, length(beta)), Total = as.numeric(beta))
print(efek_sem)
##   Variabel        Direct Indirect         Total
## 1       X1  2.637880e+00        0  2.637880e+00
## 2       X2 -1.695499e+00        0 -1.695499e+00
## 3       X3 -1.982203e-01        0 -1.982203e-01
## 4       X4  6.520158e-05        0  6.520158e-05
## 5       X5 -1.517567e+00        0 -1.517567e+00
# Jika hasil R justru mendukung SAR/GSM/SDM/SDEM, gunakan
# impacts(model_spasial, listw = knn.w) pada model yang dipilih.

# 14. PETA RESIDUAL MODEL SEM --------------------------------
peta_residual <- st_transform(peta_model, 32749)
peta_residual$Residual <- as.numeric(galat_sem)
peta_galat <- ggplot(peta_residual) +
  geom_sf(aes(fill = Residual), colour = "grey40", linewidth = 0.18) +
  scale_fill_gradient2(low = "#2166AC", mid = "#F7F7F7", high = "#B2182B",
                       midpoint = 0, name = "Sisaan (poin persen)") +
  labs(title = "Sebaran Sisaan Spatial Error Model",
       subtitle = "Kabupaten/Kota di Jawa Timur") +
  coord_sf(datum = NA) + theme_void() +
  theme(legend.position = "bottom",
        plot.title = element_text(face = "bold", size = 15, hjust = 0.5),
        plot.subtitle = element_text(hjust = 0.5),
        plot.margin = margin(15, 15, 15, 15))
print(peta_galat)

ggsave(file.path(folder, "Peta_Residual_SEM.png"), plot = peta_galat,
       width = 9, height = 6, dpi = 300, bg = "white")
## Warning in grDevices::dev.off(): agg could not write to the given file
# Simpan kandidat; tetapkan sebagai model akhir setelah verifikasi.
saveRDS(sem, file.path(folder, "Model_Kandidat_SEM.rds"))

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

summary(cars)
##      speed           dist       
##  Min.   : 4.0   Min.   :  2.00  
##  1st Qu.:12.0   1st Qu.: 26.00  
##  Median :15.0   Median : 36.00  
##  Mean   :15.4   Mean   : 42.98  
##  3rd Qu.:19.0   3rd Qu.: 56.00  
##  Max.   :25.0   Max.   :120.00

Including Plots

You can also embed plots, for example:

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.