# Load necessary libraries
library(readr)
library(tidyverse, quietly = TRUE)
library(readxl)
library(stringr)
library(mice)
library(lme4)
library(lmerTest)
library(performance)


#Function to remove outliers based on IQR
remove_outliers <- function(df, column) {
  Q1 <- quantile(df[[column]], 0.25, na.rm = TRUE)
  Q3 <- quantile(df[[column]], 0.75, na.rm = TRUE)
  IQR <- Q3 - Q1
  lower_bound <- Q1 - 1.5 * IQR
  upper_bound <- Q3 + 1.5 * IQR
  df <- dplyr::filter(df, df[[column]] >= lower_bound & df[[column]] <= upper_bound)
  return(df)
}

# Load data
MergeFlankerDec8 <- read_excel("C:/Users/John Majoubi/Downloads/MergeFlankerDec8.xlsx")
MergeSimonDec8th <- read_excel("C:/Users/John Majoubi/Downloads/MergeSimonDec8th.xlsx")       
MergeStroopDec8Full <- read_excel("C:/Users/John Majoubi/Downloads/MergeStroopDec8Full.xlsx") 

# Select relevant columns
MergeFlankerDec8_c <- MergeFlankerDec8 %>% 
  select(Subject, Task.RT, FinalScore, TrialType) %>% 
  mutate(Task.RT  = as.numeric(Task.RT))

MergeFlankerDec8_c <- remove_outliers(df = MergeFlankerDec8_c, column = "Task.RT")

MergeSimonDec8th_c <- MergeSimonDec8th %>% 
  select(Subject, Task.RT, FinalScore, TrialType) %>% 
  mutate(Task.RT  = as.numeric(Task.RT))

MergeSimonDec8th_c <- remove_outliers(MergeSimonDec8th_c, "Task.RT")

MergeStroopDec8Full_c <- MergeStroopDec8Full %>% 
  select(Subject, Task.RT, FinalScore, TrialType) %>% 
  mutate(Task.RT  = as.numeric(Task.RT))

MergeStroopDec8Full_c <- remove_outliers(MergeStroopDec8Full_c, "Task.RT")

# Impute missing values
impute_missing_values <- function(df) {
  numeric_cols <- sapply(df, is.numeric)
  na_columns <- colnames(df)[numeric_cols & colSums(is.na(df)) > 0]
  df[na_columns] <- lapply(df[na_columns], function(x) replace(x, is.na(x), mean(x, na.rm = TRUE)))
  return(df)
}

MergeFlankerDec8_c <- impute_missing_values(MergeFlankerDec8_c)
MergeSimonDec8th_c <- impute_missing_values(MergeSimonDec8th_c)
MergeStroopDec8Full_c <- impute_missing_values(MergeStroopDec8Full_c)

# Convert Task.RT columns to numeric, handling "NULL" strings
convert_to_numeric <- function(df) {
  df <- df %>%
    mutate(across(starts_with("Task.RT"), ~as.numeric(str_replace(., "NULL", NA_character_))))
  return(df)
}

MergeFlankerDec8_c <- convert_to_numeric(MergeFlankerDec8_c)
MergeSimonDec8th_c <- convert_to_numeric(MergeSimonDec8th_c)
MergeStroopDec8Full_c <- convert_to_numeric(MergeStroopDec8Full_c)

# Aggregate datasets by Subject
agg_Flanker <- MergeFlankerDec8_c %>%
  group_by(Subject) %>%
  summarise(Task.RT_Flanker = mean(Task.RT, na.rm = TRUE),
            FinalScore_Flanker = mean(FinalScore, na.rm = TRUE))

agg_Simon <- MergeSimonDec8th_c %>%
  group_by(Subject) %>%
  summarise(Task.RT_Simon = mean(Task.RT, na.rm = TRUE),
            FinalScore_Simon = mean(FinalScore, na.rm = TRUE))

agg_Stroop <- MergeStroopDec8Full_c %>%
  group_by(Subject) %>%
  summarise(Task.RT_Stroop = mean(Task.RT, na.rm = TRUE),
            FinalScore_Stroop = mean(FinalScore, na.rm = TRUE))

