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.

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    f    20
#> 2    d    13
#> 3    c    13
#> 4    e    11
#> 5    g    10
#> 6    i     9
#> 7    b     9
#> 8    h     8
#> 9    j     4
#> 10   l     2
#> 11   k     1

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

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

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