Skip to main content
v2026.11,986 entries · CC-BY 4.0

model.matrix in R: Build a Design Matrix from a Formula

Use model.matrix in R to build a design matrix from a formula: step-by-step syntax, contrasts, output reading and fixes for common errors.

Written and maintained by CASRAI Editorial Board

Published

On this page

model.matrix in R turns a model formula and a data frame into the design matrix that regression functions such as lm() use internally: one row per observation, one column per coefficient, with factors expanded into numeric indicator columns according to their contrasts. Call it directly with model.matrix(~ x1 + group, data = df) when you need to see, check or reuse that matrix. The same call works for the “model.matrix r” searches that land here, because the function lives in the stats package that ships with R.

Everything below is based on the R documentation pages for model.matrix, contrasts, formula, model.frame and options, read on 2026-11-18. The small outputs shown are derived from the documented coding rules, not pasted from a particular R version.

What model.matrix is used for in research

A model matrix (also called a design matrix) is the table of numbers that a linear model really sees. Your data frame may hold a treatment arm as text and a baseline measurement as a number; the model only works with numbers, so each factor level has to be translated into a column. R’s documentation describes model.matrix as creating a design matrix from a formula and data, and its result carries two attributes that record how that translation was done: an assign attribute (one integer per column, where 0 marks the intercept) and, when factors are present, a contrasts attribute.

Researchers reach for it in four situations:

  • Checking coding before interpreting coefficients. Which factor level is the reference, and what does each indicator column mean? A coefficient named doselow is the low-dose group compared with the reference level, and you can only be sure of that after looking at the matrix. The indicator variable regression guide covers how to interpret and report those coefficients.
  • Feeding matrix-based algorithms. Functions that take a numeric matrix rather than a formula (penalised regression, custom optimisation, simulation) need an explicit design matrix, for example when you move from lm() to regression modelling in R with other packages.
  • Diagnosing rank problems. Perfectly collinear columns show up immediately in a model matrix; see perfect multicollinearity for what that means for estimates.
  • Building interaction terms transparently. The columns for a:b are visible, so you can confirm that a moderation model contains what you think it does (moderation analysis with interaction terms).

When you fit a model with lm(), aov() or glm(), the model matrix is created from your formula and data automatically. Calling model.matrix yourself changes nothing about the fit; it only exposes the step.

How to install or access model.matrix

model.matrix is part of the stats package, so there is nothing separate to install: download and install R itself from the Comprehensive R Archive Network (CRAN) at cran.r-project.org, then open an R console or RStudio session. To read the documentation for the version you have installed, run:

?model.matrix?contrasts?formula

The method for fitted models is also available: model.matrix(fit) on an lm object returns the matrix used in that fit. The default method has this signature in the current R-devel documentation:

model.matrix(object, data = environment(object),             contrasts.arg = NULL, xlev = NULL, ...)

How to build a design matrix with model.matrix step by step

Step 1: Prepare the data frame

  1. Put each variable in its own column. Right-hand-side variables must be logical, integer, numeric or factor according to the documentation; character columns are converted to factors.
  2. Declare factors deliberately. The first level of a factor is its reference level under the default coding, so set the order yourself with factor(x, levels = c("control", "low", "high")) instead of leaving it to alphabetical order.
  3. Decide what to do with missing values before you build the matrix (see the troubleshooting section).

Step 2: Write the formula

The formula has no response variable when you call model.matrix directly: ~ dose + age. The operators come from the formula documentation:

Formula piece What it does
a + b Joins terms
a:b Interaction between a and b
a*b Shorthand for a + b + a:b
(a+b+c)^2 Main effects plus all second-order interactions
- term Removes a term
~ x - 1, ~ x + 0, ~ 0 + x Remove the intercept
I(x^2) Evaluates arithmetic inside a formula as written

Step 3: Build the matrix

Here is a small, made-up trial extract with a three-level dose factor and a numeric covariate:

trial <- data.frame(  dose = factor(c("control","low","high","control","low","high"),                levels = c("control","low","high")),  age  = c(34, 41, 29, 52, 47, 38))X <- model.matrix(~ dose + age, data = trial)X

Under the default coding the result is:

  (Intercept) doselow dosehigh age1           1       0        0  342           1       1        0  413           1       0        1  294           1       0        0  525           1       1        0  476           1       0        1  38attr(,"assign")[1] 0 1 1 2attr(,"contrasts")attr(,"contrasts")$dose[1] "contr.treatment"

The dose factor has three levels and contributes two columns, because the contrasts documentation states that the default number of contrasts is the number of levels minus one. The control group is the reference: its rows have zeros in both dose columns.

Step 4: Change the coding with contrasts.arg

The documentation says contrasts.arg “overrides the default factor coding for that variable”. It takes a list named by factor, whose entries are contrast matrices, functions or function names. Using the example from the documentation, a data frame with two factors:

dd <- data.frame(a = gl(3, 4), b = gl(4, 1, 12))model.matrix(~ a + b, dd)model.matrix(~ a + b, dd, contrasts.arg = list(a = "contr.sum"))m.orth <- model.matrix(~ a + b, dd,                       contrasts.arg = list(a = "contr.helmert"))crossprod(m.orth)   # almost orthogonal

