xtabs: Cross tabulation

Description Usage Arguments Value See Also Examples

Description

xtabs creates a contingency table (optionally a sparse matrix) from cross-classifying factors, usually contained in a data-frame-like object, using a formula interface.

NOTE: This man page is for the xtabs S4 generic function defined in the BiocGenerics package. See ?stats::xtabs for the default method (defined in the stats package). Bioconductor packages can define specific methods for objects not supported by the default method.

Usage

1
2
3
xtabs(formula=~., data=parent.frame(), subset, sparse=FALSE, 
      na.action, addNA=FALSE, exclude=if(!addNA)c(NA, NaN),
      drop.unused.levels=FALSE)

Arguments

formula, subset, sparse, na.action, addNA, exclude, drop.unused.levels

See ?stats::xtabs for a description of these arguments.

data

A data-frame-like object.

Value

See ?stats::xtabs for the value returned by the default method.

Specific methods defined in Bioconductor packages should also return the type of object returned by the default method.

See Also

Examples

1
2
3
4
5
6
7
8
xtabs  # note the dispatch on the 'data' arg only
showMethods("xtabs")
selectMethod("xtabs", "ANY")  # the default method

library(S4Vectors)
showMethods("xtabs")
## The xtabs() method for DataFrame objects:
selectMethod("xtabs", "DataFrame")

Example output

Loading required package: parallel

Attaching package:BiocGenericsThe following objects are masked frompackage:parallel:

    clusterApply, clusterApplyLB, clusterCall, clusterEvalQ,
    clusterExport, clusterMap, parApply, parCapply, parLapply,
    parLapplyLB, parRapply, parSapply, parSapplyLB

The following objects are masked frompackage:stats:

    IQR, mad, sd, var, xtabs

The following objects are masked frompackage:base:

    anyDuplicated, append, as.data.frame, basename, cbind, colnames,
    dirname, do.call, duplicated, eval, evalq, Filter, Find, get, grep,
    grepl, intersect, is.unsorted, lapply, Map, mapply, match, mget,
    order, paste, pmax, pmax.int, pmin, pmin.int, Position, rank,
    rbind, Reduce, rownames, sapply, setdiff, sort, table, tapply,
    union, unique, unsplit, which.max, which.min

standardGeneric for "xtabs" defined from package "BiocGenerics"

function (formula = ~., data = parent.frame(), subset, sparse = FALSE, 
    na.action, addNA = FALSE, exclude = if (!addNA) c(NA, NaN), 
    drop.unused.levels = FALSE) 
standardGeneric("xtabs")
<bytecode: 0x562195e25048>
<environment: 0x5621946297c8>
Methods may be defined for arguments: data
Use  showMethods("xtabs")  for currently available ones.
Function: xtabs (package BiocGenerics)
formula="ANY"

Method Definition (Class "derivedDefaultMethod"):

