Home > Back-end >  nested for loop in R not producing the correct amount of iterations
nested for loop in R not producing the correct amount of iterations

Time:10-31

I have a pretty simple for loop (or so I thought). The purpose of it is to do an action 1000 times under 20 different conditions. This should provide a result of 20,000. Instead I get 1000. My thinking is that I am likely missing something pretty trivial.

nSims <- 1000
Prop1 <- numeric(nSims * 20) 
Prop2 <- numeric(nSims * 20) 
Prop3 <- numeric(nSims * 20)
Score <- NA

for(i in 1:nSims){
for (j in 1:20){
G1 <- rnorm (10000, 100, 10)
G2 <- rnorm (10000, 100 - i/50, 10)
G3 <- rnorm (10000, 100   i/50, 10)

Prop1 [i] = length (which (G1 > (100 j))) /length (G1)
Prop2 [i] = length (which (G2 > (100 j))) /length (G2)
Prop3 [i] = length (which (G3 > (100 j))) /length (G3)
Score [j] = 100   j
}
}
sim <- data.frame (cbind (Prop1, Prop2, Prop3, Score))

The output should be a dataframe with three variable of 1000 for each iteration of j. Instead, I get 50 iterations of J and then a lot of 0's.

CodePudding user response:

You may use a different index (k) to save the calculation.

nSims <- 1000
Prop1 <- numeric(nSims * 20) 
Prop2 <- numeric(nSims * 20) 
Prop3 <- numeric(nSims * 20)
Score <- NA
k <- 0

for(i in 1:nSims){
  for (j in 1:20){
    G1 <- rnorm (10000, 100, 10)
    G2 <- rnorm (10000, 100 - i/50, 10)
    G3 <- rnorm (10000, 100   i/50, 10)
    k <- k   1
    Prop1 [k] = length (which (G1 > (100 j))) /length (G1)
    Prop2 [k] = length (which (G2 > (100 j))) /length (G2)
    Prop3 [k] = length (which (G3 > (100 j))) /length (G3)
    Score [k] = 100   j
  }
}
sim <- data.frame (Prop1, Prop2, Prop3, Score)

nrow(sim)
#[1] 20000
  • Related