# Merge aggregated datasets on 'Subject'
merged_data <- agg_Flanker %>%
  full_join(agg_Simon, by = "Subject") %>%
  full_join(agg_Stroop, by = "Subject")

# Check the structure of the merged data
str(merged_data)
## tibble [301 × 7] (S3: tbl_df/tbl/data.frame)
##  $ Subject           : num [1:301] 333 492 4037 5088 6772 ...
##  $ Task.RT_Flanker   : num [1:301] 1077 2223 1707 1991 2673 ...
##  $ FinalScore_Flanker: num [1:301] 1 6 44 36 23 44 38 41 56 13 ...
##  $ Task.RT_Simon     : num [1:301] 1178 1161 1134 889 1162 ...
##  $ FinalScore_Simon  : num [1:301] 59 53 60 74 59 66 60 70 67 56 ...
##  $ Task.RT_Stroop    : num [1:301] NA 1822 1563 1306 2235 ...
##  $ FinalScore_Stroop : num [1:301] NA 15 46 55 11 42 40 50 41 NA ...
# Remove rows with FinalScore below 0
MergeFlankerDec8_c <- MergeFlankerDec8_c %>% dplyr::filter(FinalScore >= 0)
MergeSimonDec8th_c <- MergeSimonDec8th_c %>% dplyr::filter(FinalScore >= 0)
MergeStroopDec8Full_c <- MergeStroopDec8Full_c %>% dplyr::filter(FinalScore >= 0)
MergeFlankerDec8_c %>% count(Subject)
## # A tibble: 262 × 2
##    Subject     n
##      <dbl> <int>
##  1     333    66
##  2     492    35
##  3    4037    45
##  4    5088    39
##  5    6772    30
##  6   14740    47
##  7   23295    41
##  8   42195    42
##  9   43158    57
## 10   56964    25
## # ℹ 252 more rows
# remove_outliers <- function(df, column) {
#   Q1 <- quantile(df[[column]], 0.25, na.rm = TRUE)
#   Q3 <- quantile(df[[column]], 0.75, na.rm = TRUE)
#   IQR <- Q3 - Q1
#   lower_bound <- Q1 - 1.5 * IQR
#   upper_bound <- Q3 + 1.5 * IQR
#   df %>% filter(df[[column]] >= lower_bound & df[[column]] <= upper_bound)
# }
# MergeFlankerDec8_c %>% count(Subject)
# Model fitting and diagnostics

# Ensure Task.RT is numeric and TrialType is a factor in the original dataset
MergeFlankerDec8_c <- MergeFlankerDec8_c %>%
  mutate(Task.RT = as.numeric(Task.RT),
         TrialType = as.factor(TrialType))
# Fit the linear mixed-effects model
Flankermodel <- lme4::lmer(Task.RT ~ TrialType + (1 | Subject), data = MergeFlankerDec8_c)
summary(Flankermodel)
## Linear mixed model fit by REML ['lmerMod']
## Formula: Task.RT ~ TrialType + (1 | Subject)
##    Data: MergeFlankerDec8_c
## 
## REML criterion at convergence: 133635.6
## 
## Scaled residuals: 
##     Min      1Q  Median      3Q     Max 
## -4.5477 -0.5027 -0.0986  0.4445  4.6564 
## 
## Random effects:
##  Groups   Name        Variance Std.Dev.
##  Subject  (Intercept) 307269   554.3   
##  Residual             670283   818.7   
## Number of obs: 8182, groups:  Subject, 262
## 
## Fixed effects:
##                                       Estimate Std. Error t value
## (Intercept)                            2046.32      38.94   52.55
## TrialTypeFullyIncongruent               483.78      25.76   18.78
## TrialTypeStimCongruentRespIncongruent   350.74      25.60   13.70
## TrialTypeStimIncongruentRespCongruent   312.06      25.33   12.32
## 
## Correlation of Fixed Effects:
##             (Intr) TrlTFI TTSCRI
## TrlTypFllyI -0.315              
## TrlTypStCRI -0.320  0.489       
## TrlTypStIRC -0.325  0.493  0.496
# Count the number of subjects
MergeFlankerDec8_c %>% count(Subject)
## # A tibble: 262 × 2
##    Subject     n
##      <dbl> <int>
##  1     333    66
##  2     492    35
##  3    4037    45
##  4    5088    39
##  5    6772    30
##  6   14740    47
##  7   23295    41
##  8   42195    42
##  9   43158    57
## 10   56964    25
## # ℹ 252 more rows
# Calculate ICC (Intraclass Correlation Coefficient)
icc(Flankermodel)
## # Intraclass Correlation Coefficient
## 
##     Adjusted ICC: 0.314
##   Unadjusted ICC: 0.304
# Load necessary libraries
library(dplyr)
library(ggplot2)
library(patchwork)
## Warning: package 'patchwork' was built under R version 4.4.1
# Assuming merged_data is already loaded and cleaned

