Skip to content

Create a contingency table of counts generated by cross-classifying factors from groups splitting on the values passed in the ... argument. The sums of each row and column are added to the result.

Usage

cross_tab(x, ..., useNA = "ifany")

Arguments

x

A data.frame (-like) object containing the data variables from which counts are desired.

...

A number of un-quoted expressions or quoted strings separated by commas. Generally greater than 3 is not useful.

useNA

See table().

Value

A table of grouped counts based on splitting variables with sums from each factor.

See also

Author

Stu Field

Examples

# 1 factor
cross_tab(mtcars, cyl)
#> cyl
#>   4   6   8 Sum 
#>  11   7  14  32 

# quoted string
cross_tab(mtcars, "cyl")
#> cyl
#>   4   6   8 Sum 
#>  11   7  14  32 

# with external variable
var <- "cyl"
cross_tab(mtcars, var)
#> cyl
#>   4   6   8 Sum 
#>  11   7  14  32 

# 2 factors
cross_tab(mtcars, cyl, gear)
#>      gear
#> cyl    3  4  5 Sum
#>   4    1  8  2  11
#>   6    2  4  1   7
#>   8   12  0  2  14
#>   Sum 15 12  5  32

cross_tab(mtcars, "cyl", "gear")
#>      gear
#> cyl    3  4  5 Sum
#>   4    1  8  2  11
#>   6    2  4  1   7
#>   8   12  0  2  14
#>   Sum 15 12  5  32

cross_tab(mtcars, c("cyl", "gear"))
#>      gear
#> cyl    3  4  5 Sum
#>   4    1  8  2  11
#>   6    2  4  1   7
#>   8   12  0  2  14
#>   Sum 15 12  5  32

# 3 factors
cross_tab(mtcars, cyl, gear, am)
#> , , am = 0
#> 
#>      gear
#> cyl    3  4  5 Sum
#>   4    1  2  0   3
#>   6    2  2  0   4
#>   8   12  0  0  12
#>   Sum 15  4  0  19
#> 
#> , , am = 1
#> 
#>      gear
#> cyl    3  4  5 Sum
#>   4    0  6  2   8
#>   6    0  2  1   3
#>   8    0  0  2   2
#>   Sum  0  8  5  13
#> 
#> , , am = Sum
#> 
#>      gear
#> cyl    3  4  5 Sum
#>   4    1  8  2  11
#>   6    2  4  1   7
#>   8   12  0  2  14
#>   Sum 15 12  5  32
#>