1. Instalasi dan Pemuatan Paket

pkgs <- c(
  "readxl", "dplyr", "tidyr", "stringr", "zoo",
  "plm", "lmtest", "car", "knitr", "kableExtra"
)

installed <- rownames(installed.packages())
for (p in pkgs) {
  if (!p %in% installed) {
    install.packages(p, dependencies = TRUE)
  }
}

library(readxl)
library(dplyr)
library(tidyr)
library(stringr)
library(zoo)
library(plm)
library(lmtest)
library(car)
library(knitr)
library(kableExtra)

2. Definisi Fungsi Pendukung (CIPS & Pesaran-Yamagata)

parse_num <- function(x) {
  s <- str_trim(as.character(x))
  has_pct <- str_detect(s, "%")
  s_clean <- str_replace_all(s, "%", "")
  s_clean <- str_replace_all(s_clean, ",", "")
  s_clean[s_clean %in% c("", "..", "NA", "NaN", "null", "NULL", "-")] <- NA_character_
  val <- suppressWarnings(as.numeric(s_clean))
  ifelse(!is.na(val) & has_pct, val / 100, val)
}

interp_vec <- function(x, yr) {
  non_na <- sum(!is.na(x))
  if (non_na >= 2) {
    as.numeric(zoo::na.approx(x, x = yr, na.rm = FALSE, rule = 2))
  } else if (non_na == 1) {
    rep(x[!is.na(x)][1], length(x))
  } else {
    rep(NA_real_, length(x))
  }
}

run_cips_manual <- function(df, var_name, lags = 1) {
  countries <- sort(unique(df$country))
  years <- sort(unique(df$year))
  N <- length(countries)
  T_len <- length(years)

  Y_mat <- sapply(countries, function(ct) {
    df$value[df$country == ct][match(years, df$year[df$country == ct])]
  })

  y_bar <- rowMeans(Y_mat, na.rm = TRUE)
  dy_mat <- apply(Y_mat, 2, function(col) c(NA, diff(col)))
  dy_bar <- c(NA, diff(y_bar))

  t_stats <- numeric(N)
  names(t_stats) <- countries

  for (j in seq_len(N)) {
    y_j <- Y_mat[, j]
    dy_j <- dy_mat[, j]

    lag_y <- c(NA, y_j[-T_len])
    lag_ybar <- c(NA, y_bar[-T_len])
    lag_dybar <- c(NA, dy_bar[-T_len])
    lag_dyj <- c(NA, dy_j[-T_len])

    data_cadf <- data.frame(
      dy = dy_j,
      lag_y = lag_y,
      lag_ybar = lag_ybar,
      dybar = dy_bar,
      lag_dybar = lag_dybar,
      lag_dyj = lag_dyj
    )

    if (lags >= 1) {
      for (l in seq_len(lags)) {
        data_cadf[[paste0("lag_dyj_", l)]] <- c(rep(NA, l), dy_j[seq_len(T_len - l)])
      }
    }

    fit_cadf <- lm(dy ~ ., data = data_cadf, na.action = na.omit)
    sm_fit <- summary(fit_cadf)$coefficients
    t_stats[j] <- if ("lag_y" %in% rownames(sm_fit)) sm_fit["lag_y", "t value"] else NA_real_
  }

  cips_stat <- mean(t_stats, na.rm = TRUE)
  kesimpulan <- ifelse(cips_stat < -2.23, "Stasioner (p < 0.05)", "Tidak Stasioner / Akar Unit")

  data.frame(
    Variabel = var_name,
    Statistik_CIPS = cips_stat,
    N_Negara = N,
    T_Tahun = T_len,
    Keterangan = kesimpulan
  )
}

