expand_freq_table: Expand a contingency table (as array/table or data frame) to...

View source: R/array_fun.R

expand_freq_tableR Documentation

Expand a contingency table (as array/table or data frame) to raw cases (as data frame).

Description

expand_freq_table turns a contingency table (given as an array/table or as a data frame with a frequency count variable freq_var that denotes the number of cases for each factor combination) into a data frame of raw cases.

Usage

expand_freq_table(x, freq_var = "Freq", row_name_repair = TRUE)

Arguments

x

An contingency table (as table or data.frame).

freq_var

The name of the frequency count variable in a data frame x (aka. responseName in as.data.frame). Default: freq_var = "Freq", based on default of as.data.frame(x, responseName = "Freq") for arrays/tables.

row_name_repair

Boolean: Should rows be repaired (i.e., enumerated)? Default: row_name_repair = TRUE.

Details

expand_freq_table assumes that x is a table or a data.frame with a frequency count variable freq_var.

If x is a table, expand_freq_table first uses as.data.frame (with responseName = freq_var) to turn x into a contingency table (as a data frame with a frequency variable, named "Freq" by default).

The function allows turning a contingency table (i.e., a table that cross-classifies frequency counts) — in the form of a table or a data.frame with a frequency count variable freq_var — into a corresponding data.frame of raw cases. The number of cases or observations (rows) in the resulting data frame corresponds to sum(x) (for tables) or sum(x$freq_var) (for data frames).

Value

A data frame (of raw cases).

See Also

table and xtabs for turning data frames into contingency tables; as.data.frame for turning an array/table into a contingency table (as df).

Other array functions: add_dimnames(), ctable(), flatten_array(), subtable()

Examples

# (a) from raw data (vectors):
ans <- sample(c("yes", "no", "maybe"), 100, replace = TRUE)
eat <- sample(c("fish", "meat", "veggie"), 100, replace = TRUE)
df_1 <- data.frame(ans, eat)  # data frame from vectors
df_2 <- expand_freq_table(data.frame(table(ans, eat))) # table > contingency table > df
all.equal(table(df_1), table(df_2))

# (b) from a table (3D table > contingency table > data frame > 3D array):
df <- expand_freq_table(UCBAdmissions)  # array/table > contingency table > df
tb <- table(df)                         # df > array/table 
all.equal(UCBAdmissions, tb)

# Trivial case:
expand_freq_table(data.frame(x = "a", Freq = 2))

# Full circle (4D array > contingency table > data frame > 4D array): 
df <- expand_freq_table(Titanic)
tb <- table(df)
all.equal(Titanic, tb)


hneth/i2ds documentation built on Jan. 25, 2024, 2:22 p.m.