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

David Winsemius dwinsemius at comcast.net
Fri Dec 4 06:59:51 CET 2015

```> On Dec 3, 2015, at 2:42 PM, Vermilio, Ryan <RYAN.VERMILIO at ucdenver.edu> wrote:
>
> 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
>

—— initialize a list

for( k in  1:4){

> 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))
>
> }

---Do the requested operations
---Store in list

}

>
> Inv1Total
> Inv2Total
> Inv3Total

I suspect I could write that operation in about 3 lines of code (and it actually took one line of code), but it really isn’t what you are requesting. There is a function designed for repeating operations is `replicate`. See:

?replicate

>
> Sincerely,
>
> Ryan
>
> 	[[alternative HTML version deleted]]

Sincerely, Ryan, please do read the posting guide and post in plain text.

>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius
Alameda, CA, USA

```