
install.packages("readxl")
install.packages("factoextra")
install.packages("ggplot2")

library(readxl)
library(factoextra)
library(ggplot2)

# 📁 Chemin du fichier et noms des feuilles
file_path <- "~/Desktop/LSM/Mémoire/UEQ - Imprort Rstudio .xlsx"
sheet_names <- c(
  "Proprioception Balance B",
  "Proprioception BOSU",
  "Equilibrioception Balance B",
  "Equilibrioception BOSU",
  "Monbazillac Smell",
  "Rivaner Smell",
  "Monbazillac Taste",
  "Rivaner Taste"
)

# 📂 Liste pour stocker les résultats
all_contrib <- list()

# 🔁 Boucle sur chaque feuille
for (sheet in sheet_names) {
  
  cat("\n🔎 PCA pour :", sheet, "\n")
  
  # Étape 1 : Charger et filtrer les données
  data <- read_excel(file_path, sheet = sheet)
  data_numeric <- data[, sapply(data, is.numeric)]
  
  if (ncol(data_numeric) < 2) {
    cat("⚠️ Trop peu de variables numériques dans", sheet, "- ignoré.\n")
    next
  }
  
  # Étape 2 : PCA
  data_scaled <- scale(data_numeric)
  pca_result <- prcomp(data_scaled, center = TRUE, scale. = TRUE)
  
  # Étape 3 : Contributions (PC1 + PC2)
  pca_var <- get_pca_var(pca_result)
  total_contrib <- rowSums(pca_var$contrib[, 1:2])
  sorted_contrib <- sort(total_contrib, decreasing = TRUE)
  
  # Affichage propre
  print(round(sorted_contrib, 2))
  
  # Sauvegarder dans la liste
  contrib_df <- data.frame(
    Sheet = sheet,
    Variable = names(sorted_contrib),
    Contribution_PC1_PC2 = round(sorted_contrib, 2)
  )
  all_contrib[[sheet]] <- contrib_df
  
  # ---- Ajout des graphiques principaux ----
  cat("\n📊 Scree Plot (Variance expliquée):\n")
  print(fviz_eig(pca_result, addlabels = TRUE, ylim = c(0, 100), title = paste("Scree Plot -", sheet)))
  
  cat("\n📌 Biplot (Individus + Variables):\n")
  print(fviz_pca_biplot(pca_result, repel = TRUE, col.var = "red", col.ind = "blue", title = paste("Biplot -", sheet)))
}