# Compute correlations
correlation_Flanker_Simon <- cor(merged_data$Task.RT_Flanker, merged_data$Task.RT_Simon, use = "complete.obs")
correlation_Flanker_Stroop <- cor(merged_data$Task.RT_Flanker, merged_data$Task.RT_Stroop, use = "complete.obs")
correlation_Simon_Stroop <- cor(merged_data$Task.RT_Simon, merged_data$Task.RT_Stroop, use = "complete.obs")

# Create individual plots
p1 <- ggplot(merged_data, aes(x = Task.RT_Flanker, y = Task.RT_Simon)) +
  geom_point() +
  geom_smooth(method = "lm") +
  labs(title = "Relationship between Task.RT in Flanker and Simon", 
       x = "Task.RT Flanker", 
       y = "Task.RT Simon") +
  annotate("text", x = Inf, y = Inf, label = paste("r =", round(correlation_Flanker_Simon, 2)), hjust = 1.1, vjust = 1.5, size = 5, color = "blue")

p2 <- ggplot(merged_data, aes(x = Task.RT_Flanker, y = Task.RT_Stroop)) +
  geom_point() +
  geom_smooth(method = "lm") +
  labs(title = "Relationship between Task.RT in Flanker and Stroop", 
       x = "Task.RT Flanker", 
       y = "Task.RT Stroop") +
  annotate("text", x = Inf, y = Inf, label = paste("r =", round(correlation_Flanker_Stroop, 2)), hjust = 1.1, vjust = 1.5, size = 5, color = "blue")

p3 <- ggplot(merged_data, aes(x = Task.RT_Simon, y = Task.RT_Stroop)) +
  geom_point() +
  geom_smooth(method = "lm") +
  labs(title = "Relationship between Task.RT in Simon and Stroop", 
       x = "Task.RT Simon", 
       y = "Task.RT Stroop") +
  annotate("text", x = Inf, y = Inf, label = paste("r =", round(correlation_Simon_Stroop, 2)), hjust = 1.1, vjust = 1.5, size = 5, color = "blue")

# Combine plots
combined_plot <- p1 + p2 + p3 + plot_layout(ncol = 1)
combined_plot
## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 14 rows containing non-finite outside the scale range
## (`stat_smooth()`).
## Warning: Removed 14 rows containing missing values or values outside the scale range
## (`geom_point()`).
## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 17 rows containing non-finite outside the scale range
## (`stat_smooth()`).
## Warning: Removed 17 rows containing missing values or values outside the scale range
## (`geom_point()`).
## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 14 rows containing non-finite outside the scale range
## (`stat_smooth()`).
## Warning: Removed 14 rows containing missing values or values outside the scale range
## (`geom_point()`).

# Save the combined plot
ggsave("combined_task_rt_plot.png", plot = combined_plot, dpi = 300, width = 8, height = 12, units = "in")
## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 14 rows containing non-finite outside the scale range
## (`stat_smooth()`).
## Removed 14 rows containing missing values or values outside the scale range
## (`geom_point()`).
## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 17 rows containing non-finite outside the scale range
## (`stat_smooth()`).
## Warning: Removed 17 rows containing missing values or values outside the scale range
## (`geom_point()`).
## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 14 rows containing non-finite outside the scale range
## (`stat_smooth()`).
## Warning: Removed 14 rows containing missing values or values outside the scale range
## (`geom_point()`).
# Ensure Task.RT is numeric and TrialType is a factor in the original dataset
MergeFlankerDec8_c <- MergeFlankerDec8_c %>%
  mutate(Task.RT = as.numeric(Task.RT),
         TrialType = as.factor(TrialType))

