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