tally {dplyr} | R Documentation |
tally()
is a convenient wrapper for summarise that will either call
n()
or sum(n)
depending on whether you're tallying
for the first time, or re-tallying. count()
is similar but calls
group_by()
before and ungroup()
after. If the data is already
grouped, count()
adds an additional group that is removed afterwards.
add_tally()
adds a column n
to a table based on the number
of items within each existing group, while add_count()
is a shortcut that
does the grouping as well. These functions are to tally()
and count()
as mutate()
is to summarise()
:
they add an additional column rather than collapsing each group.
tally(x, wt = NULL, sort = FALSE, name = "n") count(x, ..., wt = NULL, sort = FALSE, name = "n", .drop = group_by_drop_default(x)) add_tally(x, wt, sort = FALSE, name = "n") add_count(x, ..., wt = NULL, sort = FALSE, name = "n")
x |
a |
wt |
(Optional) If omitted (and no variable named |
sort |
if |
name |
The output column name. If omitted, it will be |
... |
Variables to group by. |
.drop |
see |
A tbl, grouped the same way as x
.
The column name in the returned data is given by the name
argument,
set to "n"
by default.
If the data already has a column by that name, the output column
will be prefixed by an extra "n"
as many times as necessary.
# tally() is short-hand for summarise() mtcars %>% tally() mtcars %>% group_by(cyl) %>% tally() # count() is a short-hand for group_by() + tally() mtcars %>% count(cyl) # Note that if the data is already grouped, count() adds # an additional group that is removed afterwards mtcars %>% group_by(gear) %>% count(carb) # add_tally() is short-hand for mutate() mtcars %>% add_tally() # add_count() is a short-hand for group_by() + add_tally() mtcars %>% add_count(cyl) # count() and tally() are designed so that you can call # them repeatedly, each time rolling up a level of detail species <- starwars %>% count(species, homeworld, sort = TRUE) species species %>% count(species, sort = TRUE) # Change the name of the newly created column: species <- starwars %>% count(species, homeworld, sort = TRUE, name = "n_species_by_homeworld") species species %>% count(species, sort = TRUE, name = "n_species") # add_count() is useful for groupwise filtering # e.g.: show details for species that have a single member starwars %>% add_count(species) %>% filter(n == 1)