Generate a crosstabulation of two vectors.

Share:

Description

Create a crosstab, displaying either frequencies or percentages calculated by row, column, or overall.

crosstab can be called in two ways:

1) It can simply be called on two vectors, like crosstab(mtcars$gear, mtcars$cyl).

2) Or, when both vectors are columns in a single data.frame, the data.frame can be provided as the first argument, followed by two unquoted column names to crosstabulate. This enables passing in a data.frame from a %>% pipeline, in addition to making for a shorter function call. Like mtcars %>% crosstab(gear, cyl).

For fancy formatting of the resulting data.frame, see adorn_crosstab.

Usage

1
2
3
4
5
6
7
8
crosstab(...)

## Default S3 method:
crosstab(vec1, vec2, percent = "none", show_na = TRUE,
  ...)

## S3 method for class 'data.frame'
crosstab(.data, ...)

Arguments

...

additional arguments, if calling crosstab on a data.frame.

vec1

the vector to place on the crosstab column. If supplying a data.frame, this should be an unquoted column name.

vec2

the vector to place on the crosstab row. If supplying a data.frame, this should be an unquoted column name.

percent

which grouping to use for percentages, if desired (defaults to "none", which returns simple counts). Must be one of "none", "row", "col", or "all".

show_na

a logical value indicating whether counts should be displayed where either variable is NA.

.data

(optional) a data.frame, in which case vec1 and vec2 should be unquoted column names.

Value

Returns a data.frame with the frequencies of the crosstabulated variables.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# Calling on two vectors:
a <- c("hi", "hi", "lo", "lo")
b <- c(1, 2, 2, 2)
crosstab(a, b)

crosstab(mtcars$cyl, mtcars$gear)
crosstab(mtcars$cyl, mtcars$gear, "row")

# Passing in a data.frame using a pipeline:
library(dplyr) # to access the pipe operator
mtcars %>% crosstab(cyl, gear)
mtcars %>% crosstab(cyl, gear, "row")

# This allows for upstream operations
# prior to the crosstab() call:
mtcars %>%
  filter(am == 0) %>%
  crosstab(cyl, gear)