setwd("C:/Users/irina/Documents/DND/EOHI/eohi2")

options(scipen = 999)

df <- read.csv("eohi2.csv")
library(psych)
library(dplyr)
library(knitr)
library(irr)

# Select the 4 variables for reliability analysis
reliability_vars <- df[, c("ehiDGEN_5_mean", "ehiDGEN_10_mean", "ehi5_global_mean", "ehi10_global_mean")]

# Check for missing values
cat("Missing values per variable:\n")
print(colSums(is.na(reliability_vars)))

# Remove rows with any missing values for reliability analysis
reliability_data <- reliability_vars[complete.cases(reliability_vars), ]

cat("\nSample size for reliability analysis:", nrow(reliability_data), "\n")

# Cronbach's Alpha
cat("\n=== CRONBACH'S ALPHA ===\n")
alpha_result <- alpha(reliability_data)
print(alpha_result)

# Alternative reliability measures
cat("\n=== ADDITIONAL RELIABILITY MEASURES ===\n")

# Split-half reliability
split_half <- splitHalf(reliability_data)
cat("Split-half reliability:\n")
print(split_half)

# Alpha if item dropped
cat("\nAlpha if item dropped:\n")
alpha_dropped <- alpha(reliability_data, check.keys = TRUE)
print(alpha_dropped$alpha.drop)

# Inter-item correlations
cat("\n=== INTER-ITEM CORRELATIONS ===\n")
cor_matrix <- cor(reliability_data, use = "complete.obs")
print(round(cor_matrix, 5))

# Descriptive statistics
cat("\n=== DESCRIPTIVE STATISTICS ===\n")
desc_stats <- describe(reliability_data)
print(desc_stats)

# Create a summary table
summary_table <- data.frame(
  Variable = names(reliability_data),
  Mean = round(colMeans(reliability_data, na.rm = TRUE), 5),
  SD = round(apply(reliability_data, 2, sd, na.rm = TRUE), 5),
  Min = round(apply(reliability_data, 2, min, na.rm = TRUE), 5),
  Max = round(apply(reliability_data, 2, max, na.rm = TRUE), 5),
  Skewness = round(apply(reliability_data, 2, skew, na.rm = TRUE), 5),
  Kurtosis = round(apply(reliability_data, 2, kurtosi, na.rm = TRUE), 5)
)

cat("\n=== SUMMARY TABLE ===\n")
print(summary_table)

# Save results
write.csv(summary_table, "reliability_summary_ehi.csv", row.names = FALSE)
cat("\nResults saved to 'reliability_summary_ehi.csv'\n")