Skip to content

Count the number of unique values in a vector. vec_count() has two important differences to table(): it returns a data frame, and when given multiple inputs (as a data frame), it only counts combinations that appear in the input.

Usage

vec_count(x, sort = c("count", "key", "location", "none"))

Arguments

x

A vector (including a data frame).

sort

One of "count", "key", "location", or "none".

  • "count", the default, puts most frequent values at top

  • "key", orders by the output key column (i.e. unique values of x)

  • "location", orders by location where key first seen. This is useful if you want to match the counts up to other unique/duplicated functions.

  • "none", leaves unordered. This is not guaranteed to produce the same ordering across R sessions, but is the fastest method.

Value

A data frame with columns key (same type as x) and count (an integer vector).

Examples

vec_count(mtcars$vs)
#>   key count
#> 1   0    18
#> 2   1    14
vec_count(iris$Species)
#>          key count
#> 1     setosa    50
#> 2 versicolor    50
#> 3  virginica    50

# If you count a data frame you'll get a data frame
# column in the output
str(vec_count(mtcars[c("vs", "am")]))
#> 'data.frame':	4 obs. of  2 variables:
#>  $ key  :'data.frame':	4 obs. of  2 variables:
#>   ..$ vs: num  0 1 1 0
#>   ..$ am: num  0 1 0 1
#>  $ count: int  12 7 7 6

# Sorting ---------------------------------------

x <- letters[rpois(100, 6)]
# default is to sort by frequency
vec_count(x)
#>    key count
#> 1    d    18
#> 2    f    18
#> 3    g    18
#> 4    h    12
#> 5    c     9
#> 6    e     9
#> 7    i     5
#> 8    j     3
#> 9    l     3
#> 10   k     3
#> 11   a     1
#> 12   b     1

# by can sort by key
vec_count(x, sort = "key")
#>    key count
#> 1    a     1
#> 2    b     1
#> 3    c     9
#> 4    d    18
#> 5    e     9
#> 6    f    18
#> 7    g    18
#> 8    h    12
#> 9    i     5
#> 10   j     3
#> 11   k     3
#> 12   l     3

# or location of first value
vec_count(x, sort = "location")
#>    key count
#> 1    h    12
#> 2    c     9
#> 3    d    18
#> 4    a     1
#> 5    e     9
#> 6    i     5
#> 7    j     3
#> 8    f    18
#> 9    g    18
#> 10   l     3
#> 11   b     1
#> 12   k     3
head(x)
#> [1] "h" "h" "h" "h" "c" "h"

# or not at all
vec_count(x, sort = "none")
#>    key count
#> 1    e     9
#> 2    a     1
#> 3    c     9
#> 4    k     3
#> 5    g    18
#> 6    f    18
#> 7    d    18
#> 8    l     3
#> 9    j     3
#> 10   b     1
#> 11   h    12
#> 12   i     5