R/percent_hungry.R

#' Calculate the Percentage of Yes Responses
#' @description Calculate the sample proportion of "Yes" responses in the specified variable.
#'
#' @param data_frame A tidy representation of the data,
#' in which each row represents a response.
#' @param yes_no_variable A "quosure" object specifying the variable that contains the
#' "Yes" and "No" responses to be tallied. This should be passed as the form quo(varname).
#'
#' @return The proportion of "Yes" responses in yes_no_variable in data_Frame.
#' @export
#' @importFrom magrittr %>%
#' @import dplyr
#'
#' @seealso quo for examples of how to quote variable names
#' @examples
#' df <- data.frame(foo=c(1,2,3), bar=c("Yes", "No", "Yes"))
#' percent_hungry(df, dplyr::quo(bar))
percent_hungry <- function(data_frame, yes_no_variable) {

  if(!inherits(yes_no_variable,"quosure")) {
    stop("Incorrect usage of percent_hungry. See documentation for usage of yes_no_variable.")
  }

  proportion <- data_frame %>%
    dplyr::group_by(!!yes_no_variable) %>%
    dplyr::summarize(n = n()) %>%
    dplyr::mutate(n = n/sum(n)) %>%
    dplyr::filter(UQ(yes_no_variable) == "Yes") %>%
    dplyr::pull("n")

  return(proportion * 100)
}
jmiahjones/lunch.time documentation built on May 29, 2019, 1:05 a.m.