# [R] Question Regarding a nested for loop in R

Vermilio, Ryan RYAN.VERMILIO at ucdenver.edu
Thu Dec 3 23:42:35 CET 2015

```Hello there,

I'm an R novice and am trying to figure out how to create an external for loop.  My current loop iterates 15 times and stores the resulting values in 3 separate vectors.  What I need is to create an outside loop that will run internal loop 4 times, sum the resulting vectors for each, and then store the sum of each in a vector of length 4 for each investment.

Right now, the target vector has the same value in each position, which is what I'm trying to fix.

Here's what I have at this point:

Inv1Returns <- c(0, 1000, -500, 500)
Inv2Returns <- c(0, -9000, 30000, 10000)
Inv3Returns <- c(0, 4000, -1000, -2000)

random = runif(15, 0, 1)

Inv1Outcome = NULL
Inv2Outcome = NULL
Inv3Outcome = NULL

Inv1Total = NULL
Inv2Total = NULL
Inv3Total = NULL

for (j in 1:4)

{

for (i in 1:15 )

{

Inv1Outcome[i] = if (random[i] <= .25){Inv1Returns[1]}
else if (random[i] > .25 & random[i] <= .50){Inv1Returns[2]}
else if (random[i] > .50 & random[i] <= .75){Inv1Returns[3]}
else {Inv1Returns[4]}

Inv2Outcome[i] = if (random[i] <= .20){Inv2Returns[1]}
else if (random[i] > .20 & random[i] <= .30){Inv2Returns[2]}
else if (random[i] > .30 & random[i] <= .70){Inv2Returns[3]}
else {Inv2Returns[4]}

Inv3Outcome[i] = if (random[i] <= .50){Inv3Returns[1]}
else if (random[i] > .50 & random[i] <= .70){Inv3Returns[2]}
else if (random[i] > .70 & random[i] <= .90){Inv3Returns[3]}
else {Inv3Returns[4]}

}

Inv1Total = append(Inv1Total, sum(Inv1Outcome))
Inv2Total = append(Inv2Total, sum(Inv2Outcome))
Inv3Total = append(Inv3Total, sum(Inv3Outcome))

}

Inv1Total
Inv2Total
Inv3Total

Sincerely,

Ryan

[[alternative HTML version deleted]]

```