# Fit the linear mixed-effects model
model <- lme4::lmer(Task.RT ~ TrialType + (1 | Subject), data = MergeFlankerDec8_c)
summary(model)
## Linear mixed model fit by REML ['lmerMod']
## Formula: Task.RT ~ TrialType + (1 | Subject)
##    Data: MergeFlankerDec8_c
## 
## REML criterion at convergence: 133635.6
## 
## Scaled residuals: 
##     Min      1Q  Median      3Q     Max 
## -4.5477 -0.5027 -0.0986  0.4445  4.6564 
## 
## Random effects:
##  Groups   Name        Variance Std.Dev.
##  Subject  (Intercept) 307269   554.3   
##  Residual             670283   818.7   
## Number of obs: 8182, groups:  Subject, 262
## 
## Fixed effects:
##                                       Estimate Std. Error t value
## (Intercept)                            2046.32      38.94   52.55
## TrialTypeFullyIncongruent               483.78      25.76   18.78
## TrialTypeStimCongruentRespIncongruent   350.74      25.60   13.70
## TrialTypeStimIncongruentRespCongruent   312.06      25.33   12.32
## 
## Correlation of Fixed Effects:
##             (Intr) TrlTFI TTSCRI
## TrlTypFllyI -0.315              
## TrlTypStCRI -0.320  0.489       
## TrlTypStIRC -0.325  0.493  0.496
# Count the number of subjects
MergeFlankerDec8_c %>% count(Subject)
## # A tibble: 262 × 2
##    Subject     n
##      <dbl> <int>
##  1     333    66
##  2     492    35
##  3    4037    45
##  4    5088    39
##  5    6772    30
##  6   14740    47
##  7   23295    41
##  8   42195    42
##  9   43158    57
## 10   56964    25
## # ℹ 252 more rows
# Calculate ICC (Intraclass Correlation Coefficient)
icc(model)
## # Intraclass Correlation Coefficient
## 
##     Adjusted ICC: 0.314
##   Unadjusted ICC: 0.304
# Identify influential data points using Cook's distance
influential_points <- which(cooks.distance(model) >= 1, arr.ind = TRUE)
influential_points
## named integer(0)
# Load necessary libraries
library(dplyr)
library(lme4)

# Ensure Task.RT and TrialType are of the correct types
MergeFlankerDec8_c <- MergeFlankerDec8_c %>%
  mutate(Task.RT = as.numeric(Task.RT),
         TrialType = as.factor(TrialType))

# Fit the traditional linear model (lm)
lm_model <- lm(Task.RT ~ TrialType, data = MergeFlankerDec8_c)

# Fit the linear mixed-effects model (lme)
lme_model <- lme4::lmer(Task.RT ~ TrialType + (1 | Subject), data = MergeFlankerDec8_c)

# Calculate BIC for both models
bic_lm <- BIC(lm_model)
bic_lme <- BIC(lme_model)

# Print the BIC values
cat("BIC for traditional linear model:", bic_lm, "\n")
## BIC for traditional linear model: 136001.9
cat("BIC for linear mixed-effects model:", bic_lme, "\n")
## BIC for linear mixed-effects model: 133689.7
# Compare the BIC values
if (bic_lm < bic_lme) {
  cat("The traditional linear model has a lower BIC and is preferred.\n")
} else {
  cat("The linear mixed-effects model has a lower BIC and is preferred.\n")
}
## The linear mixed-effects model has a lower BIC and is preferred.
# Compute mean FinalScore for each individual in MergeFlankerDec8_c
mean_final_score_Flanker <- MergeFlankerDec8_c %>%
  group_by(Subject) %>%
  summarise(mean_FinalScore_Flanker = mean(FinalScore, na.rm = TRUE))