function (formula = ~., data = parent.frame(), subset, sparse = FALSE, 
    na.action, addNA = FALSE, exclude = if (!addNA) c(NA, NaN), 
    drop.unused.levels = FALSE) 
{
    if (missing(formula) && missing(data)) 
        stop("must supply either 'formula' or 'data'")
    if (!missing(formula)) {
        formula <- as.formula(formula)
        if (!inherits(formula, "formula")) 
            stop("'formula' missing or incorrect")
    }
    if (any(attr(terms(formula, data = data), "order") > 1)) 
        stop("interactions are not allowed")
    m <- match.call(expand.dots = FALSE)
    if (is.matrix(eval(m$data, parent.frame()))) 
        m$data <- as.data.frame(data)
    m$... <- m$exclude <- m$drop.unused.levels <- m$sparse <- m$addNA <- NULL
    if (addNA && missing(na.action)) 
        m$na.action <- quote(na.pass)
    m[[1L]] <- quote(stats::model.frame)
    mf <- eval(m, parent.frame())
    if (length(formula) == 2L) {
        by <- mf
        y <- NULL
    }
    else {
        i <- attr(attr(mf, "terms"), "response")
        by <- mf[-i]
        y <- mf[[i]]
    }
    has.exclude <- !missing(exclude)
    by <- lapply(by, function(u) {
        if (!is.factor(u)) 
            u <- factor(u, exclude = exclude)
        else if (has.exclude) 
            u <- factor(as.character(u), levels = setdiff(levels(u), 
                exclude), exclude = NULL)
        if (addNA) 
            u <- addNA(u, ifany = TRUE)
        u[, drop = drop.unused.levels]
    })
    naAct <- if (!is.null(m$na.action)) 
        m$na.action
    else getOption("na.action", default = quote(na.omit))
    na.rm <- identical(naAct, quote(na.omit)) || identical(naAct, 
        na.omit) || identical(naAct, "na.omit")
    if (!sparse) {
        x <- if (is.null(y)) 
            table(by, dnn = names(by))
        else if (NCOL(y) == 1L) 
            tapply(y, by, sum, na.rm = na.rm, default = 0L)
        else {
            z <- lapply(as.data.frame(y), tapply, by, sum, na.rm = na.rm, 
                default = 0L)
            array(unlist(z), dim = c(dim(z[[1L]]), length(z)), 
                dimnames = c(dimnames(z[[1L]]), list(names(z))))
        }
        class(x) <- c("xtabs", "table")
        attr(x, "call") <- match.call()
        x
    }
    else {
        if (length(by) != 2L) 
            stop(gettextf("%s applies only to two-way tables", 
                "xtabs(*, sparse=TRUE)"), domain = NA)
        if (is.null(tryCatch(loadNamespace("Matrix"), error = function(e) NULL))) 
            stop(gettextf("%s needs package 'Matrix' correctly installed", 
                "xtabs(*, sparse=TRUE)"), domain = NA)
        if (length(i.ex <- unique(unlist(lapply(by, function(f) which(is.na(f))))))) {
            by <- lapply(by, `[`, -i.ex)
            if (!is.null(y)) 
                y <- y[-i.ex]
        }
        if (na.rm && !is.null(y) && any(isN <- is.na(y))) {
            ok <- !isN
            by <- lapply(by, `[`, ok)
            y <- y[ok]
        }
        rows <- by[[1L]]
        cols <- by[[2L]]
        dnms <- lapply(by, levels)
        x <- if (is.null(y)) 
            rep.int(1, length(rows))
        else as.double(y)
        methods::as(methods::new("dgTMatrix", x = x, Dimnames = dnms, 
            i = as.integer(rows) - 1L, j = as.integer(cols) - 
                1L, Dim = lengths(dnms, use.names = FALSE)), 
            "CsparseMatrix")
    }
}
<bytecode: 0x562195e787d0>
<environment: namespace:stats>

Signatures:
        formula
target  "ANY"  
defined "ANY"  
Loading required package: stats4

Attaching package:S4VectorsThe following object is masked frompackage:base:

    expand.grid

Function: xtabs (package BiocGenerics)
formula="ANY"
data="DataFrame"
data="Vector"

Method Definition:

function (formula = ~., data = parent.frame(), subset, sparse = FALSE, 
    na.action, addNA = FALSE, exclude = c(NA, NaN), drop.unused.levels = FALSE) 
{
    .local <- function (formula = ~., data, subset, na.action, 
        exclude = c(NA, NaN), drop.unused.levels = FALSE) 
    {
        data <- as(data, "data.frame")
        callGeneric()
    }
    .local(formula, data, subset, na.action, exclude, drop.unused.levels)
}
<bytecode: 0x562194e562e8>
<environment: namespace:S4Vectors>

Signatures:
        data       
target  "DataFrame"
defined "DataFrame"

BiocGenerics documentation built on April 17, 2021, 6:01 p.m.