wtd.xtab {weights} | R Documentation |
Weighted cross-tabulations using up to three categorical variables
Description
wtd.xtab
creates 2-way or 3-way weighted cross-tabulations. It uses weighted counts and optionally returns row, column, or total percentages. The function outputs either a matrix or a list of matrices for easier interpretation than base R's default array structure.
Usage
wtd.xtab(var1, var2, var3 = NULL,
weight = NULL,
percent = c("none", "row", "column", "total"),
na.rm = TRUE,
drop.missing.levels = TRUE,
mean1 = TRUE,
digits = 1)
Arguments
var1 |
A categorical variable to appear as rows in the table. |
var2 |
A categorical variable to appear as columns in the table. |
var3 |
An optional third categorical variable used to split the table (i.e., one table per level of |
weight |
A numeric vector of weights. If |
percent |
How percentages should be computed: |
na.rm |
Logical. If |
drop.missing.levels |
Logical. If |
mean1 |
Logical. If |
digits |
Number of digits to which percentages should be rounded (only used if |
Details
This function provides a cleaner and more interpretable alternative to xtabs
when working with weights and categorical variables. It simplifies 2-way and 3-way tabulations and avoids confusing multi-dimensional array output.
Value
If var3
is NULL
, returns a list with:
counts
— A matrix of weighted countspercent
— A matrix of percentages (orNULL
ifpercent = "none"
)
If var3
is specified, returns a named list where each element corresponds to a level of var3
and contains:
counts
— A matrix of weighted countspercent
— A matrix of percentages (orNULL
)
Author(s)
Josh Pasek
See Also
Examples
data(mtcars)
mtcars$cyl <- factor(mtcars$cyl)
mtcars$am <- factor(mtcars$am)
mtcars$gear <- factor(mtcars$gear)
mtcars$wt_cat <- cut(mtcars$wt, 3)
# Two-way table
wtd.xtab(mtcars$cyl, mtcars$am)
# With row percentages
wtd.xtab(mtcars$cyl, mtcars$am, weight = mtcars$wt, percent = "row")
# Three-way table, split by gear
wtd.xtab(mtcars$cyl, mtcars$am, mtcars$gear, weight = mtcars$wt)
# Column percentages by weight class
wtd.xtab(mtcars$cyl, mtcars$am, mtcars$wt_cat, weight = mtcars$wt, percent = "column")