#' Downsampling Function For Binary Response
#'
#' This function serves a way to balance a binary response through downsampling.
#' @param training_data the training data set
#' @param target.var an unquoted expression referring to the binary response variable
#' @export
#' @examples
#' data %>% downsample(binary.response)
downsample <- function(training_data, target.var){
training_data <- as_tibble(training_data)
target.var <- enexpr(target.var)
check_for_binary_response(eval(expr(`$`(training_data,!!target.var))))
split_data <- split_by_class(training_data, target.var)
indices.vector <- 1:nrow(split_data$majority_class)
minority.class.length <- nrow(split_data$minority_class)
balanced.majority_class <- split_data$majority_class[sample(x = indices.vector, size = minority.class.length), ]
balanced.data <- bind_rows(balanced.majority_class, split_data$minority_class)
return(balanced.data)
}
#'Binary Response Checking Function
#'
#'This function checks for binary response
#'@param unquoted.target.var unquoted response variable
check_for_binary_response <- function(unquoted.target.var){
if(length(unique(unquoted.target.var)) != 2){
stop("Response factor does not have exactly two levels.")
}
}
#'Tibble Splitting Function for Binary Response
#'
#'Takes a tibble with a binary response and then puts them in a list that categorizes
#'one dataset as a majority case and the other as a minority case.
#'
#'@param training_data a training data set
#'@param target.var.expr an expression that refers to the binary response variable
split_by_class <- function(training_data, target.var.expr){
class_split <- training_data %>% group_split(!!target.var.expr)
names(class_split)[which.max(map_dbl(class_split, nrow))] <- "majority_class"
names(class_split)[which.min(map_dbl(class_split, nrow))] <- "minority_class"
return(class_split)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.