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    17
#> 2    e    16
#> 3    g    14
#> 4    f    14
#> 5    i     9
#> 6    c     8
#> 7    b     6
#> 8    j     6
#> 9    l     4
#> 10   h     3
#> 11   a     2
#> 12   k     1

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

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

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