# Load required packages library(psych) library(Hmisc) library(corrplot) library(openxlsx) # Specify variables variables <- c("GAD", "GDS", "WEMWBS", "CFRS", "PCA_RC1", "PCA_RC2", "BERQ_ActivelyApproach", "BERQ_Distraction", "BERQ_Withdrawal", "BERQ_SocialSupport", "BERQ_Ignoring", "CERQ_SelfBlame", "CERQ_Acceptance", "CERQ_Rumination", "CERQ_Refocus", "CERQ_Planning", "CERQ_Reappraisal", "CERQ_Perspective", "CERQ_Catastrophising", "CERQ_OtherBlame", "Age", "Education", "UPDRS_Motor", "PD_Duration", "MoCA_Total") # Subset the dataframe df_subset <- df2[, variables] # Calculate the Spearman correlation matrix and p-values cor_results <- rcorr(as.matrix(df_subset), type = "spearman") # Extract the correlation coefficients and p-values cor_matrix <- cor_results$r p_matrix <- cor_results$P # Define the number of tests for Bonferroni correction n_tests <- sum(upper.tri(cor_matrix)) alpha_bonferroni <- 0.05 / n_tests # Create a matrix to store both correlation coefficients and significance asterisks combined_matrix <- matrix("", ncol = length(variables), nrow = length(variables)) colnames(combined_matrix) <- variables rownames(combined_matrix) <- variables # Fill the matrix with correlation coefficients and significance asterisks for (i in 1:nrow(cor_matrix)) { for (j in 1:ncol(cor_matrix)) { if (!is.na(p_matrix[i, j])) { # Determine significance level based on p-value significance <- ifelse(p_matrix[i, j] <= 0.001, "***", ifelse(p_matrix[i, j] <= 0.01, "**", ifelse(p_matrix[i, j] <= 0.05, "*", ""))) # Store the correlation coefficient rounded to 3 decimal places and significance level in the matrix combined_matrix[i, j] <- sprintf("%.3f%s", round(cor_matrix[i, j], 3), significance) } } } # Convert the matrix to a data frame Q1B_Correlations <- as.data.frame(combined_matrix) # Print the combined matrix print(Q1B_Correlations) # Define the file path to save the Excel file file_path <- "~/Desktop/Q1B_Correlations.xlsx" # Write the combined matrix to an Excel file write.xlsx(Q1B_Correlations, file_path)