#' Add totals (sums or means) to a dataset.
#' @param x Data.frame. Data to which you wish to add the totals
#' @param rows Logical. Whether totals should be added at the bottom of the table.
#' @param columns Logical. Whether totals should be added at the right-side of the table.
#' @param omit_col Character vector. Names of the variables not to be included in the total.
#' @param summary Character. Whether the total is a "sum" or a "mean".
#' @return Character vector with coefficients formatted for publication.
#' @importFrom dplyr %>%
#' @importFrom dplyr mutate
#' @importFrom dplyr select
#' @importFrom dplyr bind_rows
#' @export
stat_totals <- function(x,
rows = TRUE,
columns = TRUE,
omit_col = NA,
summary = "sum"){
if (rows){
y <- dplyr::select(x,-omit_col)
if (summary == "sum") {
srows <- as.data.frame(t(colSums(y, na.rm = TRUE)))
} else {
srows <- as.data.frame(t(colMeans(y, na.rm = TRUE)))
}
x <- bind_rows(x, srows)
}
if (columns){
y <- dplyr::select(x,-omit_col)
if (summary == "sum") {
x$Total <- rowSums(y, na.rm = TRUE)
} else {
x$Total <- rowMeans(y, na.rm = TRUE)
}
}
dplyr::select(x, omit_col, everything())
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.