这里是一些用于从R中的lmtest包中重现bgtest()函数的代码。以下是我在bgtest()中为卡方和F测试重新创建代码的最佳尝试。两次尝试都接近bgtest()的输出,特别是卡方,但它们并不相同。有什么想法吗?
x = c(39,47,45,47,65,46,67,42,67,56,64,56,59,34,42,48,45,17,20,19,36,50,39,21,44,53,63,29,25,69)
y = c(144,220,138,145,162,142,170,124,158,154,162,150,140,110,128,130,135,114,116,124,136,142,120,120,160,158,144,130,125,175)
dat <- data.frame(x=x,y=y)
p=1
k=2
n=nrow(dat)
## Get the residuals
mod<-lm(y ~ x, data=dat)
dat$res <- mod$residuals
#install.packages("Hmisc")
library(Hmisc)
dat$res1 <- Lag(dat$res, p)
bgmod<-lm(res~x+res1,data=dat)
(LM<-(n*sum(bgmod$fitted^2))/sum(dat$res^2))
1-pchisq(q=LM,df=p)
bgtest(mod,order = 1)
(Fstar= ((sum(dat$res^2) - sum(bgmod$residuals^2))/p)/(sum(bgmod$residuals^2)/(n - k - p)))
1-pf(q = Fstar,p,n-k-p)
bgtest(mod,order = 1,type="F")