简体   繁体   中英

Nested for loop in R for simulation

Dear community,

I want to build a nested for loop. The inner loop shall repeatedly (x 10.000) calculate the p-value of a stand. norm. distn.with j draws and save it in 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. The below code does not work for me and my p_val_mean has 1000 entries with only 4 of them containing calculated values:

# 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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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