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

options(scipen = 999)

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

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

# Cronbach's Alpha
alpha_result <- alpha(reliability_data)

# Split-half reliability
split_half <- splitHalf(reliability_data)

# Alpha if item dropped
alpha_dropped <- alpha(reliability_data, check.keys = TRUE)

# Inter-item correlations
cor_matrix <- cor(reliability_data, use = "complete.obs")

# Create a summary table
summary_table <- data.frame(
  Variable = names(reliability_data),
  n = nrow(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),
  Median = round(apply(reliability_data, 2, median, na.rm = TRUE), 5)
)

html_output <- paste0(
  "<html><head><title>EHI Reliability Analysis</title></head><body>",
  "<h1>EHI Reliability Analysis</h1>",
  
  "<h2>Cronbach's Alpha</h2>",
  kable(alpha_result$total, format = "html"),
  
  "<h2>Split-Half Reliability</h2>",
  "<p>Maximum split half reliability: ", round(split_half$maxrb, 5), "</p>",
  
  "<h2>Item-Level Statistics</h2>",
  kable(alpha_dropped$alpha.drop, format = "html"),
  
  "<h3>Corrected Item-Total Correlations</h3>",
  kable(alpha_result$item.stats, format = "html"),
  
  "<h2>Inter-Item Correlations</h2>",
  kable(round(cor_matrix, 5), format = "html"),
  
  "<h2>Summary Table</h2>",
  kable(summary_table, format = "html"),
  
  "</body></html>"
)

writeLines(html_output, "EHI reliability.html")