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 16:02:17 浏览: 136
这段代码存在一些问题,导致运行时出现报错。其中的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)
```
这样修改后,代码应该能够正常运行了。
相关问题
rm(list=ls()) k <- 1000; n <- 100; alp <- 0.05; test.res <- numeric(k); mu <- 0.1; for(i in 1:k){ dat<- rnorm(n,mu,1) test.res[i] <- (abs(sqrt(n)*mean(dat))>=qnorm(1-alp/2,0,1)) } hp <- mean(test.res) p <- 2-pnorm(qnorm(1-alp/2,0,1)-sqrt(n)*mu)-pnorm(qnorm(1-alp/2,0,1)+sqrt(n)*mu) p <- 2-pnorm(qnorm(1-alp/2,0,1)*(1/sqrt(n))-mu)-pnorm(qnorm(1-alp/2,0,1)*(1/sqrt(n))+mu) hp-p
这段代码是进行一个单样本 t 检验的假设检验并计算 p 值以及检验是否拒绝原假设的过程。
具体来说,代码中先清空环境中的所有变量,然后设置样本量 n、显著性水平 alp、实验重复次数 k 和总体均值 mu 的值。接着,使用 for 循环生成 k 个样本,每个样本包含 n 个来自 N(mu,1) 的随机数,并计算样本均值的 t 统计量。在循环过程中,将每个样本是否拒绝原假设的结果存储在 test.res 向量中。
然后,代码计算样本中拒绝原假设的比例 hp,即样本中 t 统计量的绝对值大于临界值的样本占比。接着,分别使用两种方法计算 p 值,并将它们相减得到一个差值,即 hp-p。如果差值小于 0.01,则认为两种计算方法得到的 p 值差异不大。
最终的结果是差值的值,可以用来检查两种方法计算的 p 值是否一致。
k <- 1000 n <- 200 alp <- 2 lamb <- 1 x <- numeric(k) alphat <- numeric(k) lambhat <- numeric(k) set.seed(123) library(bootstrap) for(i in 1:k){ x[i] <- rgamma(n,alp,lamb) alphat[i] <- lambhat[i] <- (n*alp)/x[i] }
这段代码看起来是在使用自助法(bootstrap)来估计参数 alp 和 lamb。具体来说,这个程序会生成 1000 组大小为 200 的随机样本 x,这些样本服从参数为 alp 和 lamb 的 gamma 分布。然后,对于每一组样本,程序会用样本均值来估计参数 alp 和 lamb,最终得到两个长为 1000 的向量 alphat 和 lambhat,分别存储了 1000 组估计值。
需要注意的是,这里使用了 set.seed(123) 来设置随机数种子,这样可以使得程序每次运行生成的随机数序列都相同,方便验证结果的正确性。另外,这里调用了 bootstrap 包来实现自助法的计算。
阅读全文
相关推荐












