## Loading required package: pbkrtest
## Loading required package: lme4
## Loading required package: Matrix

Package version: 0.5.2

Consider two linear models; the smaller is a submodel of the large:

N <- 4
dat <- data.frame(int=rep(1, N), x=1:N, y=rnorm(N))
lg <- lm(y ~ x + I(x^2), data=dat)
sm <- lm(y ~ x, data=dat)
lg
## 
## Call:
## lm(formula = y ~ x + I(x^2), data = dat)
## 
## Coefficients:
## (Intercept)            x       I(x^2)  
##     1.14200     -0.49503      0.08482
sm
## 
## Call:
## lm(formula = y ~ x, data = dat)
## 
## Coefficients:
## (Intercept)            x  
##     0.71792     -0.07095

The corresponding model matrices are

Xlg <- model.matrix(lg)
Xsm <- model.matrix(sm)
Xlg
##   (Intercept) x I(x^2)
## 1           1 1      1
## 2           1 2      4
## 3           1 3      9
## 4           1 4     16
## attr(,"assign")
## [1] 0 1 2
Xsm
##   (Intercept) x
## 1           1 1
## 2           1 2
## 3           1 3
## 4           1 4
## attr(,"assign")
## [1] 0 1

Given the two model matrices, the restriction matrix which describes the restrictions that should be made to the model matrix of the large model to produce the model matrix of the small model:

L <- make_restriction_matrix(Xlg, Xsm)
L 
##      [,1] [,2] [,3]
## [1,]    0    0   -1

Given the model matrix of the large model and the restriction matrix, the model matrix of the small model can be constructed as:

Xsm_2 <- make_model_matrix(Xlg, L)
Xsm_2
##   [,1] [,2]
## 1    1    1
## 2    2    1
## 3    3    1
## 4    4    1

The same operation can be made directly on model objects:

##      [,1] [,2] [,3]
## [1,]    0    0   -1

Likewise, given the large model and the restriction matrix, the small model can be constructed:

sm_2 <- restriction_matrix2model(lg, L)
sm_2
## 
## Call:
## lm(formula = y ~ .X1 + .X2 - 1, data = structure(list(.X1 = c(1, 
## 2, 3, 4), .X2 = c(1, 1, 1, 1), y = c(0.346516823166798, 1.64701187281576, 
## -0.735558530709959, 0.904200394770981), x = 1:4, `I(x^2)` = structure(c(1, 
## 4, 9, 16), class = "AsIs")), class = "data.frame", row.names = c(NA, 
## 4L)))
## 
## Coefficients:
##      .X1       .X2  
## -0.07095   0.71792
sm_2 |> model.matrix()
##   .X1 .X2
## 1   1   1
## 2   2   1
## 3   3   1
## 4   4   1
## attr(,"assign")
## [1] 1 2

Lastly, model matrices can be compared

## The first column space contains the second
compare_column_space(Xlg, Xsm)
## [1] 1
## The second column space contains the first
compare_column_space(Xsm, Xlg)
## [1] 0
## The two column spaces are identical
compare_column_space(Xlg, Xlg) 
## [1] -1