library(hypervolume)
library(tidyverse)
library(BAT)

setwd('')

data <- read.csv('Results/amalgamated_results.csv')

# calculate beta diversity metrics
for(i in 1:nrow(data)) {
      load(paste0('Results/HV_objects/',
                  data$Species[i],
                  '_hv_objects.RData'))
      # select random numbers to sample
      con_samples <- sample(1:200, 100, replace = FALSE)
      null_samples <- sample(1:1000, 100, replace = FALSE)
      betas <- list()
      for(j in 1:100) {
        b <- kernel.beta(hypervolume_join(contemporary_hypervolume[[con_samples[j]]],
                                          null_hypervolume[[null_samples[j]]]))
        betas[[j]] <- data.frame(total = b$Btotal[1],
                                 repl = b$Brepl[1],
                                 rich = b$Brich[1])
      }
      betas <- bind_rows(betas)
      data$Btotal[i] <- mean(betas$total)
      data$BtotalSD[i] <- sd(betas$total)
      data$Brepl[i] <- mean(betas$repl)
      data$BreplSD[i] <- sd(betas$repl)
      data$Brich[i] <- mean(betas$rich)
      data$BrichSD[i] <- sd(betas$rich)
}

write.csv(data,
          'Results/amalgamated_data-beta.csv',
          row.names = F)














