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
print(colSums(is.na(reliability_vars)))

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

print(nrow(reliability_data))

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

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

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

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

# Descriptive statistics
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)
)

print(summary_table)

# Save results
write.csv(summary_table, "reliability_summary_ehi.csv", row.names = FALSE)

# Create HTML output using sink()
sink("temp_output.txt")
print(alpha_result)
print(split_half)
print(alpha_dropped$alpha.drop)
print(round(cor_matrix, 5))
print(desc_stats)
print(summary_table)
sink()

# Read the captured output
captured_output <- readLines("temp_output.txt")
file.remove("temp_output.txt")

html_output <- sprintf(
  "<html><head><title>EHI Reliability Analysis</title></head><body>
  <h1>EHI Reliability Analysis</h1>
  <pre>%s</pre>
  </body></html>",
  paste(captured_output, collapse = "\n")
)

writeLines(html_output, "EHI reliability.html")