Skip to content

The crosstab function generates crosstabs (contingency tables) from survey data, allowing for a variety of formatting and analytical options. It can produce tables with statistical measures, create visual plots, and handle weighted data.

Usage

crosstab(
  data,
  rowVar,
  colVar,
  weight = NULL,
  totals = TRUE,
  round_decimals = NULL,
  statistics = FALSE,
  plot = FALSE,
  format = c("df_long", "df_wide", "csv", "statistics"),
  convert_to = c("percent", "frequency"),
  yLab = "Population (%)",
  adjustX = FALSE
)

Arguments

data

A data frame containing survey data. This parameter is required.

rowVar

The independent variable represented in rows (side of the table).

colVar

The dependent variable represented in columns (top of the table).

weight

An optional variable containing weight factors for the analysis.

totals

Logical; if TRUE, includes a totals column in the output (default is TRUE).

round_decimals

Optional; number of decimal points for rounding the data (default is NULL).

statistics

Logical; if TRUE, calculates and prints Chi-Square, degrees of freedom (DF), Cramer's V, and p-value (default is FALSE).

plot

Logical; if TRUE, generates a plot for visual representation of the crosstab data (default is FALSE).

format

Specifies the output format: 'df_long', 'df_wide', 'csv', or 'statistics' (default is 'df_long').

convert_to

Determines conversion type: 'percent' or 'frequency' (default is 'percent').

yLab

Title for the Y-axis, default is "Population (%)".

adjustX

Logical; if TRUE, adjusts the X-axis labels to a 45-degree angle for better readability (default is FALSE).

Value

Depending on the chosen format, returns a data frame in either long or wide format, containing row-wise percentages and column-wise totals. If plot is TRUE, a plot object is also generated.

Examples

if (FALSE) { # \dontrun{
  # Example: Create crosstabs with a long data frame output using weighted data
  crosstab_result <- crosstab(data = dataset,
                              rowVar = "Q1",
                              colVar = "Gender",
                              weight = "wgtvar",
                              totals = FALSE,
                              round_decimals = 2)
} # }