library(caret)
library(mda)

# Load data
datos_pca <- read.csv("/divergencemda.csv", header = TRUE)
datos_pca$spp <- as.factor(datos_pca$spp)

# Preliminary model fitting
tuneGrid <- expand.grid(subclasses = 1:10)  
fitControl <- trainControl(method = "cv", number = 10)  
model <- caret::train(spp ~ RC1 + RC2 + RC3, data = datos_pca, method = "mda", trControl = fitControl, tuneGrid = tuneGrid)
print(model)

# Fit the definitive model
MDA <- mda(spp ~ RC1 + RC2 + RC3, data = datos_pca, subclasses = model$bestTune$subclasses)
MDA

# Extract discriminant function coordinates
coordenadas <- as.data.frame(predict(MDA, newdata = datos_pca, type = "variates"))
predicciones <- predict(MDA, newdata = datos_pca)

# Overall confusion matrix
confusion_matrix <- confusionMatrix(predicciones, datos_pca$spp)
print(confusion_matrix)

# Confusion matrix with percentages
confusion_table <- confusion_matrix$table
confusion_percent <- prop.table(confusion_table, margin = 1) * 100
confusion_percent <- round(confusion_percent, 2)
confusion_percent
