xtable: Cross table

View source: R/utils.R

xtableR Documentation

Cross table

Description

Create a contingency table with totals, percentages, and statistical test.

Usage

xtable(
  x,
  by,
  digits = 0L,
  total = TRUE,
  pct.sign = FALSE,
  test = TRUE,
  label.test = NULL,
  html = FALSE,
  ...
)

Arguments

x, by

row and column variables, respectively; should be factor-like and will be coerced; missing values in by will be removed with the corresponding values in x

digits

for percentages, number of digits past the decimal to keep

total

logical; if TRUE, the row totals will be added as a separate column

pct.sign

logical; if FALSE (default), no percentage signs will be shown

test

logical; if TRUE, a test and p-value will be added as a separate column; see rawr:::guess_test

alternatively, a user-defined test function which takes two arguments, x and by, and returns a numeric p-value with an optional attribute, "name", which will be used as a test label; the function may return a string instead in which case the string will be used literally; see examples

label.test

optional label for the test column

html

logical; if TRUE uses HTML entities for < and >; see pvalr

...

additional arguments passed to getDescriptionStatsBy

See Also

getDescriptionStatsBy; tabler_stat2; rawr:::guess_test

Examples

x <- mtcars$gear
y <- mtcars$cyl
z <- mtcars$vs

table(x, y)
xtable(x, y)

xtable(ordered(x), z)
xtable(ordered(x), y)
xtable(ordered(x), ordered(y))


## user-defined test functions
test <- function(x, by) {
  x <- fisher.test(table(x, by))
  sprintf('%.1f (%.1f, %.1f), %s', x$estimate, x$conf.int[1],
          x$conf.int[2], pvalr(x$p.value, show.p = TRUE))
}
xtable(mtcars$am, z, test = test, label.test = 'OR (95% CI), p-value')


test <- function(x, by) {
  structure(
    color_pval(chisq.test(table(x, by))$p.value),
    name = '<i>p-value</i>'
  )
}
res <- xtable(x, y, test = test)
res

names(dimnames(res)) <- c('Gears', 'Cylinders')
htmlTable::htmlTable(
  res, n.cgroup = c(1, 3, 1), cgroup = c('', 'Cylinders', '')
)


raredd/rawr documentation built on April 29, 2024, 10:29 a.m.