pesaran_yamagata_test <- function(df, formula_obj) {
  countries <- unique(df$country)
  N <- length(countries)
  vars_all <- all.vars(formula_obj)
  y_name <- vars_all[1]
  x_names <- vars_all[-1]
  k <- length(x_names)

  fit_pool <- lm(formula_obj, data = df)
  beta_pool <- coef(fit_pool)[x_names]

  resid_pool <- residuals(fit_pool)
  n_tot <- length(resid_pool)
  sigma2_pool <- sum(resid_pool^2) / max(1, (n_tot - N - k))

  s_tilde_list <- numeric(N)
  names(s_tilde_list) <- countries
  valid_n <- 0L

  for (ct in countries) {
    sub_ct <- df[df$country == ct, , drop = FALSE]
    T_i <- nrow(sub_ct)
    if (T_i > (k + 2)) {
      X_mat <- as.matrix(sub_ct[, x_names, drop = FALSE])
      y_vec <- sub_ct[[y_name]]
      X_dm <- scale(X_mat, center = TRUE, scale = FALSE)
      y_dm <- y_vec - mean(y_vec, na.rm = TRUE)
      XtX <- crossprod(X_dm)
      XtX_inv <- try(solve(XtX), silent = TRUE)
      if (!inherits(XtX_inv, "try-error")) {
        beta_i <- as.numeric(XtX_inv %*% crossprod(X_dm, y_dm))
        diff_b <- beta_i - beta_pool
        s_tilde_list[ct] <- as.numeric(t(diff_b) %*% XtX %*% diff_b) / sigma2_pool
        valid_n <- valid_n + 1L
      }
    }
  }

  S_tilde <- sum(s_tilde_list, na.rm = TRUE)
  T_bar <- mean(sapply(countries, function(ct) sum(df$country == ct)))

  delta_tilde <- sqrt(valid_n) * ((S_tilde / valid_n) - k) / sqrt(2 * k)
  v_nk <- max(1e-6, (2 * k * (T_bar - k - 1)) / (T_bar + 1))
  delta_adj <- sqrt(valid_n) * ((S_tilde / valid_n) - k) / sqrt(v_nk)

  pval_delta <- 2 * (1 - pnorm(abs(delta_tilde)))
  pval_adj <- 2 * (1 - pnorm(abs(delta_adj)))

  data.frame(
    Statistik = c("Delta_tilde (Pesaran-Yamagata)", "Delta_tilde_adj"),
    Nilai = c(delta_tilde, delta_adj),
    P_Value = c(pval_delta, pval_adj),
    Keputusan = ifelse(
      c(pval_delta, pval_adj) < 0.05,
      "Tolak H0: Slope Heterogen antar-negara",
      "Gagal Tolak H0: Slope Homogen"
    )
  )
}

3. Pembacaan dan Pembersihan Data Excel

file_path <- "Data indonesia pacific sri 1.xlsx"
stopifnot(file.exists(file_path))

sheets_avail <- readxl::excel_sheets(file_path)
target_sheet <- if ("Data Model Manusia" %in% sheets_avail) {
  "Data Model Manusia"
} else {
  sheets_avail[1]
}

raw_df <- readxl::read_excel(file_path, sheet = target_sheet, col_names = FALSE)

year_row_idx <- which(apply(raw_df, 1, function(r) {
  nums <- suppressWarnings(as.numeric(as.character(r)))
  sum(!is.na(nums) & nums >= 1990 & nums <= 2030) >= 10
}))[1]
stopifnot(!is.na(year_row_idx))

years_vec <- suppressWarnings(as.numeric(as.character(unlist(raw_df[year_row_idx, ]))))
valid_year_cols <- which(!is.na(years_vec) & years_vec >= 1990 & years_vec <= 2030)
years_clean <- as.integer(years_vec[valid_year_cols])

data_rows <- raw_df[(year_row_idx + 1):nrow(raw_df), , drop = FALSE]

long_list <- list()
current_country <- NA_character_
idx_counter <- 1L

