R中的异方差性模拟

时间:2013-11-06 02:25:53

标签: r montecarlo

我想模拟异方差性,看看White的测试如何针对各种样本量进行测试(这与Greene类似,但测试不同类型)。

现在,我想测试的模型是:

Replications=1000=n 
y=1.5x+ e 
x ~ N(25, 15) 
e ~ N(0, sigma_i) 
sigma_i= 1+ alpha (sqrt(x[i]^2) 

并说最初样本量= 20(这部分很容易变化)

因此,使用bstats命令进行白色测试,我将代码编写为

for (j in 1:n) {
  for (i in 1:20){
    x[i]=rnorm(1, 25, 15)
    sigma [i]=1+0*sqrt(x[i]^2)
    epsilon[i]=rnorm(1, 0, sigma[i])
    y[i]=1.5*x[i]+epsilon[i]}
  lm1[j]<- lm(y~x); white.test(lm1[j])
  if (white.test(lm1)$p.value > 0.05){ind=ind
  }else{
    if (white.test(lm1)$p.value < 0.05) {ind=ind+1}
  } 
  IND1=ind/1000}
} 

现在,我知道这是一个问题,因为i部分有效,但我无法使外部for循环工作。有没有人有任何建议?

1 个答案:

答案 0 :(得分:2)

require(tseries)
# if you dont have above package, please install it
# it can be done by running following code
# install.packages('tseries')

########### function that simulates 100 times for hetro- 
test_gen=function(n,m){
  esp=0
  saved=0
  for(i in 1:m){   # simulate  100 times
    X=rnorm(n,25,1)
    for(j in 1:length(X)){
    eps[j]=rnorm(1,0,sqrt((X[j])^2)[1])
    }
    Y=1.5*X+eps

    temp=white.test(X,Y)

    saved[i]=temp$p.value
  }
  return(saved)
}

#red dots are the values less than 0.05
#n controls the size of sample
#m controls numbers of simulation
n=20
m=100
out=test_gen(n,m)
plot(c(1:length(out)),out,main="p-value(whitetest) for each simulated data") 
ind=out<0.05
points(c(1:length(out))[ind],out[ind],col='red',pch=16)

plot

out2=0
#simulate 100 times for each specific data size 
for(i in 20:100){
  k=i-19
  temp=test_gen(i,100)
  out2[k]=sum(temp<0.5)/100
}

plot(20:100,out2,main="error rate",xlab="sample size") # error rate

plot

我觉得我正在做你的作业......无论如何好运