Skip to content

model.matrix(): keep the estimation reference of i() on new data - #704

Open
soodoku wants to merge 2 commits into
lrberge:masterfrom
finite-sample:model-matrix-i-newdata
Open

soodoku wants to merge 2 commits into
lrberge:masterfrom
finite-sample:model-matrix-i-newdata

Conversation

@soodoku

@soodoku soodoku commented Nov 15, 2026

Copy link
Copy Markdown
Contributor

Closes #687. This follows the diagnosis and the i_noref suggestion in that issue.

On new data, model.matrix() builds a bare i() term with the lowest level present in that data as the reference. If the estimation reference is absent, a column for an estimated coefficient is silently dropped:

library(fixest)
m  = feols(mpg ~ hp + i(cyl), data = mtcars)
nd = subset(mtcars, cyl != 4)
colnames(model.matrix(m, data = nd, type = "rhs"))
#> master:  "(Intercept)" "hp" "cyl::8"
#> this PR: "(Intercept)" "hp" "cyl::6" "cyl::8"      # = names(coef(m))

What the PR does. On new data, model.matrix() builds the i() columns with i_noref = TRUE, as predict() already does, and keeps those that were estimated.

One step beyond the issue, which you may want to reject. An estimated level with no row in the new data now comes back as a column of zeros. Examples are i(cyl, ref = 6) or i(cyl, hp) on data without cyl == 4. On master those columns are missing, so X %*% coef(m) fails or misaligns. The values are exact, since the indicator is identically zero on those rows. Without this, the columns still would not match coef() in that case. If you'd rather keep the PR to the reference-level case only, I can drop that part.

Calls without new data take the same path as before.

Tests, added to the Model matrix chunk:

  • columns equal coef() and X %*% coef equals predict(), with the reference absent;
  • the columns are unchanged when the reference is present;
  • the explicit-ref and i(cyl, hp) cases, with the zero column.

The first test fails on master. tests/fixest_tests.R runs to completion on this branch and merged with #703 and #705.

🤖 Generated with Claude Code

@kylebutts

Copy link
Copy Markdown
Collaborator

@grantmcdermott this is related to your issues, right? Do you mind reviewing this and see if it fixes your problems?

@grantmcdermott

Copy link
Copy Markdown
Collaborator

@grantmcdermott this is related to your issues, right? Do you mind reviewing this and see if it fixes your problems?

Thanks. I'll try to take a look by the end of the week.

@kylebutts

Copy link
Copy Markdown
Collaborator

@soodoku two problems I found.

  1. this breaks the subset = TRUE argument
m = feols(mpg ~ hp + i(cyl), mtcars)
model.matrix(m, data = mtcars["hp"], subset = TRUE)
  1. This example produces too many columns
m = feols(mpg ~ hp + i(cyl, factor(am), ref = 4), mtcars)
model.matrix(m, data = mtcars)

m does not have coefficients for cyl::4:factor(am):0 or cyl::4:factor(am):1, but these show up in the model matrix

@kylebutts

Copy link
Copy Markdown
Collaborator

BTW, the goal of this PR matches lm behavior:

fit <- lm(mpg ~ hp + factor(cyl):factor(am), data = mtcars)
model.matrix(fit, data = mtcars[1:5, ])

But it is not clear what to do in this situation where new levels exist in the new dataset:

fit <- lm(mpg ~ hp + factor(cyl):factor(am), data = mtcars[mtcars$cyl %in% c(4, 6), ])
model.matrix(fit, data = mtcars)
#> Error in `model.frame.default()`:
#> ! factor factor(cyl) has new levels 8

library(fixest)
fit <- feols(mpg ~ hp + i(cyl, i.am), data = mtcars[mtcars$cyl %in% c(4, 6), ])
head(model.matrix(fit, data = mtcars))
#>       (Intercept)  hp cyl::4:am::1 cyl::6:am::0 cyl::6:am::1 cyl::8:am::0 
#>  [1,]           1 110            0            0            1            0
#>  [2,]           1 110            0            0            1            0
#>  [3,]           1  93            1            0            0            0
#>  [4,]           1 110            0            1            0            0
#>  [5,]           1 175            0            0            0            1
#>       cyl::8:am::1
#>  [1,]            0
#>  [2,]            0
#>  [3,]            0
#>  [4,]            0
#>  [5,]            0