for (i in seq_len(nrow(data_rows))) {
  c_val <- str_trim(as.character(data_rows[[2]][i]))
  if (!is.na(c_val) && nzchar(c_val) && !c_val %in% c("NA", "NaN")) {
    current_country <- c_val
  }
  ind_val <- str_trim(as.character(data_rows[[3]][i]))
  if (is.na(current_country) || is.na(ind_val) || !nzchar(ind_val)) next

  vals_num <- parse_num(unlist(data_rows[i, valid_year_cols]))
  long_list[[idx_counter]] <- tibble(
    country = current_country,
    indicator = ind_val,
    year = years_clean,
    value = vals_num
  )
  idx_counter <- idx_counter + 1L
}

long_df <- bind_rows(long_list) %>%
  mutate(
    var_code = case_when(
      str_detect(str_to_lower(indicator), "education") ~ "edu_exp",
      str_detect(str_to_lower(indicator), "health") ~ "health_exp",
      str_detect(str_to_lower(indicator), "life expectancy") ~ "life_exp",
      str_detect(str_to_lower(indicator), "gdp per capita") ~ "gdp_pc",
      TRUE ~ make.names(indicator)
    )
  ) %>%
  group_by(country, year, var_code) %>%
  summarise(
    value = if (all(is.na(value))) NA_real_ else mean(value, na.rm = TRUE),
    .groups = "drop"
  )

panel_raw <- long_df %>%
  pivot_wider(names_from = var_code, values_from = value) %>%
  arrange(country, year)

for (col_nm in c("gdp_pc", "edu_exp", "health_exp", "life_exp")) {
  if (!col_nm %in% names(panel_raw)) {
    panel_raw[[col_nm]] <- NA_real_
  }
}

panel_bal <- panel_raw %>%
  filter(year >= 2001 & year <= 2023) %>%
  group_by(country) %>%
  arrange(year, .by_group = TRUE) %>%
  mutate(
    gdp_pc_i = interp_vec(gdp_pc, year),
    edu_exp_i = interp_vec(edu_exp, year),
    health_exp_i = interp_vec(health_exp, year),
    life_exp_i = interp_vec(life_exp, year)
  ) %>%
  ungroup() %>%
  mutate(
    ln_gdp = ifelse(!is.na(gdp_pc_i) & gdp_pc_i > 0, log(gdp_pc_i), NA_real_),
    edu = edu_exp_i,
    health = health_exp_i,
    life = life_exp_i
  ) %>%
  filter(!is.na(ln_gdp) & !is.na(edu) & !is.na(health) & !is.na(life))

common_years <- Reduce(intersect, split(panel_bal$year, panel_bal$country))
panel_bal <- panel_bal %>%
  filter(year %in% common_years) %>%
  arrange(country, year)

pdata <- pdata.frame(panel_bal, index = c("country", "year"))
form_panel <- ln_gdp ~ edu + health + life

4. Uji Cross-Sectional Independence (CD Test) dan Stasioneritas CIPS

Hipotesis nol (\(H_0\)) uji cross-sectional dependence adalah cross-sectional independence (tidak ada korelasi lintas-seksi antar-negara).

fe_init <- plm(form_panel, data = pdata, model = "within")
cd_pesaran <- pcdtest(fe_init, test = "cd")
cd_bp_lm <- pcdtest(fe_init, test = "lm")

cd_model_tbl <- data.frame(
  Uji = c("Pesaran CD Test (Residual FEM)", "Breusch-Pagan LM Test (Residual FEM)"),
  Statistik = c(as.numeric(cd_pesaran$statistic), as.numeric(cd_bp_lm$statistic)),
  P_Value = c(as.numeric(cd_pesaran$p.value), as.numeric(cd_bp_lm$p.value)),
  Status_Independensi = ifelse(
    c(as.numeric(cd_pesaran$p.value), as.numeric(cd_bp_lm$p.value)) >= 0.05,
    "Gagal Tolak H0: Cross-Sectional Independent",
    "Tolak H0: Ada Cross-Sectional Dependence"
  )
)

kable(cd_model_tbl, digits = 4, caption = "Uji Cross-Sectional Independence pada Residual Model Panel") %>%
  kable_styling(bootstrap_options = c("striped", "hover"), full_width = FALSE)
