# Load the required libraries
library(data.table)
library(stats)

# Specify the file path to data
input_file <- ""

# Read the gene expression data
gene_expression <- fread(input_file, header = TRUE)

# Specify the list of gene IDs you want to test co-expression data with 
query_gene_ids <- c("1315611","1232421", etc
                    
                    
                    
        
                    
) 

# Filter the data to include only therequested  gene IDs
filtered_gene_expression <- gene_expression[Protein_Id %in% query_gene_ids,]

# Initialize a list to store the results
pairwise_results <- list()

# Loop through each pair of genes
for (i in 1:(nrow(filtered_gene_expression) - 1)) {
  for (j in (i + 1):nrow(filtered_gene_expression)) {
    
    # Extract gene expression values, excluding the first column (gene IDs)
    gene1_expression <- as.numeric(filtered_gene_expression[i, -1, with = FALSE])
    gene2_expression <- as.numeric(filtered_gene_expression[j, -1, with = FALSE])
    
    # Check for non-finite values and exclude them
    valid_idx <- which(is.finite(gene1_expression) & is.finite(gene2_expression))
    
    # Only compute correlation if there are enough valid observations
    if (length(valid_idx) > 2) {  # At least 3 valid observations are needed
      spearman_result <- cor.test(gene1_expression[valid_idx], gene2_expression[valid_idx], method = "spearman", exact = FALSE)
      pairwise_results[[length(pairwise_results) + 1]] <- data.frame(
        Gene1 = filtered_gene_expression$Protein_Id[i],
        Gene2 = filtered_gene_expression$Protein_Id[j],
        Spearman_Correlation = spearman_result$estimate,
        P_Value = spearman_result$p.value,
        Adjusted_P_Value = NA  # Placeholder for now
      )
    } else {
      # If not enough valid observations, record NA
      pairwise_results[[length(pairwise_results) + 1]] <- data.frame(
        Gene1 = filtered_gene_expression$Protein_Id[i],
        Gene2 = filtered_gene_expression$Protein_Id[j],
        Spearman_Correlation = NA,
        P_Value = NA,
        Adjusted_P_Value = NA
      )
    }
  }
}

# Combine the list of data frames into a single data frame
pairwise_results <- do.call(rbind, pairwise_results)

# Adjust p-values for multiple comparisons using the Benjamini-Hochberg method
pairwise_results$Adjusted_P_Value <- p.adjust(pairwise_results$P_Value, method = "BH")

# Specify the output file path
output_file <- ""

# Save the correlations to a text file
write.table(pairwise_results, file = output_file, sep = "\t", quote = FALSE, row.names = FALSE)

# Print a message to confirm that the file has been saved
cat("Spearman correlations between specified genes saved in your folder as", output_file, "\n")

