# This function defines a matrix that is used to add transformed residuals.
# Grouping is determined by using res_order.
define_grouping_matrix <- function(X, res_order){
  if(length(unique(res_order)) == 1)
    stop("Grouping is unavailable when only one unique combination of covariate values is supplied.")
  mm <- unname(model.matrix(~ as.factor(res_order) - 1))
  matrix_scales <- sqrt(colSums(mm))
  grouping_matrix <- t(t(mm)/matrix_scales)
  
  return(grouping_matrix)
}
