'Nested Loop (sampling) in R

I was wondering if anyone could help me figure out a nested loop!

I need to run the same loop 11 times, where the other loop is a simulation of 1000 iterations.

Here is the function I made use in the loop:


d.func <- function(y1,y0){

  temp <-  runif(n, min= 0, max=1)
  
  data.1 = tibble(D = ifelse(temp > .5,1,0), 
                  
      Y = ifelse(D == 1, y1, y0))
  
  ATE <- (mean(data.1[data.1$D==1,]$Y) - mean(data.1[data.1$D==0,]$Y))
  
  p.v <- t.test(data.1[data.1$D==1,]$Y, data.1[data.1$D==0,]$Y )$p.value

 return(p.v)
}

Here is the basic loop:


y0 <- rnorm(1000, mean=1, sd=1)

## Simulation


sim <- 10000

## creating storage for p.values

n <- 1000

pv.storage <- data.frame(matrix(data=NA, nrow=10000, ncol=1))
names(pv.storage)[1] <- "p.values"

## Running Simulation 

for(i in 1:sim){
  
tau.0 <- rnorm(1000, mean=.0, sd=1)

yt.2 <- y0 + tau.0

pv.storage[i,] <- d.func(yt.2,y0)
}

The thing I need to change is tau.2 <- rnorm(1000, mean=.2, sd=1), where the mean here needs to change from 0 to 1, by .1 . Basically, run the same thing 11 times.

Furthermore, I need to store all the p.values, since after I need to see how many of those values are less or equal to .5.

I don't know where to start. If anyone could give me any pointers. I don't understand how I can tell the loop to change the value of the mean everytime it goes.



Solution 1:[1]

It's not possible to replicate your code because some definitions of your code are not provided (y0 and d.func, namely), and you make a reference to tau.0 in one line and tau.2 in another - maybe that's a typo? Anyway, here's a blind attempt:

First, create a custom function for the steps that you wish to iterate over. In this case, there's no inputs needed for the function:

myfun <- function() {
  tau.0 <- rnorm(1000, mean=.0, sd=1)

  yt.2 <- y0 + tau.2

  d.func(yt.2,y0)
}

Assuming that this returns one value, you could just do:

pv.storage[,1] <- replicate(1000, myfun())

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Phil