我认为最直接的解决方案是使用model.matrix
. 可能,您可以通过一些花哨的步法和自定义对比来实现您想要的。但是,如果您想要“类型 3 esque”的 p 值,您可能希望模型中的每个术语都使用它,在这种情况下,我认为我的方法model.matrix
无论如何都很方便,因为您可以轻松地隐式循环遍历所有模型,将一列放在一次。提供一种可能的方法并不是对其统计优点的认可,但我确实认为你提出了一个明确的问题,并且似乎知道它在统计上可能不合理,所以我认为没有理由不回答它。
## initial data
set.seed(10)
d <- data.frame(
A = rep(c("a1", "a2"), each = 50),
B = c("b1", "b2"),
value = rnorm(100))
options(contrasts=c('contr.sum','contr.poly'))
## create design matrix
X <- model.matrix(~ A * B, data = d)
## fit models dropping one effect at a time
## change from 1:ncol(X) to 2:ncol(X)
## to avoid a no intercept model
m <- lapply(1:ncol(X), function(i) {
lm(value ~ 0 + X[, -i], data = d)
})
## fit (and store) the full model
m$full <- lm(value ~ 0 + X, data = d)
## fit the full model in usual way to compare
## full and regular should be equivalent
m$regular <- lm(value ~ A * B, data = d)
## extract and view coefficients
lapply(m, coef)
这将导致最终输出:
[[1]]
X[, -i]A1 X[, -i]B1 X[, -i]A1:B1
-0.2047465 -0.1330705 0.1133502
[[2]]
X[, -i](Intercept) X[, -i]B1 X[, -i]A1:B1
-0.1365489 -0.1330705 0.1133502
[[3]]
X[, -i](Intercept) X[, -i]A1 X[, -i]A1:B1
-0.1365489 -0.2047465 0.1133502
[[4]]
X[, -i](Intercept) X[, -i]A1 X[, -i]B1
-0.1365489 -0.2047465 -0.1330705
$full
X(Intercept) XA1 XB1 XA1:B1
-0.1365489 -0.2047465 -0.1330705 0.1133502
$regular
(Intercept) A1 B1 A1:B1
-0.1365489 -0.2047465 -0.1330705 0.1133502
到目前为止,对于使用lm
. 你提到这最终是为了lmer()
,所以这里是一个使用混合模型的例子。我相信,如果您有多个随机截距(即,需要从模型的固定和随机部分删除效果),它可能会变得更加复杂。
## mixed example
require(lme4)
## data is a bit trickier
set.seed(10)
mixed <- data.frame(
ID = factor(ID <- rep(seq_along(n <- sample(3:8, 60, TRUE)), n)),
A = sample(c("a1", "a2"), length(ID), TRUE),
B = sample(c("b1", "b2"), length(ID), TRUE),
value = rnorm(length(ID), 3) + rep(rnorm(length(n)), n))
## model matrix as before
X <- model.matrix(~ A * B, data = mixed)
## as before but allowing a random intercept by ID
## becomes trickier if you need to add/drop random effects too
## and I do not show an example of this
mm <- lapply(1:ncol(X), function(i) {
lmer(value ~ 0 + X[, -i] + (1 | ID), data = mixed)
})
## full model
mm$full <- lmer(value ~ 0 + X + (1 | ID), data = mixed)
## full model regular way
mm$regular <- lmer(value ~ A * B + (1 | ID), data = mixed)
## view all the fixed effects
lapply(mm, fixef)
这给了我们...
[[1]]
X[, -i]A1 X[, -i]B1 X[, -i]A1:B1
0.009202554 0.028834041 0.054651770
[[2]]
X[, -i](Intercept) X[, -i]B1 X[, -i]A1:B1
2.83379928 0.03007969 0.05992235
[[3]]
X[, -i](Intercept) X[, -i]A1 X[, -i]A1:B1
2.83317191 0.02058800 0.05862495
[[4]]
X[, -i](Intercept) X[, -i]A1 X[, -i]B1
2.83680235 0.01738798 0.02482256
$full
X(Intercept) XA1 XB1 XA1:B1
2.83440919 0.01947658 0.02928676 0.06057778
$regular
(Intercept) A1 B1 A1:B1
2.83440919 0.01947658 0.02928676 0.06057778