model.Matrix: Construct Possibly Sparse Design or Model Matrices

View source: R/modelMatrix.R

model.MatrixR Documentation

Construct Possibly Sparse Design or Model Matrices

Description

model.Matrix creates design matrix, very much like the standard R function model.matrix, however returning a dense or sparse object of class modelMatrix.

Usage

model.Matrix(object, data = environment(object),
             contrasts.arg = NULL, xlev = NULL,
             sparse = FALSE, drop.unused.levels = FALSE, ...)

Arguments

object

an object of an appropriate class. For the default method, a model formula or a terms object.

data

a data frame created with model.frame. If another sort of object, model.frame is called first.

contrasts.arg

A list, whose entries are values (numeric matrices or character strings naming functions) to be used as replacement values for the contrasts replacement function and whose names are the names of columns of data containing factors.

xlev

to be used as argument of model.frame if data has no "terms" attribute.

sparse

logical indicating if the result should be sparse (of class sparseModelMatrix), using sparse.model.matrix() (package Matrix).

drop.unused.levels

used only when sparse is TRUE: Should factors have unused levels dropped? (This used to be true, implicitly in the first versions up to July 2010; the default has been changed for compatibility with R's standard (dense) model.matrix().

...

further arguments passed to or from other methods.

Details

model.Matrix() is a simple wrapper either (sparse = FALSE) around the traditional model.matrix() returning a "ddenseModelMatrix", or (sparse = TRUE) around sparse.model.matrix(), returning a "dsparseModelMatrix" object.

model.Matrix creates a design matrix from the description given in terms(object), using the data in data which must supply variables with the same names as would be created by a call to model.frame(object) or, more precisely, by evaluating attr(terms(object), "variables").

For more details, see model.matrix.

Value

an object inheriting from class modelMatrix, by default, ddenseModelMatrix.

See Also

model.matrix, sparse.model.matrix.

Examples

data(CO2, package="datasets")
class(sm <- model.Matrix(~ 0+Type*Treatment, data=CO2, sparse=TRUE))
class(dm <- model.Matrix(~ 0+Type*Treatment, data=CO2, sparse=FALSE))
stopifnot(dim(sm) == c(84,4), dim(sm) == dim(dm), all(sm == dm))

MatrixModels documentation built on Nov. 6, 2023, 5:09 p.m.