# Compute mean Task.RT for each individual in MergeSimonDec8th_c
mean_task_rt_Simon <- MergeSimonDec8th_c %>%
  group_by(Subject) %>%
  summarise(mean_Task.RT_Simon = mean(Task.RT, na.rm = TRUE))

# Merge the two datasets on Subject to align them for correlation calculation
merged_data <- inner_join(mean_final_score_Flanker, mean_task_rt_Simon, by = "Subject")

# Calculate the correlation
correlation <- cor(merged_data$mean_FinalScore_Flanker, merged_data$mean_Task.RT_Simon, use = "complete.obs")

# Print the correlation
print(correlation)
## [1] -0.4714869
# Load necessary libraries
library(dplyr)
library(ggplot2)
library(patchwork)

# Compute mean FinalScore for each individual in MergeFlankerDec8_c
mean_final_score_Flanker <- MergeFlankerDec8_c %>%
  group_by(Subject) %>%
  summarise(mean_FinalScore_Flanker = mean(FinalScore[FinalScore >= 0], na.rm = TRUE))

# Compute mean FinalScore for each individual in MergeSimonDec8th_c
mean_final_score_Simon <- MergeSimonDec8th_c %>%
  group_by(Subject) %>%
  summarise(mean_FinalScore_Simon = mean(FinalScore[FinalScore >= 0], na.rm = TRUE))

# Compute mean FinalScore for each individual in MergeStroopDec8Full_c
mean_final_score_Stroop <- MergeStroopDec8Full_c %>%
  group_by(Subject) %>%
  summarise(mean_FinalScore_Stroop = mean(FinalScore[FinalScore >= 0], na.rm = TRUE))

# Merge the datasets on Subject to align them for correlation calculation
merged_data_final_score <- mean_final_score_Flanker %>%
  full_join(mean_final_score_Simon, by = "Subject") %>%
  full_join(mean_final_score_Stroop, by = "Subject")

# Calculate the correlations
correlation_Flanker_Simon_FinalScore <- cor(merged_data_final_score$mean_FinalScore_Flanker, merged_data_final_score$mean_FinalScore_Simon, use = "complete.obs")
correlation_Flanker_Stroop_FinalScore <- cor(merged_data_final_score$mean_FinalScore_Flanker, merged_data_final_score$mean_FinalScore_Stroop, use = "complete.obs")
correlation_Simon_Stroop_FinalScore <- cor(merged_data_final_score$mean_FinalScore_Simon, merged_data_final_score$mean_FinalScore_Stroop, use = "complete.obs")

# Create plots
p1 <- ggplot(merged_data_final_score, aes(x = mean_FinalScore_Flanker, y = mean_FinalScore_Simon)) +
  geom_point() +
  geom_smooth(method = "lm") +
  labs(title = "Relationship between Final Scores in Flanker and Simon", 
       x = "Final Score Flanker", 
       y = "Final Score Simon") +
  annotate("text", x = Inf, y = Inf, label = paste("r =", round(correlation_Flanker_Simon_FinalScore, 2)), hjust = 1.1, vjust = 1.5, size = 5, color = "blue")

p2 <- ggplot(merged_data_final_score, aes(x = mean_FinalScore_Flanker, y = mean_FinalScore_Stroop)) +
  geom_point() +
  geom_smooth(method = "lm") +
  labs(title = "Relationship between Final Scores in Flanker and Stroop", 
       x = "Final Score Flanker", 
       y = "Final Score Stroop") +
  annotate("text", x = Inf, y = Inf, label = paste("r =", round(correlation_Flanker_Stroop_FinalScore, 2)), hjust = 1.1, vjust = 1.5, size = 5, color = "blue")

p3 <- ggplot(merged_data_final_score, aes(x = mean_FinalScore_Simon, y = mean_FinalScore_Stroop)) +
  geom_point() +
  geom_smooth(method = "lm") +
  labs(title = "Relationship between Final Scores in Simon and Stroop", 
       x = "Final Score Simon", 
       y = "Final Score Stroop") +
  annotate("text", x = Inf, y = Inf, label = paste("r =", round(correlation_Simon_Stroop_FinalScore, 2)), hjust = 1.1, vjust = 1.5, size = 5, color = "blue")

