Learn R Programming

mark (version 0.8.1)

counts: Count observations by unique values

Description

Variables will be return by the order in which they appear. Even factors are shown by their order of appearance in the vector.

There are 2 methods for counting vectors. The default method uses base::tabulate() (the workhorse for base::table() with a call to pseudo_id() to transform all inputs into integers. The logical method counts TRUE, FALSE and NA values, which is much quicker.

Usage

counts(x, ...)

# S3 method for data.frame counts(x, cols, sort = FALSE, ..., .name = "freq")

props(x, ...)

# S3 method for default props(x, sort = FALSE, na.rm = FALSE, ...)

# S3 method for data.frame props(x, cols, sort = FALSE, na.rm = FALSE, ..., .name = "prop")

Value

A named vector of integers or doubles (for counts, and props, respectively) or data.frame with columns for each column chosen and the .name chosen for the summary

Arguments

x

A vector or data.frame

...

Arguments passed to other methods

cols

A vector of column names or indexes

sort

Logical, if TRUE will sort values (not counts) before returning. For factors this will sort by factor levels. This has no effect for logical vectors, which already return in the order of FALSE, TRUE, NA.

.name

The name of the new column

na.rm

If TRUE will remove NA values from proportions

Details

Get counts or proportions of unique observations in a vector or columns in a data.frame

Examples

Run this code
x <- sample(1:5, 10, TRUE)
counts(x)
props(x)

x <- quick_df(list(
  a = c("a", "c", "a", "c", "d", "b"),
  b = c("a", "a", "a", "c", "c", "b"),
  c = c("a", "a", "a", "c", "b", "b")
))

counts(x, "a")
counts(x, c("a", "b", "c"))
props(x, 2)
props(x, 1:3)

props(c(1, 1, 3, NA, 4))
props(c(1, 1, 3, NA, 4), na.rm = TRUE)

Run the code above in your browser using DataLab