counts: Count observations by unique values

View source: R/counts.R

countsR Documentation

Count observations by unique values


Variables will be return by the order in which they appear. Even factors are shown by their order of appearance in the vector.

There are 2 methods for counting vectors. The default method uses base::tabulate() (the workhorse for base::table() with a call to pseudo_id() to transform all inputs into integers. The logical method counts TRUE, FALSE and NA values, which is much quicker.


counts(x, ...)

## S3 method for class 'data.frame'
counts(x, cols, sort = FALSE, ..., .name = "freq")

props(x, ...)

## Default S3 method:
props(x, sort = FALSE, na.rm = FALSE, ...)

## S3 method for class 'data.frame'
props(x, cols, sort = FALSE, na.rm = FALSE, ..., .name = "prop")



A vector or data.frame


Arguments passed to other methods


A vector of column names or indexes


Logical, if TRUE will sort values (not counts) before returning. For factors this will sort by factor levels. This has no effect for logical vectors, which already return in the order of FALSE, TRUE, NA.


The name of the new column


If TRUE will remove NA values from proportions


Get counts or proportions of unique observations in a vector or columns in a data.frame


A named vector of integers or doubles (for counts, and props, respectively) or data.frame with columns for each column chosen and the .name chosen for the summary


x <- sample(1:5, 10, TRUE)

x <- quick_df(list(
  a = c("a", "c", "a", "c", "d", "b"),
  b = c("a", "a", "a", "c", "c", "b"),
  c = c("a", "a", "a", "c", "b", "b")

counts(x, "a")
counts(x, c("a", "b", "c"))
props(x, 2)
props(x, 1:3)

props(c(1, 1, 3, NA, 4))
props(c(1, 1, 3, NA, 4), na.rm = TRUE)

mark documentation built on May 29, 2024, 5:13 a.m.