soodoku and others added 2 commits November 24, 2026 00:05
With new data, model.matrix() built bare i() terms with the lowest level
present in that data as the reference, not the reference used at estimation.
When the estimation reference was absent, a column for an estimated
coefficient was silently dropped and X %*% coef() disagreed with predict().
For feols(mpg ~ hp + i(cyl), mtcars) on subset(mtcars, cyl != 4) the columns
were (Intercept), hp, cyl::8 against coefficients (Intercept), hp, cyl::6,
cyl::8.

As predict() already does, build the i() columns with i_noref = TRUE on new
data and keep those that were estimated. An estimated level with no row in
the new data is now a column of zeros, so the columns match coef() in that
case too (for example i(cyl, ref = 6) or i(cyl, hp) on data without cyl == 4).
Calls without new data are unchanged.

Closes lrberge#687. Diagnosis and the i_noref suggestion by @grantmcdermott in that
issue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@soodoku
soodoku force-pushed the model-matrix-i-newdata branch from 5654bb2 to 8c3a9e2 Compare November 24, 2026 13:48
@soodoku

soodoku commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for catching both of those, @kylebutts — rebased on master and fixed both in 8c3a9e2:

  1. subset = TRUE: when subset is not FALSE, we now only adjust i() terms whose columns were kept in linear.mat, so dropped i() terms are not padded back in:

    m = feols(mpg ~ hp + i(cyl), mtcars)
    colnames(model.matrix(m, data = mtcars["hp"], subset = TRUE))
    #> "hp"
  2. Two-factor i() (i(cyl, factor(am), ref = 4)): i() previously skipped model_matrix_info when IS_INTER_FACTOR = TRUE, so i_noref = TRUE restored cyl::4 without model.matrix() knowing to drop it. i() now records coef_names_full and is_inter_fact = TRUE in model_matrix_info (which iplot() already guards against via is_inter_fact):

    m = feols(mpg ~ hp + i(cyl, factor(am), ref = 4), mtcars)
    colnames(model.matrix(m, data = mtcars))
    #> "(Intercept)" "hp" "cyl::6:factor(am)::0" "cyl::6:factor(am)::1" "cyl::8:factor(am)::0" "cyl::8:factor(am)::1"

    Regression tests for both cases (plus two-factor i() with absent estimated levels and partial subset = TRUE) are added in tests/fixest_tests.R.

  3. Unseen levels in data: checking current behavior across fixest:

    • factor(cyl) errors in both predict() and model.matrix() via xlev (matching lm()).
    • i(cyl) errors in predict() ("In i(), predictions cannot be done for values that were not present at estimation time"), while model.matrix() on master emits the unseen column (cyl::8).
    • i(cyl, i.am) previously bypassed predict()'s unseen-level check because IS_INTER_FACTOR wasn't in model_matrix_info, silently treating unseen cyl == 8 as the reference level cyl::4:am::0. Recording IS_INTER_FACTOR in model_matrix_info fixes that so predict() now errors consistently for two-factor i() as well.

    For model.matrix() on unseen i() levels, silently dropping unseen columns would alias those rows to the reference level, so the only safe options are either keeping master's behavior (emitting the extra columns so X %*% coef(fit) fails on non-conformable dimensions rather than silently mispredicting) or erroring with the same setdiff(mm_new_i$coef_names_full, mm_i$coef_names_full) check predict.fixest() uses. This PR keeps master's behavior on unseen levels to stay scoped to model.matrix() ignores the estimation reference for bare i() on new data #687, though erroring to match lm(), factor(), and predict.fixest() is the cleaner long-term behavior.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

model.matrix() ignores the estimation reference for bare i() on new data

3 participants