02 - Coercion between model objects and restriction matrices in ‘pbkrtest’

Søren Højsgaard and Ulrich Halekoh

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)  
##      3.3611      -1.3818       0.1324
sm
## 
## Call:
## lm(formula = y ~ x, data = dat)
## 
## Coefficients:
## (Intercept)            x  
##      2.6990      -0.7197

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:

L <- model2restriction_matrix(lg, sm)
L
##      [,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(2.35880696402226, 0.385927588718172, 
## 1.14883382329707, -0.29436026637611), 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.7197   2.6990
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