#' Compute the proportion of items (like dplyr::add_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 %>% add_prop(cyl)
#' # Number of variables
#' mtcars %>% add_prop(cyl, vs)
#' # To compute the proportions relative to a variable, use a group_by
#' mtcars %>% group_by(am) %>% add_prop(cyl, vs)
#'
#' @importFrom magrittr %>%
#'
#' @export
add_prop <- function(x, ..., leave_n = FALSE, name = "prop"){
tmp <- x %>% dplyr::count(..., name = "n4prop") %>%
dplyr::mutate(`:=`(!!name, n4prop/sum(n4prop)))
if (!leave_n) {
tmp <- tmp %>% dplyr::select(-n4prop)
}
suppressMessages(
res <- x %>%
left_join(tmp)
)
return(res)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.