Uji Cross-Sectional Independence pada Residual Model Panel
Uji Statistik P_Value Status_Independensi
Pesaran CD Test (Residual FEM) 7.5845 0 Tolak H0: Ada Cross-Sectional Dependence
Breusch-Pagan LM Test (Residual FEM) 452.3273 0 Tolak H0: Ada Cross-Sectional Dependence
cd_vars <- lapply(c("ln_gdp", "edu", "health", "life"), function(v) {
  res <- pcdtest(pdata[[v]], test = "cd")
  pval <- as.numeric(res$p.value)
  data.frame(
    Variabel = v,
    Statistik_CD = as.numeric(res$statistic),
    P_Value = pval,
    Status_Independensi = ifelse(
      pval >= 0.05,
      "Cross-Sectional Independent",
      "Ada Cross-Sectional Dependence"
    )
  )
}) %>% bind_rows()

kable(cd_vars, digits = 4, caption = "Uji Pesaran CD per Variabel (pseries)") %>%
  kable_styling(bootstrap_options = c("striped", "hover"), full_width = FALSE)
Uji Pesaran CD per Variabel (pseries)
Variabel Statistik_CD P_Value Status_Independensi
ln_gdp 41.0789 0.0000 Ada Cross-Sectional Dependence
edu -0.4415 0.6588 Cross-Sectional Independent
health 6.6317 0.0000 Ada Cross-Sectional Dependence
life 37.9252 0.0000 Ada Cross-Sectional Dependence
cips_results <- lapply(c("ln_gdp", "edu", "health", "life"), function(v) {
  sub_df <- panel_bal %>% select(country, year, value = all_of(v))
  run_cips_manual(sub_df, v, lags = 1)
}) %>% bind_rows()

kable(cips_results, digits = 4, caption = "Uji Stasioneritas Generasi Kedua (Pesaran CIPS)") %>%
  kable_styling(bootstrap_options = c("striped", "hover"), full_width = FALSE)
Uji Stasioneritas Generasi Kedua (Pesaran CIPS)
Variabel Statistik_CIPS N_Negara T_Tahun Keterangan
ln_gdp -2.2655 15 23 Stasioner (p < 0.05)
edu -1.7494 15 23 Tidak Stasioner / Akar Unit
health -2.0238 15 23 Tidak Stasioner / Akar Unit
life -2.4367 15 23 Stasioner (p < 0.05)

5. Uji Heterogenitas Slope (Pesaran dan Yamagata)

het_tbl <- pesaran_yamagata_test(panel_bal, form_panel)
kable(het_tbl, digits = 4, caption = "Uji Heterogenitas Slope (Pesaran & Yamagata)") %>%
  kable_styling(bootstrap_options = c("striped", "hover"), full_width = FALSE)
Uji Heterogenitas Slope (Pesaran & Yamagata)
Statistik Nilai P_Value Keputusan
Delta_tilde (Pesaran-Yamagata) 0.7699 0.4414 Gagal Tolak H0: Slope Homogen
Delta_tilde_adj 0.8653 0.3869 Gagal Tolak H0: Slope Homogen

6. Estimasi & Pemilihan Model Panel Statis (CEM, FEM, REM)

cem_mod <- plm(form_panel, data = pdata, model = "pooling")
fem_mod <- plm(form_panel, data = pdata, model = "within", effect = "individual")
rem_mod <- plm(form_panel, data = pdata, model = "random", effect = "individual")

chow_test <- pFtest(fem_mod, cem_mod)
hausman_test <- phtest(fem_mod, rem_mod)
bplm_test <- plmtest(cem_mod, type = "bp")

