Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

vec_count

Count unique values in a vector


Description

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).

Dependencies

Examples

vec_count(mtcars$vs)
vec_count(iris$Species)

# If you count a data frame you'll get a data frame
# column in the output
str(vec_count(mtcars[c("vs", "am")]))

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

x <- letters[rpois(100, 6)]
# default is to sort by frequency
vec_count(x)

# by can sort by key
vec_count(x, sort = "key")

# or location of first value
vec_count(x, sort = "location")
head(x)

# or not at all
vec_count(x, sort = "none")

vctrs

Vector Helpers

v0.3.8
MIT + file LICENSE
Authors
Hadley Wickham [aut], Lionel Henry [aut, cre], Davis Vaughan [aut], data.table team [cph] (Radix sort based on data.table's forder() and their contribution to R's order()), RStudio [cph]
Initial release

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.