Skip to content

Instantly share code, notes, and snippets.

@dgrtwo
Last active August 22, 2016 02:13
Show Gist options
  • Select an option

  • Save dgrtwo/2411974dbf38bf5a363b61286a9feaea to your computer and use it in GitHub Desktop.

Select an option

Save dgrtwo/2411974dbf38bf5a363b61286a9feaea to your computer and use it in GitHub Desktop.
add_tally and add_count
#' Add a column counting or tallying observations within groups
#'
#' \code{add_tally} adds a column named "n" (or similar) to a table based on the number
#' of items within each group. These functions are to \code{tally} and
#' \code{count} as \code{mutate} is to \code{summarise}: they add an additional
#' column. They tally within the groups of the current data, and do not change them.
#'
#' @param x A table
#' @param wt (Optional) If omitted, will count the number of rows. Otherwise, use a weighted tally
#' @param sort Whether to sort the result in descending order of n
#'
#' @examples
#'
#' add_tally(mtcars)
#' add_tally(group_by(mtcars, cyl))
#' add_tally(group_by(mtcars, cyl), sort = TRUE)
#'
#' add_count(mtcars, cyl)
#' add_count(mtcars, cyl, am)
#'
#' @export
add_tally <- function(x, wt, sort = FALSE) {
if (missing(wt)) {
if ("n" %in% names(x)) {
message("Using n as weighting variable")
wt <- quote(n)
}
else {
wt <- NULL
}
}
else {
wt <- substitute(wt)
}
add_tally_(x, wt, sort = sort)
}
#' @rdname add_tally
#' @export
add_tally_ <- function(x, wt = NULL, sort = FALSE) {
g <- groups(x)
if (is.null(wt)) {
n <- quote(n())
}
else {
n <- lazyeval::interp(quote(sum(wt, na.rm = TRUE)), wt = wt)
}
n_name <- n_name(tbl_vars(x))
out <- mutate_(x, .dots = setNames(list(n), n_name))
if (sort) {
desc_n <- lazyeval::interp(quote(desc(n)), n = as.name(n_name))
out <- arrange_(out, desc_n)
}
group_by_(out, .dots = g)
}
#' @rdname add_tally
#' @export
add_count <- function(x, ..., wt = NULL, sort = FALSE) {
vars <- lazyeval::lazy_dots(...)
wt <- substitute(wt)
add_count_(x, vars, wt, sort = sort)
}
#' @rdname add_tally
#' @export
add_count_ <- function(x, vars, wt = NULL, sort = FALSE) {
g <- groups(x)
grouped <- group_by_(x, .dots = vars, add = TRUE)
ret <- add_tally_(grouped, wt = wt, sort = sort)
group_by_(ret, .dots = g)
}
@evbettor

Copy link
Copy Markdown

where is the function n_name first defined?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment