make_table: More consistent version of base::table()

View source: R/make_table.R

make_tableR Documentation

More consistent version of base::table()

Description

Takes a data frame and the columns specified and creates a table object that is clean and easy to use for the rest of the calculations. It helps to resolve some issues with the base R table function that doesn't handle empty cells very well IMHO.

Usage

make_table(data, x, y,
           x_lvls = NULL, y_lvls = NULL,
           labs = c(NA, NA),
           type = "unique", sorted = FALSE, useNA = "ifany")

Arguments

data

A data frame or tibble

x

"X" variable; counts appear in the rows of the table

y

"Y" variable; counts appear in the columns of the table

x_lvls

(optional) levels for the X variable

y_lvls

(optional) levels for the Y variable

labs

(optional) labels for the X and Y variables

type

Character; To use the values of the variables that exist in the data use "unique" (default). To use the values attributed to the variables as a factor then choose "levels" which may not actually exist in the data as actual values.

sorted

Logical; If FALSE (default) then the values for the table appear just as they are in the data or as they are defined as a factor. If TRUE, then the factor order is overrided and the variables are sorted.

useNA

useNA controls if the table includes counts of NA values: the allowed values correspond to never ("no"), only if the count is positive ("ifany") and even for zero counts ("always")

Value

A table

Examples

df <- tibble::tribble(
  ~a, ~b, ~c,
  1L, 1L, 1L,
  0L, 1L, 1L,
  1L, 1L, 0L,
  0L, 1L, 0L,
  1L, 1L, 1L,
  0L, 1L, 1L,
  1L, 1L, 0L
)

table(df$a, df$b)

make_table(data = df, x = a, y = b)

make_table(data = df, x = a, y = b, labs = c("Cats", "Dogs"))

make_table(data = df,
           x = a,
           y = b,
           x_lvls = c(1, 0),
           y_lvls = c(1, 0),
           type = "levels")

make_table(data = df,
           x = a,
           y = b,
           x_lvls = c(0, 1),
           y_lvls = c(0, 1),
           type = "levels")


make_table(data = df,
           x = a,
           y = b,
           x_lvls = c(1, 0),
           y_lvls = c(1, 0),
           type = "unique",
           sorted = TRUE)


make_table(data = df,
           x = a,
           y = b,
           x_lvls = c(1),
           y_lvls = c(1),
           type = "unique",
           sorted = TRUE)

emilelatour/lamisc documentation built on April 9, 2024, 10:33 a.m.