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.
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 18
#> 2 e 15
#> 3 d 15
#> 4 g 13
#> 5 c 10
#> 6 h 9
#> 7 j 6
#> 8 i 4
#> 9 k 4
#> 10 l 3
#> 11 a 2
#> 12 b 1
# by can sort by key
vec_count(x, sort = "key")
#> key count
#> 1 a 2
#> 2 b 1
#> 3 c 10
#> 4 d 15
#> 5 e 15
#> 6 f 18
#> 7 g 13
#> 8 h 9
#> 9 i 4
#> 10 j 6
#> 11 k 4
#> 12 l 3
# or location of first value
vec_count(x, sort = "location")
#> key count
#> 1 a 2
#> 2 f 18
#> 3 d 15
#> 4 h 9
#> 5 g 13
#> 6 c 10
#> 7 e 15
#> 8 k 4
#> 9 j 6
#> 10 l 3
#> 11 i 4
#> 12 b 1
head(x)
#> [1] "a" "f" "d" "h" "g" "g"
# or not at all
vec_count(x, sort = "none")
#> key count
#> 1 f 18
#> 2 b 1
#> 3 i 4
#> 4 k 4
#> 5 a 2
#> 6 e 15
#> 7 l 3
#> 8 d 15
#> 9 g 13
#> 10 j 6
#> 11 c 10
#> 12 h 9