Generate cross tabulations with optional percentages and totals
Source:R/dta_crosstab.R
dta_crosstab.Rd
dta_crosstab()
creates a cross-tabulation (contingency table) for
a given dataset, with options to include counts, row percentages, or column
percentages. Totals can also be added to rows, columns, or both. The output
is styled using the janitor
package.
Arguments
- dat
A data frame (not a tibble) containing the variables to tabulate.
- .row
The variable to be used as rows in the crosstab.
- .column
The variable to be used as columns in the crosstab.
- cells
A character string indicating the type of values to display in the crosstab:
"counts"
Display counts (default).
"row"
Display row percentages.
"col"
Display column percentages.
- add_totals
A character string specifying where to add totals:
"both"
Add totals to both rows and columns (default).
"row"
Add totals to rows only.
"col"
Add totals to columns only.
- name
A character string to rename the first column in the output. Default is
"Variable"
.- add_percent_symbol
Logical indicating whether or not to add a % sign to percentages. Default is
TRUE
.- digits
An integer specifying the number of decimal places to use for percentages. Default is 1.
Value
A data frame representing the cross-tabulation, styled using
janitor
functions.
The format of the output depends on the cells
argument:
- Counts
Displays raw counts.
- Percentages
Displays percentages with counts in parentheses if
cells
is"row"
or"col"
.
Examples
data("data_sample")
df <- data_sample
# Crosstabulation of frequencies (counts)
result <- dta_crosstab(
dat = df, .row = region, .column = age_group
)
dta_gtable(result)
# Calculate column percentages
result2 <- dta_crosstab(
dat = df,
.row = region,
.column = age_group,
cells = "col",
add_totals = "col"
)
dta_gtable(result2)
# Calculate row percentages
result3 <- dta_crosstab(
dat = df,
.row = region,
.column = age_group,
cells = "row",
add_totals = "row"
)
dta_gtable(result3)
# Remove the percentages symbol
result4 <- dta_crosstab(
dat = df,
.row = region,
.column = age_group,
cells = "row",
add_totals = "row",
add_percent_symbol = FALSE
)
dta_gtable(result4)