我有一个带有一个分类变量的线性回归模型(男性和女性)和一个连续变量.
我在 R 中用options(contrasts=c("contr.sum","contr.poly"))
. 现在我有 III 型平方和,, 以及它们的交互 (A:B) 使用drop1(model, .~., test="F")
.
我坚持的是如何计算平方和. 我认为是sum((predicted y of the full model - predicted y of the reduced model)^2)
。简化后的模型看起来像y~A+A:B
。但是当我使用 时predict(y~A+A:B)
,R 会返回与完整模型预测值相同的预测值。因此,平方和为 0。
(对于平方和,我使用了 的简化模型y~B+A:B
,与 相同y~A:B
。)
以下是随机生成数据的示例代码:
A<-as.factor(rep(c("male","female"), each=5))
set.seed(1)
B<-runif(10)
set.seed(5)
y<-runif(10)
model<-lm(y~A+B+A:B)
options(contrasts = c("contr.sum","contr.poly"))
#type3 sums of squares
drop1(model, .~., test="F")
#or same result:
library(car)
Anova(lm(y~A+B+A:B),type="III")
#full model
predFull<-predict(model)
#Calculate sum of squares
#SS(A|B,AB)
predA<-predict(lm(y~B+A:B))
sum((predFull-predA)^2)
#SS(B|A,AB) (???)
predB<-predict(lm(y~A+A:B))
sum((predFull-predB)^2)
#Sums of squares should be 0.15075 (according to anova table)
#but calculated to be 2.5e-31
#SS(AB|A,B)
predAB<-predict(lm(y~A+B))
sum((predFull-predAB)^2)
#Anova Table (Type III tests)
#Response: y
# Sum Sq Df F value Pr(>F)
#(Intercept) 0.16074 1 1.3598 0.2878
#A 0.00148 1 0.0125 0.9145
#B 0.15075 1 1.2753 0.3019
#A:B 0.01628 1 0.1377 0.7233
#Residuals 0.70926 6