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)]

cat("Sample size for correlations:", nrow(correlation_data), "\n\n")

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

# Print correlation matrix with 5 decimal places
cat("Correlation Matrix:\n")
print(round(cor_matrix, 5))

# Separate correlations between the two sets
set1_set2_cor <- cor_matrix[set1_vars, set2_vars]

cat("\nCorrelations between Set 1 (EOHI/DGEN) and Set 2 (Cognitive):\n")
print(round(set1_set2_cor, 5))

# Calculate correlations within each set
set1_within_cor <- cor_matrix[set1_vars, set1_vars]
set2_within_cor <- cor_matrix[set2_vars, set2_vars]

cat("\nWithin Set 1 correlations (EOHI/DGEN):\n")
print(round(set1_within_cor, 5))

cat("\nWithin Set 2 correlations (Cognitive):\n")
print(round(set2_within_cor, 5))

# Statistical significance tests
cat("\nStatistical significance tests (p-values):\n")
cor_test_results <- rcorr(as.matrix(correlation_data))

cat("\nP-values for Set 1 vs Set 2 correlations:\n")
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$P[var1, var2]
    cat(sprintf("%s vs %s: p = %.5f\n", var1, var2, p_val))
  }
}

# Create correlation plot
pdf("correlation_plot_scales.pdf", width = 10, height = 8)
corrplot(cor_matrix, method = "color", type = "upper", 
         order = "hclust", tl.cex = 0.8, tl.col = "black",
         addCoef.col = "black", number.cex = 0.7,
         title = "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("\nAnalysis completed. Correlation plot saved as 'correlation_plot_scales.pdf'\n")