######################################################################################
#                                                                                    #
# Function for creating unbalanced datasets and calling function grow_RF to get VIs  #
#                                                                                    #
# Input: - Imbalance level                                                           #
#       (- number of iterations 'niter')                                             #
#                                                                                    #
# Output: list of VIs using ER-based and AUC-based permutation VIM                   #
#         1st list element: (43*2 x niter) matrix of VI values using AUC-based VIM   #
#         2nd list element: (43*2 x niter) matrix of VI values using ER-based VIM    #
#                                                                                    #
######################################################################################


calc_VIMs <- function(imbalance = 0.25, niter = 100){

  # Get number of plus-class for pre-specified imbalance level
  n.minor <- ceiling((imbalance * dim(arabidopsis_minus)[1]) / (1 - imbalance))

  # Number of majority class is fixed to 1307 (<- orig. number)
  n.major <- dim(arabidopsis_minus)[1]

  plus_index_matrix <- matrix(rep(plus_index, niter), ncol = niter)

  set.seed(1234)     # set seed for reproducibility
  
  # Take subsamples from plus-class (niter times)
  plus_index_sel_matrix <- apply(plus_index_matrix, 2, function(x)
                                 sample(x, n.minor, replace = FALSE))
                                 
  # For each iteration call function 'growRF'
  res <- apply(plus_index_sel_matrix, 2, grow_RF)

  # Save VIs in matrices  
  AUC_VI <- data.frame(res)[, grep("varimp.AUC", colnames(data.frame(res)))]
  ER_VI  <- data.frame(res)[, grep("varimp.ER",  colnames(data.frame(res)))]

  # Build list object containing VI values
  res    <- list(AUC_VI = AUC_VI, ER_VI = ER_VI)
  
  return(res)  # return list
  
}