This function performs a cross-tabulation between two categorical variables and conducts Fisher's exact test, returning a formatted table with counts, proportions, and p-values.

compare_categorical(
  dat,
  col_var,
  row_var,
  varname = "",
  total = FALSE,
  colname = "Variables"
)

Arguments

dat

A data frame containing the variables.

col_var

The grouping variable (categorical or factor) to classify the data into two or more groups.

row_var

The categorical variable to compare against col_var.

varname

Optional. A character string to label the row_var row in the output table (default is an empty string).

total

Logical; if TRUE, includes an overall total in the table.

colname

Optional. The name of the first column in the output table (default is 'Variables').

Value

A data frame with the cross-tabulation results, including counts, proportions, and the p-value from Fisher's exact test.

Details

This function creates a contingency table for col_var and row_var using xtabs, adds row margins if requested, computes proportions, and performs Fisher's exact test to assess the association between the two variables. The output is a formatted table with counts, proportions, and the test's p-value.

Examples

compare_categorical(mtcars, 'cyl', 'gear', varname = 'Gear')
#>     Variables         4         6          8 p-value
#> 1 Gear, n (%)      <NA>      <NA>       <NA>  <0.001
#> 2           3  1 (9.1%) 2 (28.6%) 12 (85.7%)    <NA>
#> 3           4 8 (72.7%) 4 (57.1%)     0 (0%)    <NA>
#> 4           5 2 (18.2%) 1 (14.3%)  2 (14.3%)    <NA>