Learn R Programming

janitor (version 0.3.0)

crosstab: Generate a crosstabulation of two vectors.

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

crosstab(...)

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

# S3 method for 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

Run this code
# NOT RUN {
# 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:
mtcars %>% crosstab(cyl, gear)
mtcars %>% crosstab(cyl, gear, "row")

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

Run the code above in your browser using DataLab