cat("--- Ringkasan CEM ---\n")
## --- Ringkasan CEM ---
print(summary(cem_mod))
## Pooling Model
## 
## Call:
## plm(formula = form_panel, data = pdata, model = "pooling")
## 
## Balanced Panel: n = 15, T = 23, N = 345
## 
## Residuals:
##    Min. 1st Qu.  Median 3rd Qu.    Max. 
##  -2.541  -0.329   0.100   0.277   1.738 
## 
## Coefficients:
##               Estimate Std. Error  t-value  Pr(>|t|)    
## (Intercept) -7.1809952  0.3867272 -18.5686 < 2.2e-16 ***
## edu         -0.0077740  0.0191739  -0.4054    0.6854    
## health      -0.0841943  0.0181851  -4.6299  5.21e-06 ***
## life         0.2212783  0.0056449  39.1994 < 2.2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Total Sum of Squares:    757.13
## Residual Sum of Squares: 130.31
## R-Squared:      0.8279
## Adj. R-Squared: 0.82638
## F-statistic: 546.788 on 3 and 341 DF, p-value: < 2.22e-16
cat("\n--- Ringkasan FEM ---\n")
## 
## --- Ringkasan FEM ---
print(summary(fem_mod))
## Oneway (individual) effect Within Model
## 
## Call:
## plm(formula = form_panel, data = pdata, effect = "individual", 
##     model = "within")
## 
## Balanced Panel: n = 15, T = 23, N = 345
## 
## Residuals:
##    Min. 1st Qu.  Median 3rd Qu.    Max. 
## -1.1482 -0.1249  0.0106  0.1446  1.5054 
## 
## Coefficients:
##           Estimate  Std. Error t-value  Pr(>|t|)    
## edu    -0.05349987  0.01838044 -2.9107  0.003854 ** 
## health  0.00083196  0.01864089  0.0446  0.964429    
## life    0.21734584  0.00846563 25.6739 < 2.2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Total Sum of Squares:    101.57
## Residual Sum of Squares: 30.303
## R-Squared:      0.70167
## Adj. R-Squared: 0.68616
## F-statistic: 256.365 on 3 and 327 DF, p-value: < 2.22e-16
cat("\n--- Ringkasan REM ---\n")
## 
## --- Ringkasan REM ---
print(summary(rem_mod))
## Oneway (individual) effect Random Effect Model 
##    (Swamy-Arora's transformation)
## 
## Call:
## plm(formula = form_panel, data = pdata, effect = "individual", 
##     model = "random")
## 
## Balanced Panel: n = 15, T = 23, N = 345
## 
## Effects:
##                   var std.dev share
## idiosyncratic 0.09267 0.30442 0.198
## individual    0.37580 0.61303 0.802
## theta: 0.897
## 
## Residuals:
##    Min. 1st Qu.  Median 3rd Qu.    Max. 
## -1.2836 -0.1302  0.0239  0.1515  1.4878 
## 
## Coefficients:
##               Estimate Std. Error  z-value  Pr(>|z|)    
## (Intercept) -7.0821024  0.5972727 -11.8574 < 2.2e-16 ***
## edu         -0.0528495  0.0179961  -2.9367  0.003317 ** 
## health      -0.0027042  0.0182471  -0.1482  0.882185    
## life         0.2172349  0.0080726  26.9102 < 2.2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Total Sum of Squares:    108.53
## Residual Sum of Squares: 31.459
## R-Squared:      0.71012
## Adj. R-Squared: 0.70757
## Chisq: 835.366 on 3 DF, p-value: < 2.22e-16
sel_tbl <- data.frame(
  Uji = c("Uji Chow (CEM vs FEM)", "Uji Hausman (REM vs FEM)", "Uji Breusch-Pagan LM (CEM vs REM)"),
  Statistik = c(
    as.numeric(chow_test$statistic),
    as.numeric(hausman_test$statistic),
    as.numeric(bplm_test$statistic)
  ),
  P_Value = c(
    as.numeric(chow_test$p.value),
    as.numeric(hausman_test$p.value),
    as.numeric(bplm_test$p.value)
  ),
  Rekomendasi = c(
    ifelse(as.numeric(chow_test$p.value) < 0.05, "Pilih FEM", "Pilih CEM"),
    ifelse(as.numeric(hausman_test$p.value) < 0.05, "Pilih FEM", "Pilih REM"),
    ifelse(as.numeric(bplm_test$p.value) < 0.05, "Pilih REM", "Pilih CEM")
  )
)