# Combine plots
combined_plot <- p1 + p2 + p3 + plot_layout(ncol = 1)
combined_plot
## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 42 rows containing non-finite outside the scale range
## (`stat_smooth()`).
## Warning: Removed 42 rows containing missing values or values outside the scale range
## (`geom_point()`).
## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 48 rows containing non-finite outside the scale range
## (`stat_smooth()`).
## Warning: Removed 48 rows containing missing values or values outside the scale range
## (`geom_point()`).
## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 17 rows containing non-finite outside the scale range
## (`stat_smooth()`).
## Warning: Removed 17 rows containing missing values or values outside the scale range
## (`geom_point()`).

# Save the combined plot
ggsave("combined_plot.png", plot = combined_plot, dpi = 300, width = 8, height = 12, units = "in")
## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 42 rows containing non-finite outside the scale range
## (`stat_smooth()`).
## Warning: Removed 42 rows containing missing values or values outside the scale range
## (`geom_point()`).
## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 48 rows containing non-finite outside the scale range
## (`stat_smooth()`).
## Warning: Removed 48 rows containing missing values or values outside the scale range
## (`geom_point()`).
## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 17 rows containing non-finite outside the scale range
## (`stat_smooth()`).
## Warning: Removed 17 rows containing missing values or values outside the scale range
## (`geom_point()`).
# Load necessary libraries
library(dplyr)
library(lme4)
library(ggplot2)

# Ensure Task.RT and FinalScore are numeric
MergeFlankerDec8_c <- MergeFlankerDec8_c %>% mutate(Task.RT = as.numeric(Task.RT))
MergeSimonDec8th_c <- MergeSimonDec8th_c %>% mutate(FinalScore = as.numeric(FinalScore))

# Remove rows with NA or zero values
MergeFlankerDec8_c <- MergeFlankerDec8_c %>% dplyr::filter(!is.na(Task.RT) & Task.RT > 0)
MergeSimonDec8th_c <- MergeSimonDec8th_c %>% dplyr::filter(!is.na(FinalScore) & FinalScore > 0)

# Compute the mean FinalScore for each individual in MergeSimonDec8th_c
mean_final_score_Simon <- MergeSimonDec8th_c %>%
  group_by(Subject) %>%
  summarise(mean_FinalScore_Simon = mean(FinalScore, na.rm = TRUE))

# Merge the mean FinalScore into MergeFlankerDec8_c
MergeFlankerDec8_c <- MergeFlankerDec8_c %>%
  left_join(mean_final_score_Simon, by = "Subject")

# Standardize the mean FinalScore and Task.RT
MergeFlankerDec8_c <- MergeFlankerDec8_c %>%
  mutate(mean_FinalScore_Simon = scale(mean_FinalScore_Simon, center = TRUE, scale = TRUE),
         Task.RT = scale(Task.RT, center = TRUE, scale = TRUE))

# Run the linear mixed-effects model
lme_model <- lme4::lmer(Task.RT ~ mean_FinalScore_Simon + TrialType + (1 | Subject), data = MergeFlankerDec8_c)