The first call gives treatment coding for both factors: an intercept, two columns for a and three for b, six columns in all. The second recodes a with sum-to-zero contrasts; the third uses Helmert contrasts, and the documentation notes that the cross-product of that matrix is “almost orthogonal”. Related functions named on the contrasts page are contr.treatment, contr.sum, contr.helmert and contr.poly. To change the coding for a factor everywhere, assign contrasts to it with contrasts(x) <- value; contrasts(x, contrasts = FALSE) returns the identity matrix, one column per level.

Step 5: Drop the intercept when you want one column per level

With ~ 0 + dose (or ~ dose - 1) the intercept column disappears and the first factor is coded with an indicator column for every level. This is a common way to get group means as coefficients, but it only makes sense when the model does not also need a shared baseline.

Step 6: Use the matrix

Pass X to a function that takes a matrix, for example solve(crossprod(X), crossprod(X, y)) for least squares on a response vector y. For matrix operations in R more generally, see the guide on matrix multiplication in R. For the conceptual background to the formula you wrote, linear and multiple regression explains what each coefficient represents.

How to read the output

Columns

Each column is one numeric predictor. The first column is (Intercept), a column of ones, whenever the model has an intercept. Factor columns are named from the variable name and the level it indicates, and numeric variables keep their own names. These names are what appear as coefficient names after lm() fits the same formula.

The assign attribute

The assign attribute maps every column to the term it came from. In the example above, 0 1 1 2 means: the intercept (0), two columns from the first term dose (1, 1) and one column from the second term age (2). This is how functions such as anova() know which columns to test together.

The contrasts attribute

Present when factors are in the model, it records the coding used for each factor. Seeing "contr.treatment" tells you the coefficients are comparisons with the reference level. The contrasts option for unordered and ordered factors is a character vector of length two, set with options(contrasts = c(...)); the options page does not give the factory values, so check getOption("contrasts") in your own session before assuming them.

Interaction column order

For interactions, the documentation states that “the variable whose levels vary fastest is the first one to appear in the formula”. That determines the order of columns for a:b, which matters when you index columns by position.

Troubleshooting model.matrix

Rows disappear

Rows with missing values in any variable used by the formula are not in the matrix, so the matrix can have fewer rows than the data frame. The model.frame documentation lists the order of precedence for na.action: first any na.action attribute of the data, then an na.action setting in options, then na.fail, and describes the factory-fresh default as na.omit. If you need row alignment with the original data, build the model frame first and inspect which rows were dropped.

Warning about a response on the right-hand side

If you pass a two-sided formula like y ~ x to model.matrix, the response is dropped with a warning in the situations the documentation describes. Use a one-sided formula, ~ x, to avoid it.

Warning about contrasts.arg

Invalid values in contrasts.arg are ignored, and since R 3.6.0 this produces a warning. If your recoding seems to have no effect, check that the list is named exactly by the factor’s column name and that each entry is a matrix, function or function name.

Error about factors with fewer than two levels

A factor with a single level cannot be coded into contrasts, because the number of contrasts is the number of levels minus one. R stops with an error saying that contrasts can be applied only to factors with two or more levels. This often happens after filtering a data frame so that one level has no rows left; apply droplevels() and check the subset, or drop the variable from the formula.

Predicting for new data gives different columns

Matrices built separately for training and new data can have different columns if a level is missing from one of them. The xlev argument, passed on to model.frame, is “a named list of character vectors giving the full set of levels to be assumed for each factor”, which keeps the columns aligned. Per the documentation, if xlev names a factor and a character variable is found, the variable is converted to a factor.

Coefficients cannot be estimated

If you remove the intercept but leave a full set of indicator columns for a second factor, or add a hand-built indicator for every level alongside an intercept, the columns become linearly dependent. Fitting then returns NA coefficients for the redundant terms. The fix is to drop one column or one term; the same logic is described for the Stata equivalent in creating dummy variables in Stata.

Free alternatives to model.matrix

model.matrix is free like the rest of R. If you need something different from the dense matrix it returns, these alternatives are also freely available. The table below lists what the documentation says about each.

Alternative What it gives you Where documented
model.matrix(fit) on a fitted model The matrix used in an existing lm, glm or aov fit, rather than rebuilding it from the formula R stats documentation, model.matrix usage
Matrix::sparse.model.matrix A sparse version of the design matrix for models with many factor levels Matrix and MatrixModels package documentation
MatrixModels::model.Matrix A wrapper that returns either a dense model matrix (sparse = FALSE) or a sparse one (sparse = TRUE) MatrixModels package documentation
contrasts() with contr.* functions The coding matrix for a single factor, without building the whole design matrix R stats documentation, contrasts

The data table below summarises how many columns the formulas used in this guide produce on the documentation’s example data frame, derived from the documented coding rules.

Sources

Data: Columns produced by model.matrix formulas on the R documentation example data frame

Number of design-matrix columns for formulas applied to the data frame dd (a = gl(3,4), b = gl(4,1,12)) from the R model.matrix help page, derived from the documented rules: levels minus one contrasts per factor under default coding, plus an intercept, interactions as products of main-effect columns, and the intercept removed by 0 or -1.

Columns produced by model.matrix formulas on the R documentation example data frame
FormulaNumber of columns (columns)Basis
~ a3Intercept plus 2 contrasts for a (3 levels)
~ a + b6Intercept plus 2 for a plus 3 for b
~ a * b12a + b + a:b: 1 + 2 + 3 + 6 interaction columns
~ 0 + a3Intercept removed with 0, a coded with one column per level

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about model.matrix in R: Build a Design Matrix from a Formula

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →