##import data
dt <- read.csv("CP.csv")
##load library
library(MASS)
library(stargazer)
library(AER)
##Q1.b
set.seed(12)
##type in parameter values
reps <- 1000
n <- 250
pai <- c(1,4,10,1000)
##create matrix for alpha.LS and alpha.IV
alpha.IV <-matrix(nrow=reps, ncol=1)
alpha.LS <-matrix(nrow=reps, ncol=1)
X.hat <-matrix(nrow=reps, ncol=1)
##OLS regression
for(j in 1:reps){
Z <-rnorm(n, mean=0, sd=1)
W <-rnorm(n, mean=0, sd=1)
X <-rnorm(n, mean=(1+pai)*W+Z, sd=sqrt((1+pai)^2+2))
Y <-rnorm(n, mean=X+pai*Z, sd=sqrt(2*(1+pai)^2+1))
LS <- lm(Y~0+X+Z)
alpha.LS[j] <-LS$coefficient[1]
}
print(mean(alpha.LS))
##2SLS
for(val in pai){
set.seed(12)
for(j in 1:reps){
Z.IV <-rnorm(n, mean=0, sd=1)
W.IV <-rnorm(n, mean=0, sd=1)
X.IV <-rnorm(n, mean=(1+pai)*W.IV+Z.IV, sd=sqrt((1+pai)^2+2))
eq1 <- lm(X.IV~0+Z.IV+W.IV)
Y.IV <-rnorm(n, mean=X.IV+pai*Z.IV, sd=sqrt(2*(1+pai)^2+1))
IV <- ivreg(Y.IV~0+eq1$fitted.values+Z.IV|Z.IV+W.IV)
alpha.IV[j] <-IV$coefficient[1]
}
print(mean(alpha.IV))
}
When I try to calculate the mean of alpha.IV I use a double loops since I want to test the result using 4 different values of pai. However, using the double loops result in giving different values than pre-setting the value of pai before going into the loop.
Why would this happen?
Thanks a lot!