# Print the model summary
summary(lme_model)
## Linear mixed model fit by REML ['lmerMod']
## Formula: Task.RT ~ mean_FinalScore_Simon + TrialType + (1 | Subject)
##    Data: MergeFlankerDec8_c
## 
## REML criterion at convergence: 18256.7
## 
## Scaled residuals: 
##     Min      1Q  Median      3Q     Max 
## -3.8838 -0.6375 -0.1638  0.4696  5.5249 
## 
## Random effects:
##  Groups   Name        Variance Std.Dev.
##  Subject  (Intercept) 0.3280   0.5727  
##  Residual             0.5461   0.7390  
## Number of obs: 7837, groups:  Subject, 259
## 
## Fixed effects:
##                                       Estimate Std. Error t value
## (Intercept)                           -0.16748    0.04038  -4.147
## mean_FinalScore_Simon                 -0.38526    0.03549 -10.857
## TrialTypeFullyIncongruent              0.57772    0.02374  24.338
## TrialTypeStimCongruentRespIncongruent  0.42815    0.02358  18.160
## TrialTypeStimIncongruentRespCongruent  0.37951    0.02334  16.258
## 
## Correlation of Fixed Effects:
##             (Intr) m_FS_S TrlTFI TTSCRI
## mn_FnlScr_S  0.207                     
## TrlTypFllyI -0.279 -0.010              
## TrlTypStCRI -0.283 -0.011  0.486       
## TrlTypStIRC -0.286 -0.006  0.490  0.493
icc(lme_model)
## # Intraclass Correlation Coefficient
## 
##     Adjusted ICC: 0.375
##   Unadjusted ICC: 0.308
# Plot the relationship between mean FinalScore Simon and Task.RT
ggplot(MergeFlankerDec8_c, aes(x = mean_FinalScore_Simon, y = Task.RT)) +
  geom_point(color = "steelblue") +
  geom_smooth(method = "lm", se = FALSE, color = "red") +
  theme_minimal() +
  labs(title = "Relationship between Simon Final Score and Task.RT",
       x = "Simon Final Score",
       y = "Task.RT (Flanker Global RT)") +
  theme(plot.title = element_text(hjust = 0.5))
## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 83 rows containing non-finite outside the scale range
## (`stat_smooth()`).
## Warning: Removed 83 rows containing missing values or values outside the scale range
## (`geom_point()`).

# Ensure necessary libraries are loaded
library(dplyr)
library(lme4)
library(lmerTest)
library(ggplot2)
library(performance)

# Assuming you have already preprocessed and cleaned the datasets:
# Load your datasets here if not already loaded
# MergeFlankerDec8 <- read_excel("C:/path_to_your_file/MergeFlankerDec8.xlsx")
# MergeSimonDec8th <- read_excel("C:/path_to_your_file/MergeSimonDec8th.xlsx")

# Compute the mean FinalScore for each individual in MergeSimonDec8th_c
mean_final_score_Simon <- MergeSimonDec8th_c %>%
  group_by(Subject) %>%
  summarise(mean_FinalScore_Simon = mean(FinalScore, na.rm = TRUE))

# Merge the Simon FinalScore into MergeFlankerDec8_c
MergeFlankerDec8_c <- MergeFlankerDec8_c %>%
  left_join(mean_final_score_Simon, by = "Subject")

# Remove duplicate columns if they exist (e.g., if the dataset had duplicate joins previously)
MergeFlankerDec8_c <- MergeFlankerDec8_c %>%
  select(-contains("mean_FinalScore_Simon."))

# Check for the new column
if ("mean_FinalScore_Simon" %in% colnames(MergeFlankerDec8_c)) {
  # Standardize the Simon FinalScore and Task.RT
  MergeFlankerDec8_c <- MergeFlankerDec8_c %>%
    mutate(mean_FinalScore_Simon = scale(mean_FinalScore_Simon, center = TRUE, scale = TRUE),
           Task.RT = scale(Task.RT, center = TRUE, scale = TRUE))
  
  # Fit the linear mixed-effects model
  model2 <- lme4::lmer(Task.RT ~ mean_FinalScore_Simon + TrialType + (1 | Subject), data = MergeFlankerDec8_c)
  summary(model2)
  
  # Calculate ICC for model2
  icc_model2 <- performance::icc(model2)
  print(icc_model2)
  
  # Visualize the relationship between mean_FinalScore_Simon and Task.RT
  ggplot(MergeFlankerDec8_c, aes(x = mean_FinalScore_Simon, y = Task.RT)) +
    geom_point(color = "steelblue") +
    geom_smooth(method = "lm", se = FALSE, color = "red") +
    theme_minimal() +
    labs(title = "Relationship between FinalScore (Simon) and Task.RT (Flanker)",
         x = "FinalScore (Simon)",
         y = "Task.RT (Flanker)") +
    theme(plot.title = element_text(hjust = 0.5))
} else {
  print("The mean_FinalScore_Simon column does not exist in the merged dataset.")
}
## [1] "The mean_FinalScore_Simon column does not exist in the merged dataset."