#' Compute the proportion of items (like dplyr::count() does with number of appearances)
#'
#' @param x a tbl() to compute proportions
#' @param leave_n if TRUE will also generate a column named n4prop (FALSE by default).
#' @param name The output column name. If omitted, it will be prop.
#' @param ... Variables to group by
#'
#' @return A tbl, grouped the same way as x.
#'
#' @examples
#' # Without any grouping, just calc proportions
#' mtcars %>% prop(cyl)
#' # Number of variables
#' mtcars %>% prop(cyl, vs)
#' # To compute the proportions relative to a variable, use a group_by
#' mtcars %>% group_by(am) %>% prop(cyl, vs)
#'
#' @importFrom magrittr %>%
#'
#' @export
prop <- function(x, ..., leave_n = FALSE, name = "prop"){
res <- x %>%
dplyr::count(..., name = "n4prop") %>%
dplyr::mutate(!!name := n4prop/sum(n4prop))
if (!leave_n){
res <- res %>% dplyr::select(-n4prop)
}
return(res)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.