% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/count-tally.R
\name{count}
\alias{count}
\alias{tally}
\alias{add_count}
\alias{add_tally}
\title{Count observations by group}
\usage{
count(x, ..., wt = NULL, sort = FALSE, name = NULL)

tally(x, wt = NULL, sort = FALSE, name = NULL)

add_count(x, ..., wt = NULL, sort = FALSE, name = NULL)

add_tally(x, wt = NULL, sort = FALSE, name = NULL)
}
\arguments{
\item{x}{A \code{data.frame}.}

\item{...}{Variables to group by.}

\item{wt}{If omitted, will count the number of rows. If specified, will perform a "weighted" count by summing the
(non-missing) values of variable \code{wt}. If omitted, and column \code{n} exists, it will automatically be used as a
weighting variable, although you will have to specify \code{name} to provide a new name for the output.}

\item{sort}{\code{logical(1)}. If \code{TRUE}, will show the largest groups at the top.}

\item{name}{\code{character(1)}. The name of the new column in the output. If omitted, it will default to \code{n}. If there's
already a column called \code{n}, it will error, and require you to specify the name.}
}
\value{
A \code{data.frame}. \code{count()} and \code{add_count()} have the same groups as the input.
}
\description{
\code{count()} lets you quickly count the unique values of one or more variables:
\code{df \%>\% count(a, b)} is roughly equivalent to
\code{df \%>\% group_by(a, b) \%>\% summarise(n = n())}.
\code{count()} is paired with \code{tally()}, a lower-level helper that is equivalent to \code{df \%>\% summarise(n = n())}. Supply
\code{wt} to perform weighted counts, switching the summary from from \code{n = n()} to \code{n = sum(wt)}.
\code{add_count()} and \code{add_tally()} are equivalent to \code{count()} and \code{tally()} but use \code{mutate()} instead of \code{summarise()}
so that they add a new column with group-wise counts.
}
\examples{
# count() is a convenient way to get a sense of the distribution of
# values in a dataset
mtcars \%>\% count(cyl)
mtcars \%>\% count(cyl, sort = TRUE)
mtcars \%>\% count(cyl, am, sort = TRUE)
# Note that if the data are already grouped, count() adds an additional grouping variable
# which is removed afterwards
mtcars \%>\% group_by(gear) \%>\% count(cyl)

# tally() is a lower-level function that assumes you've done the grouping
mtcars \%>\% tally()
mtcars \%>\% group_by(cyl) \%>\% tally()

# both count() and tally() have add_ variants that work like mutate() instead of summarise
mtcars \%>\% add_count(cyl, wt = am)
mtcars \%>\% add_tally(wt = am)

}
