Every factor in a model becomes columns of 0s and 1s. Read that design matrix and coefficient tables, interactions and RNA-seq design formulas such as ~ cell + dex all make sense.
This lesson follows Correlation and linear regression, where lm() estimated the effect of smoking on birth weight with the mother's weight and recorded race held fixed.
How R turns a factor into numbers
A linear model is arithmetic: an intercept plus a coefficient times each predictor. That works for the mother's weight, which is a number. But "smoker" and "black" are words. Before fitting, R must turn every factor into numeric columns. The table of those columns, one row per observation, is the design matrix, and model.matrix() shows it to you. Once you can read a design matrix, every coefficient table makes sense, and so does the design formula of an RNA-seq analysis.
The code uses bw, the labelled birth weight data from Describing data. Start with recorded race, a factor with three levels.
fit_race <- lm(bwt ~ race, data = bw) coef(fit_race) tapply(bw$bwt, bw$race, mean) X <- model.matrix(~ race, data = bw) head(X, 4) head(bw$race, 4) colSums(X)
What this does
lm(bwt ~ race, data = bw)fits birth weight by recorded race alone, andcoef()prints just the coefficients.tapply(bw$bwt, bw$race, mean)calculates the mean birth weight in each group, for comparison.model.matrix(~ race, data = bw)builds the design matrix R used.head(X, 4)shows its first four rows, andhead(bw$race, 4)the race of those four babies.colSums(X)adds up each column.
Reading the output. The design matrix has three columns. (Intercept) is 1 for every baby. raceblack is 1 for babies of mothers recorded as black and 0 otherwise; raceother likewise. There is no column for white, the first level: a white mother's row is 1, 0, 0. Columns of 0s and 1s like these are called dummy variables (or indicator variables), and this scheme, where each level is compared with the first, is treatment coding, R's default. The column sums count the babies: 189 in all, 26 black and 67 other, so 96 white.
Now the coefficients have a plain meaning. For a white mother, the model predicts intercept × 1 = 3,102.7 g, which is exactly the white group's mean. For a black mother it predicts 3,102.7 − 383.0 = 2,719.7 g, the black group's mean. So the intercept is the mean of the reference level, and each other coefficient is the difference between that level's mean and the reference. contrasts(bw$race) prints the same 0/1 pattern as a small table, one row per level.
Choosing the reference
The comparisons you get depend on which level comes first, as Matrices, lists and factors showed. To compare with black instead, relevel. To get each group's own mean instead of differences, drop the intercept with 0 +:
bw$race_b <- relevel(bw$race, ref = "black") coef(lm(bwt ~ race_b, data = bw)) coef(lm(bwt ~ 0 + race, data = bw))
Reading the output. With black as the reference, the intercept is the black mean, 2,719.7 g, and "other" is 85.6 g heavier. That comparison was not in the first table, though you could have got it by subtraction: −297.4 − (−383.0) = 85.6. The fitted model is the same in all three versions; the predictions for every baby are identical. Only the way the group means are written as coefficients changes, and so does which comparisons get a standard error and p-value. Choose the reference that makes the comparisons you care about appear in the table.
A factor and a covariate
A covariate is a numeric predictor included alongside the groups, often to adjust for it. Adding the mother's weight, lwt, to smoking puts a numeric column next to a dummy column:
fit_add <- lm(bwt ~ lwt + smoke, data = bw) summary(fit_add)$coefficients head(model.matrix(fit_add), 4) head(model.matrix(fit_add) %*% coef(fit_add), 3) head(fitted(fit_add), 3)
What this does
summary(fit_add)$coefficientstakes just the coefficient table out of the summary, which is a list, as Matrices, lists and factors explained.model.matrix(fit_add)returns the design matrix of a fitted model.lwtenters as its own value; smoking as a 0/1 dummy.%*%multiplies the design matrix by the coefficients. For each baby, that adds up 1 × intercept + lwt × slope + dummy × smoking effect.fitted()returns the model's predictions directly.
Reading the output. Each extra pound of the mother's weight adds 4.2 g, and smokers' babies are 272 g lighter at the same maternal weight (p = 0.011). The matrix product gives exactly the fitted values: for baby 85, 2,501.1 + 182 × 4.237 + 0 = 3,272.2 g. That is all a linear model is: predictions = design matrix × coefficients, with the coefficients chosen by least squares. The smoking dummy shifts the whole line down by 272 g, so the model draws two parallel lines, one per group.
Adjustment can move an estimate in either direction. Alone, smoking was worth −284 g in Comparing two groups. Adjusted for weight it is −272 g. Adjusted for recorded race instead, lm(bwt ~ race + smoke) gives −428.7 g, because in these data smoking was much more common among mothers recorded as white (52 of 96) than among those recorded as other (12 of 67), and white mothers had heavier babies. A cross-table such as table(bw$race, bw$smoke) is the quickest way to see why a coefficient moved.
Interaction: when the lines need not be parallel
An interaction lets the effect of one predictor depend on another. lwt * smoke is shorthand for lwt + smoke + lwt:smoke, and lwt:smoke adds one more column to the design matrix: the mother's weight for smokers, and 0 for non-smokers.
fit_int <- lm(bwt ~ lwt * smoke, data = bw) summary(fit_int)$coefficients anova(fit_add, fit_int)
Reading the output. With an interaction, every coefficient changes meaning, and this is where most misreadings happen.
- lwt, 5.39, is now the slope for non-smokers only (the reference group).
- lwt:smokesmoker, −2.42, is how much the slope differs for smokers: 5.39 − 2.42 = 2.97 g per lb.
- smokesmoker, +41, is the smoking gap at lwt = 0, a mother weighing nothing. It is not "the smoking effect", and its huge standard error (451) reflects how far 0 lb is from the data.
anova() compares the two models. Allowing separate slopes reduced the unexplained variation only slightly, F = 0.51, p = 0.48: no evidence that the slopes differ, so the parallel-lines model is a fair description.
Worked example · making the interaction readable
at 130 lb: 41.4 − 314.8 = −273.4 g
centred model,
I(lwt - 130) * smoke: smoker coefficient −273.4 (95% CI −482.0 to −64.8)Step by step. The gap between the two lines at any weight is the smoking coefficient plus the interaction times the weight. At 130 lb, close to the mean of 129.8 lb: 130 × −2.4216 = −314.8, and 41.4 − 314.8 = −273.4 g. Refitting with weight centred at 130 lb, lm(bwt ~ I(lwt - 130) * smoke, data = bw), makes R report that number directly as the smokesmoker coefficient, with its confidence interval. The slopes (5.4 and −2.4) do not change.
What the answer means. In a model with an interaction, a "main effect" is the effect where the other variable is zero. Centre numeric covariates at a sensible value so that zero means something, and the main effects become readable again.
From birth weight to RNA-seq design formulas
Everything above carries straight over to RNA-seq. DESeq2, used in Differential expression with DESeq2, fits one model per gene, and you tell it which model with a design formula such as ~ cell + dex. DESeq2 uses a count model (the negative binomial) on the log scale rather than lm(), but it builds its design matrix with the same model.matrix(), so the columns and the meaning of each coefficient are the ones you have just learned. Here is the airway sample sheet, made as in RNA-seq counts and exploration:
library(airway)
library(SummarizedExperiment)
data("airway")
counts <- assay(airway)
coldata <- as.data.frame(colData(airway))
coldata$dex <- relevel(coldata$dex, ref = "untrt")
design <- model.matrix(~ cell + dex, data = coldata)
designReading the output. Eight samples, five columns. The reference donor is N052611, the first level alphabetically, so it has no column; the three cell dummies mark the other donors. dextrt is 1 for treated samples. Because every donor appears once untreated and once treated, the dextrt coefficient is the treatment effect within donors, the paired comparison of Comparing two groups written as a model. Its name is where DESeq2's dex_trt_vs_untrt comes from, and the relevel line is why it means treated minus untreated.
You can fit the same design with lm() to one gene's log counts to see the logic, though it is not how a real analysis should be done:
gene <- "ENSG00000152583" # SPARCL1 coldata$y <- log2(counts[gene, ] + 1) round(coef(lm(y ~ cell + dex, data = coldata)), 2) coldata$batch <- ifelse(coldata$dex == "trt", "day2", "day1") bad <- model.matrix(~ batch + dex, data = coldata) qr(bad)$rank; ncol(bad) coef(lm(y ~ batch + dex, data = coldata))
Reading the output. For this gene, treated samples sit 4.39 log2 units higher than untreated samples from the same donor, about a 21-fold rise (24.39). These are raw counts without the depth correction DESeq2 applies, so treat the number as a sketch. The donor coefficients are small here (0.07 to 0.36), but for many genes the donors differ a lot, and that is exactly the variation the cell columns soak up.
The second half shows what goes wrong when a design cannot separate two effects. Suppose every treated sample had been sequenced on day 2 and every untreated one on day 1. The batchday2 and dextrt columns are then identical, so the matrix has 3 columns but only 2 independent ones: its rank, from qr(), is 2. lm() cannot split the effect between them, gives all of it to batch and reports NA for treatment. DESeq2 refuses such a design with an error that the model matrix is not full rank. No software can fix this afterwards: batch and treatment are confounded, and only the experimental design can prevent it. Batch effects and design formulas returns to this.
Go deeper: other codings and interactions in RNA-seq designs
Treatment coding is one choice among several. With contrasts(bw$race) <- contr.sum(3), sum coding, the coefficients compare each level with the average of all levels instead of with one reference group. The fitted values are unchanged; only the meaning of the coefficients moves. Most RNA-seq tools assume treatment coding, so stay with it unless you have a reason.
Interactions appear in RNA-seq designs too. ~ genotype + treatment + genotype:treatment asks whether the treatment effect differs between genotypes, and the interaction coefficient is that difference, exactly like lwt:smokesmoker above. Read its main effects with the same care: treatment is then the effect in the reference genotype only.
The formula notation used by lm() and model.matrix() goes back to Wilkinson and Rogers, "Symbolic description of factorial models for analysis of variance" (Journal of the Royal Statistical Society, Series C, 1973), and was adopted for S and then R by Chambers and Hastie in Statistical Models in S (1992). DESeq2 is described by Love, Huber and Anders 2014 (Genome Biology); its vignette explains how design formulas, reference levels and interaction terms map onto coefficient names such as dex_trt_vs_untrt.
Common mistakes
- Reading a factor coefficient as a group mean. It is a difference from the reference level; only the intercept is a mean.
- Forgetting which level is the reference. Check
levels()before fitting, and relevel if needed. - Reading a main effect as "the effect" in a model with an interaction. It is the effect where the other variable is zero or at its reference.
- Coding groups as numbers (1, 2, 3) and leaving them numeric.
lm()then fits one slope across the codes. Make them factors. - Designing an experiment where batch and condition line up perfectly. Check the design matrix's rank before you collect, not after.
Further reading · Module 2Greenland et al. 2016: 25 common misreadings of p-values and confidence intervals. · All reading for this course
Check your understanding
1. In lm(bwt ~ race) with white as the first level, what is the raceblack coefficient?
2. In lm(bwt ~ lwt * smoke), what does the smokesmoker coefficient measure?
3. Every treated sample was sequenced in batch 2 and every untreated one in batch 1. What happens with ~ batch + dex?