kable(sel_tbl, digits = 4, caption = "Ringkasan Uji Pemilihan Model Panel Statis") %>%
  kable_styling(bootstrap_options = c("striped", "hover"), full_width = FALSE)
Ringkasan Uji Pemilihan Model Panel Statis
Uji Statistik P_Value Rekomendasi
Uji Chow (CEM vs FEM) 77.0817 0.0000 Pilih FEM
Uji Hausman (REM vs FEM) 1.2605 0.7385 Pilih REM
Uji Breusch-Pagan LM (CEM vs REM) 2051.5213 0.0000 Pilih REM

7. Uji Asumsi Diagnostik & Driscoll-Kraay Robust Standard Errors

best_model <- if (as.numeric(chow_test$p.value) < 0.05) {
  if (as.numeric(hausman_test$p.value) < 0.05) fem_mod else rem_mod
} else {
  if (as.numeric(bplm_test$p.value) < 0.05) rem_mod else cem_mod
}

best_name <- if (identical(best_model, fem_mod)) {
  "Fixed Effect Model (FEM)"
} else if (identical(best_model, rem_mod)) {
  "Random Effect Model (REM)"
} else {
  "Common Effect Model (CEM)"
}

cat("Model panel statis terpilih otomatis:", best_name, "\n\n")
## Model panel statis terpilih otomatis: Random Effect Model (REM)
# 1. Multikolinearitas (VIF)
ols_aux <- lm(form_panel, data = panel_bal)
cat("--- Multikolinearitas (VIF) ---\n")
## --- Multikolinearitas (VIF) ---
print(car::vif(ols_aux))
##      edu   health     life 
## 1.057802 1.211220 1.149950
# 2. Heteroskedastisitas (Breusch-Pagan)
cat("\n--- Heteroskedastisitas (Breusch-Pagan) ---\n")
## 
## --- Heteroskedastisitas (Breusch-Pagan) ---
print(lmtest::bptest(ols_aux))
## 
##  studentized Breusch-Pagan test
## 
## data:  ols_aux
## BP = 20.432, df = 3, p-value = 0.0001381
# 3. Autokorelasi Serial Panel (Breusch-Godfrey & Durbin-Watson)
cat("\n--- Autokorelasi Serial Panel ---\n")
## 
## --- Autokorelasi Serial Panel ---
print(plm::pbgtest(best_model))
## 
##  Breusch-Godfrey/Wooldridge test for serial correlation in panel models
## 
## data:  form_panel
## chisq = 197.98, df = 23, p-value < 2.2e-16
## alternative hypothesis: serial correlation in idiosyncratic errors
print(plm::pdwtest(best_model))
## 
##  Durbin-Watson test for serial correlation in panel models
## 
## data:  form_panel
## DW = 0.56493, p-value < 2.2e-16
## alternative hypothesis: serial correlation in idiosyncratic errors
# 4. Driscoll-Kraay Robust Standard Errors
cat("\n--- Estimasi Robust (Driscoll-Kraay SE) ---\n")
## 
## --- Estimasi Robust (Driscoll-Kraay SE) ---
print(lmtest::coeftest(best_model, vcov. = function(x) plm::vcovSCC(x, type = "HC1", cluster = "group")))
## 
## t test of coefficients:
## 
##               Estimate Std. Error  t value Pr(>|t|)    
## (Intercept) -7.0821024  0.5468268 -12.9513  < 2e-16 ***
## edu         -0.0528495  0.0313890  -1.6837  0.09316 .  
## health      -0.0027042  0.0334646  -0.0808  0.93564    
## life         0.2172349  0.0067554  32.1574  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1