options(scipen = 999)
setwd("C:/Users/irina/Documents/DND/EOHI/eohi1")

# Load required libraries
library(corrplot)
library(Hmisc)
library(psych)

# Load the data
exp1_data <- read.csv("exp1.csv")

# Define the two sets of variables
set1_vars <- c("NPast_mean_total", "NFut_mean_total", "DGEN_past_mean", "DGEN_fut_mean")
set2_vars <- c("AOT_total", "CRT_correct", "CRT_int")

# Create subset with only the variables of interest
correlation_data <- exp1_data[, c(set1_vars, set2_vars)]

# Calculate correlation matrices (both Pearson and Spearman)
cor_matrix_pearson <- cor(correlation_data, method = "pearson")
cor_matrix_spearman <- cor(correlation_data, method = "spearman")

# Use Spearman as primary method
cor_matrix <- cor_matrix_spearman

# Print correlation matrices with 5 decimal places
print(round(cor_matrix_spearman, 5))

# Separate correlations between the two sets (Spearman)
set1_set2_cor <- cor_matrix_spearman[set1_vars, set2_vars]
print(round(set1_set2_cor, 5))

# Calculate correlations within each set (Spearman)
set1_within_cor <- cor_matrix_spearman[set1_vars, set1_vars]
set2_within_cor <- cor_matrix_spearman[set2_vars, set2_vars]

# Statistical significance tests (Spearman)
cor_test_results_spearman <- rcorr(as.matrix(correlation_data), type = "spearman")

for(i in 1:length(set1_vars)) {
  for(j in 1:length(set2_vars)) {
    var1 <- set1_vars[i]
    var2 <- set2_vars[j]
    p_val <- cor_test_results_spearman$P[var1, var2]
    cat(sprintf("%s vs %s: p = %.5f\n", var1, var2, p_val))
  }
}

# Create correlation plots for both methods
pdf("correlation_plot_scales_spearman.pdf", width = 10, height = 8)
corrplot(cor_matrix_spearman, method = "color", type = "upper", 
         order = "hclust", tl.cex = 0.8, tl.col = "black",
         addCoef.col = "black", number.cex = 0.7,
         title = "Spearman Correlation Matrix: EOHI/DGEN vs Cognitive Measures")
dev.off()

pdf("correlation_plot_scales_pearson.pdf", width = 10, height = 8)
corrplot(cor_matrix_pearson, method = "color", type = "upper", 
         order = "hclust", tl.cex = 0.8, tl.col = "black",
         addCoef.col = "black", number.cex = 0.7,
         title = "Pearson Correlation Matrix: EOHI/DGEN vs Cognitive Measures")
dev.off()

# Summary statistics
cat("\nDescriptive Statistics:\n")
desc_stats <- describe(correlation_data)
print(round(desc_stats, 5))

cat("\n=== ANALYSIS COMPLETED ===\n")
cat("Spearman correlations are recommended for this analysis due to:\n")
cat("- Non-parametric nature (no distribution assumptions)\n")
cat("- Robustness to outliers and non-linear relationships\n")
cat("- Better suitability for cognitive measures\n\n")
cat("Output files created:\n")
cat("- correlation_plot_scales_spearman.pdf (primary analysis)\n")
cat("- correlation_plot_scales_pearson.pdf (comparison)\n")
cat("\nSpearman correlations are reported as the primary analysis.\n")