简体   繁体   English

在 R 中嵌套 for 循环进行模拟

[英]Nested for loop in R for simulation

Dear community,亲爱的社区,

I want to build a nested for loop.我想构建一个嵌套的 for 循环。 The inner loop shall repeatedly (x 10.000) calculate the p-value of a stand.内循环应重复 (x 10.000) 计算支架的 p 值。 norm.规范。 distn.with j draws and save it in p_val.用 j 绘制并将其保存在 p_val 中。 The outer loop shall repeat this inner loop for my i number of draws, where i = c(10,50,100,1000) and then save the mean of that in p_val_mean which should be a vector with only four entries.外循环应为我的 i 次抽奖重复这个内循环,其中 i = c(10,50,100,1000) 然后将平均值保存在 p_val_mean 中,它应该是一个只有四个条目的向量。 The below code does not work for me and my p_val_mean has 1000 entries with only 4 of them containing calculated values:下面的代码对我不起作用,我的 p_val_mean 有 1000 个条目,其中只有 4 个包含计算值:

# outer loop

p_val_mean <- rep(NA, 4)
for (i in c(10, 50, 100, 1000)){

# inner loop
n <- 10000
p_val <- rep(NA, 10000)
for(j in 1:n){
  current_data <- rnorm(i,0,1)
  current_t_stat <- t.test(current_data)
  current_p_val <- current_t_stat$p.value
  p_val[j] <- current_p_val
}
p_val_mean[i] <- mean(p_val)
}
p_val_mean

I thank you in advance for your replies!我提前感谢您的回复!

You cannot use your i as an index, use this instead:您不能使用 i 作为索引,而是使用它:

p_val_mean <- rep(NA, 4)
N <- c(10, 50, 100, 1000)

for (i in 1:length(N)){

  # inner loop
  n <- 10000
  p_val <- rep(NA, n)
  for(j in 1:n){
    current_data <- rnorm(N[i], 0, 1)
    current_t_stat <- t.test(current_data)
    current_p_val <- current_t_stat$p.value
    p_val[j] <- current_p_val
  }
  p_val_mean[i] <- mean(p_val)
}
p_val_mean

You don't need nested loops.您不需要嵌套循环。 The following single line of code does what you need:以下单行代码可以满足您的需求:

sapply(c(10, 50, 100, 1000), function(x) mean(replicate(x, t.test(rnorm(1000))$p.val)))
#> [1] 0.4272396 0.5089299 0.4686196 0.4930584

We can use map我们可以使用map

library(purrr)
map_dbl(c(10, 50, 100, 1000), ~ mean(replicate(.x, t.test(rnorm(1000))$p.val)))
#[1] 0.4030399 0.4840713 0.4791711 0.4960831

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM