rm(list=ls()) k <- 1000 n <- 100 alp <- 0.05 test.res <- numeric(k) for(i in 1:k){ x1<- rnorm(n,0,0.5) x2<- rbinom(n,1,prob=0.5) y <- 2*x1+3*x2 eb <- rnorm(n,0,1) beta1hat <- solve(t(x1)%*%x1)%*%t(x1)%*%y beta2hat <- solve(t(x1)%*%x1)%*%t(x1)%*%y } hlo1 <- beta1hat-sigma*solve(t(x1)%*%x1)*qnorm(0.025) hup1 <- beta1hat+sigma*solve(t(x1)%*%x1)*qnorm(0.025) hlo2 <- beta2hat-sigma*solve(t(x2)%*%x2)*qnorm(0.025) hup2 <- beta2hat+sigma*solve(t(x2)%*%x2)*qnorm(0.025) 报错
时间: 2023-12-18 20:02:17 浏览: 125
zip test_1_0-201130185208.alp
这段代码存在一些问题,导致运行时出现报错。其中的sigma没有定义,应该是指模型误差的标准差,需要在代码中进行定义。同时,最小二乘法估计beta2hat的时候,应该是用t(x2)而不是t(x1)进行计算。修改后的代码如下:
```
rm(list=ls())
k <- 1000
n <- 100
alp <- 0.05
test.res <- numeric(k)
sigma <- 1 # 定义模型误差的标准差
for(i in 1:k){
x1<- rnorm(n,0,0.5)
x2<- rbinom(n,1,prob=0.5)
y <- 2*x1+3*x2
eb <- rnorm(n,0,1)
beta1hat <- solve(t(x1)%*%x1)%*%t(x1)%*%y
beta2hat <- solve(t(x2)%*%x2)%*%t(x2)%*%y
}
hlo1 <- beta1hat-sigma*solve(t(x1)%*%x1)*qnorm(0.025)
hup1 <- beta1hat+sigma*solve(t(x1)%*%x1)*qnorm(0.025)
hlo2 <- beta2hat-sigma*solve(t(x2)%*%x2)*qnorm(0.025)
hup2 <- beta2hat+sigma*solve(t(x2)%*%x2)*qnorm(0.025)
```
这样修改后,代码应该能够正常运行了。
阅读全文