# \donttest{
# Assuming existence of rkkw, llkkw, grkkw, hskkw functions for kkw
# Generate sample data
set.seed(123)
true_par_kkw <- c(alpha = 2, beta = 3, delta = 1.5, lambda = 0.5)
if (exists("rkkw")) {
sample_data_kkw <- rkkw(100, alpha = true_par_kkw[1], beta = true_par_kkw[2],
delta = true_par_kkw[3], lambda = true_par_kkw[4])
} else {
sample_data_kkw <- rgkw(100, alpha = true_par_kkw[1], beta = true_par_kkw[2],
gamma = 1, delta = true_par_kkw[3], lambda = true_par_kkw[4])
}
# --- Find MLE estimates ---
start_par_kkw <- c(1.5, 2.5, 1.0, 0.6)
mle_result_kkw <- stats::optim(par = start_par_kkw,
fn = llkkw,
gr = if (exists("grkkw")) grkkw else NULL,
method = "BFGS",
hessian = TRUE,
data = sample_data_kkw)
# --- Compare analytical Hessian to numerical Hessian ---
if (mle_result_kkw$convergence == 0 &&
requireNamespace("numDeriv", quietly = TRUE) &&
exists("hskkw")) {
mle_par_kkw <- mle_result_kkw$par
cat("\nComparing Hessians for kkw at MLE estimates:\n")
# Numerical Hessian of llkkw
num_hess_kkw <- numDeriv::hessian(func = llkkw, x = mle_par_kkw, data = sample_data_kkw)
# Analytical Hessian from hskkw
ana_hess_kkw <- hskkw(par = mle_par_kkw, data = sample_data_kkw)
cat("Numerical Hessian (kkw):\n")
print(round(num_hess_kkw, 4))
cat("Analytical Hessian (kkw):\n")
print(round(ana_hess_kkw, 4))
# Check differences
cat("Max absolute difference between kkw Hessians:\n")
print(max(abs(num_hess_kkw - ana_hess_kkw)))
# Optional: Use analytical Hessian for Standard Errors
# tryCatch({
# cov_matrix_kkw <- solve(ana_hess_kkw)
# std_errors_kkw <- sqrt(diag(cov_matrix_kkw))
# cat("Std. Errors from Analytical kkw Hessian:\n")
# print(std_errors_kkw)
# }, error = function(e) {
# warning("Could not invert analytical kkw Hessian: ", e$message)
# })
} else {
cat("\nSkipping kkw Hessian comparison.\n")
cat("Requires convergence, 'numDeriv' package, and function 'hskkw'.\n")
}
# }
Run the code above in your browser using DataLab