# Mixed ANOVA Analysis for Domain Means - EOHI2
# EOHI Experiment Data Analysis - Domain Level Analysis with INTERVAL factor
# Variables: NPast_5_pref_MEAN, NPast_5_pers_MEAN, NPast_5_val_MEAN, etc.
#           NFut_5_pref_MEAN, NFut_5_pers_MEAN, NFut_5_val_MEAN, etc.
#           NPast_10_pref_MEAN, NPast_10_pers_MEAN, NPast_10_val_MEAN, etc.
#           NFut_10_pref_MEAN, NFut_10_pers_MEAN, NFut_10_val_MEAN, etc.
#           5.10past_pref_MEAN, 5.10past_pers_MEAN, 5.10past_val_MEAN
#           5.10fut_pref_MEAN, 5.10fut_pers_MEAN, 5.10fut_val_MEAN

# Load required libraries
library(tidyverse)
library(ez)
library(car)
library(afex)         # For aov_ez (cleaner ANOVA output)
library(nortest)      # For normality tests
library(emmeans)      # For post-hoc comparisons
library(purrr)        # For map functions
library(effsize)      # For Cohen's d calculations
library(effectsize)   # For effect size calculations

# Global options to remove scientific notation
options(scipen = 999)

# Set contrasts to sum for mixed ANOVA (necessary for proper interpretation)
options(contrasts = c("contr.sum", "contr.poly"))

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

# Read the data
data <- read.csv("eohi2.csv")

# Display basic information about the dataset
print(paste("Dataset dimensions:", paste(dim(data), collapse = " x")))
print(paste("Number of participants:", length(unique(data$ResponseId))))

# Verify the specific variables we need
required_vars <- c("NPast_5_pref_MEAN", "NPast_5_pers_MEAN", "NPast_5_val_MEAN",
                   "NPast_10_pref_MEAN", "NPast_10_pers_MEAN", "NPast_10_val_MEAN",
                   "NFut_5_pref_MEAN", "NFut_5_pers_MEAN", "NFut_5_val_MEAN",
                   "NFut_10_pref_MEAN", "NFut_10_pers_MEAN", "NFut_10_val_MEAN",
                   "5.10past_pref_MEAN", "5.10past_pers_MEAN", "5.10past_val_MEAN",
                   "5.10fut_pref_MEAN", "5.10fut_pers_MEAN", "5.10fut_val_MEAN")

missing_vars <- required_vars[!required_vars %in% colnames(data)]
if (length(missing_vars) > 0) {
  print(paste("Warning: Missing variables:", paste(missing_vars, collapse = ", ")))
} else {
  print("All required domain mean variables found!")
}

# Define domain mapping with TIME, DOMAIN, and INTERVAL factors
domain_mapping <- data.frame(
  variable = required_vars,
  time = c(rep("Past", 3), rep("Past", 3), rep("Future", 3), rep("Future", 3), 
           rep("Past", 3), rep("Future", 3)),
  domain = rep(c("Preferences", "Personality", "Values"), 6),
  interval = c(rep("5", 3), rep("10", 3), rep("5", 3), rep("10", 3), 
               rep("5_10", 3), rep("5_10", 3)),
  stringsAsFactors = FALSE
)

print("Domain mapping created:")
print(domain_mapping)

# Efficient data pivoting using pivot_longer
long_data <- data %>%
  select(ResponseId, TEMPORAL_DO, INTERVAL_DO, all_of(required_vars)) %>%
  pivot_longer(
    cols = all_of(required_vars),
    names_to = "variable",
    values_to = "MEAN_DIFFERENCE"
  ) %>%
  left_join(domain_mapping, by = "variable") %>%
  # Convert to factors with proper levels
  mutate(
    TIME = factor(time, levels = c("Past", "Future")),
    DOMAIN = factor(domain, levels = c("Preferences", "Personality", "Values")),
    INTERVAL = factor(interval, levels = c("5", "10", "5_10")),
    ResponseId = as.factor(ResponseId),
    TEMPORAL_DO = as.factor(TEMPORAL_DO),
    INTERVAL_DO = as.factor(INTERVAL_DO)
  ) %>%
  # Select final columns and remove any rows with missing values
  select(ResponseId, TEMPORAL_DO, INTERVAL_DO, TIME, DOMAIN, INTERVAL, MEAN_DIFFERENCE) %>%
  filter(!is.na(MEAN_DIFFERENCE))

print(paste("Long data dimensions:", paste(dim(long_data), collapse = " x")))
print(paste("Number of participants:", length(unique(long_data$ResponseId))))

# =============================================================================
# DESCRIPTIVE STATISTICS
# =============================================================================

# Overall descriptive statistics by TIME, DOMAIN, and INTERVAL
desc_stats <- long_data %>%
  group_by(TIME, DOMAIN, INTERVAL) %>%
  summarise(
    n = n(),
    mean = round(mean(MEAN_DIFFERENCE, na.rm = TRUE), 5),
    variance = round(var(MEAN_DIFFERENCE, na.rm = TRUE), 5),
    sd = round(sd(MEAN_DIFFERENCE, na.rm = TRUE), 5),
    median = round(median(MEAN_DIFFERENCE, na.rm = TRUE), 5),
    q1 = round(quantile(MEAN_DIFFERENCE, 0.25, na.rm = TRUE), 5),
    q3 = round(quantile(MEAN_DIFFERENCE, 0.75, na.rm = TRUE), 5),
    min = round(min(MEAN_DIFFERENCE, na.rm = TRUE), 5),
    max = round(max(MEAN_DIFFERENCE, na.rm = TRUE), 5),
    .groups = 'drop'
  )

print("Descriptive statistics by TIME, DOMAIN, and INTERVAL:")
print(desc_stats)

# Descriptive statistics by between-subjects factors
desc_stats_by_between <- long_data %>%
  group_by(TEMPORAL_DO, INTERVAL_DO, TIME, DOMAIN, INTERVAL) %>%
  summarise(
    n = n(),
    mean = round(mean(MEAN_DIFFERENCE, na.rm = TRUE), 5),
    variance = round(var(MEAN_DIFFERENCE, na.rm = TRUE), 5),
    sd = round(sd(MEAN_DIFFERENCE, na.rm = TRUE), 5),
    .groups = 'drop'
  )

print("Descriptive statistics by between-subjects factors:")
print(desc_stats_by_between)

# Summary by between-subjects factors only
desc_stats_between_only <- long_data %>%
  group_by(TEMPORAL_DO, INTERVAL_DO) %>%
  summarise(
    n = n(),
    mean = round(mean(MEAN_DIFFERENCE, na.rm = TRUE), 5),
    variance = round(var(MEAN_DIFFERENCE, na.rm = TRUE), 5),
    sd = round(sd(MEAN_DIFFERENCE, na.rm = TRUE), 5),
    .groups = 'drop'
  )

print("Descriptive statistics by between-subjects factors only:")
print(desc_stats_between_only)