Skip to content

Instantly share code, notes, and snippets.

@jgeller112
Created September 5, 2024 14:32
Show Gist options
  • Save jgeller112/f9f66940cb00d8b02b211378b6761d2f to your computer and use it in GitHub Desktop.
Save jgeller112/f9f66940cb00d8b02b211378b6761d2f to your computer and use it in GitHub Desktop.
Calculate ISC Pupil/Eye movements
calculate_isc_per_subject <- function(data_matrix, window_size = 10) {
# data_matrix: A matrix where each column is a participant and each row is a time point.
# window_size: The size of the sliding window for calculating correlations.
n_timepoints <- nrow(data_matrix)
n_participants <- ncol(data_matrix)
# Check that the number of participants is greater than 1
if (n_participants <= 1) {
stop("There must be more than one participant to calculate inter-subject correlation.")
}
# Initialize a vector to store ISC values for each subject
isc_values <- numeric(n_participants)
# Loop over each participant to calculate their ISC
for (subject in 1:n_participants) {
z_values <- numeric() # Store z-transformed correlation coefficients
# Loop over the time points with a sliding window
for (i in 1:(n_timepoints - window_size + 1)) {
# Subset the data for the current window
window_data <- data_matrix[i:(i + window_size - 1), ]
# Calculate the average time series of all other subjects
other_subjects_mean <- rowMeans(window_data[, -subject])
# Correlate the excluded subject's data with the average of the other subjects
subject_corr <- cor(window_data[, subject], other_subjects_mean)
# Apply Fisher's r-to-z transformation
z_values <- c(z_values, atanh(subject_corr))
}
# Average the z-values and inverse Fisher transformation back to r
avg_z_value <- mean(z_values)
isc_values[subject] <- tanh(avg_z_value)
}
return(isc_values)
}
# Example data: a matrix with 5 participants and 100 time points
#set.seed(123)
#data_matrix <- matrix(rnorm(500), nrow = 100, ncol = 5)
# Calculate ISC for each subject with a sliding window of size 10
#isc_result_per_subject <- calculate_isc_per_subject(data_matrix, window_size = 10)
# View ISC values for each subject
#print(isc_result_per_subject)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment