#' Cross Tabulate Counts
#'
#' Create a contingency table of counts generated by cross-classifying
#' factors from groups splitting on the values passed in the `...` argument.
#' The sums of each row and column are added to the result.
#'
#' @param x A `soma_adat` or `data.frame` object containing the
#' meta data from which counts are desired.
#' @param ... A number of un-quoted expressions separated by commas. Generally
#' greater than 3 is un-useful.
#' @return A table of grouped counts based on splitting
#' variables with sums from each factor.
#' @author Stu Field
#' @seealso [table()], [addmargins()]
#' @examples
#' # 1 factor
#' cross_tabulate(mtcars, cyl)
#' # 2 factors
#' cross_tabulate(mtcars, cyl, gear)
#' # 3 factors
#' cross_tabulate(mtcars, cyl, gear, am)
#' @importFrom stats addmargins
#' @importFrom dplyr select
#' @importFrom usethis ui_stop
#' @importFrom purrr map_chr
#' @importFrom rlang enquos quo_name
#' @export
cross_tabulate <- function(x, ...) {
by <- rlang::enquos(...)
by_names <- purrr::map_chr(by, rlang::quo_name)
if ( !all(by_names %in% names(x)) ) {
usethis::ui_stop(
"Missing or misspelled entry: {paste0(by_names, collapse = ' or ')}"
)
}
dplyr::select(x, !!!by) %>%
table(dnn = NULL) %>%
stats::addmargins()
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.