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 var3).

weight

A numeric vector of weights. If NULL, equal weights are assumed.

percent

How percentages should be computed: "none" (default), "row", "column", or "total".

na.rm

Logical. If TRUE, removes observations with missing values on any input variable.

drop.missing.levels

Logical. If TRUE, drops unused factor levels in var1, var2, and var3.

mean1

Logical. If TRUE, normalizes the weights to have a mean of 1.

digits

Number of digits to which percentages should be rounded (only used if percent != "none").

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:

If var3 is specified, returns a named list where each element corresponds to a level of var3 and contains:

Author(s)

Josh Pasek

See Also

wtd.chi.sq, xtabs, wtd.table

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")

[Package weights version 1.1.2 Index]