2016-07-06 91 views
0

我想知道如何创建一个双循环。 在我的代码中,我对1000个样本进行了多元回归(每个样本大小:25) 然后,我为1000个样本中的每个样本创建了t检验值,其中为null假设:来自sample ='real'beta3值的beta3值。我知道蒙特卡洛模拟中的'真实'beta3值(beta 3 =回归的第三个系数值)。 但是,代码工作到目前为止。 现在,我想对样本大小为50,100,250,500和1000(每个样本大小为1000次)执行相同的过程。 如何用循环来实现这个目标。如果你能帮助我,我会很高兴!在这里你可以看到我的代码:如何创建双循环?

n <- 25 
B <- 1000 
beta3 <- 1.01901 #'real' beta3 value 

t.test.values <- rep(NA, B) 
for(rep in 1:B){ 

##data generation 
    d1 <- runif(25, 0, 1) 
    d2 <- rnorm(25, 0, 1) 
    d3 <- rchisq(25, 1, ncp=0) 
    x1 <- (1 + d1) 
    x2 <- (3 * d1 + 0.6 * d2) 
    x3 <- (2 * d1 + 0.6 * d3) 
    exi <- rchisq(25, 5, ncp = 0) 
    y <- beta0 + beta1*x1 + beta2*x2 + beta3*x3 + exi 

## estimation 
    lmobj  <- lm(y ~ x1 + x2 + x3)   

## extraction 
    betaestim <- coefficients(lmobj)[2:4] 
    betavar <- vcov(lmobj)[2:4, 2:4] 

## t-test 
    t.test.values[rep] <- (betaestim[3] - beta3)/sqrt((betavar)[9]) 

    } 
+2

_16月16日发布您的原始问题并接受@bouncyball的答案后的四个月,您在17NOV16上大量更改了Q.请回复您的更改并提交一个新问题。 – Uwe

回答

0

我们可以用一个data.frame储存结果。还请注意,您没有包含beta0,beta1beta2的值,所以我只使用了占位符值。

n <- c(50,100,250,500,1000) #how big are our sample sizes? 
B <- 1000 
beta3 <- 1.01901 #'real' beta3 value 
#other beta values (note that these were not included in your question) 
beta1 <- 2 
beta2 <- 4 
beta0 <- 6 

iter <- 1 

#initialize our results data.frame 
result_df <- data.frame(sample_size = numeric(length(n) * B), 
         t.test.values = numeric(length(n) * B) 
         ) 

for(size in n){ 

for(rep in 1:B){ 

    ##data generation 
    d1 <- runif(size, 0, 1) 
    d2 <- rnorm(size, 0, 1)  
    d3 <- rchisq(size, 1, ncp=0)  
    x1 <- (1 + d1)  
    x2 <- (3 * d1 + 0.6 * d2)  
    x3 <- (2 * d1 + 0.6 * d3)  
    exi <- rchisq(size, 5, ncp = 0)  
    y <- beta0 + beta1*x1 + beta2*x2 + beta3*x3 + exi 

    ## estimation 
    lmobj  <- lm(y ~ x1 + x2 + x3)   

    ## extraction 
    betaestim <- coefficients(lmobj)[2:4] 
    betavar <- vcov(lmobj)[2:4, 2:4] 

    ## store our values 
    result_df[iter, 1] <- size 

    result_df[iter, 2] <- (betaestim[3] - beta3)/sqrt((betavar)[9]) 

    iter = iter + 1 #iterate 

    } 
} 

只要你使用的东西来跟踪迭代(我在这里使用iter),双for环是不是太糟糕。只要确保将data.frame初始化为正确的大小即可。如果你打算做更多的模拟,看看replicate函数和*apply函数类可能会有帮助。