[R] nested "for" loops

David Winsemius dwinsemius at comcast.net
Sat Nov 5 21:04:51 CET 2011

```You need to define "l" as a dimensioned object , either a vector or an array, and then assign the value of your calculation to the correctly indexed "location" in that object. Otherwise you are just overwriting the value each time through the loop. Use these help pages (and review "Introduction to R"

?array
?vector
?"["

On Nov 4, 2011, at 7:49 PM, nick_pan <nick_pan88 at yahoo.gr> wrote:

> Hi all , I have written a code with nested "for" loops .
> The aim is to estimate the maximum likelihood by creating 3 vectors with the
> same length( sequence )
> and then to utilize 3 "for" loops to make combinations among the 3 vectors ,
> which are (length)^3 in number , and find the one that maximize the
> likelihood ( maximum likelihood estimator).
>
>
> The code I created, runs but I think something goes wrong...because when I
> change the length of the vectors but not the bounds the result is the
> same!!!
>
> I will give a simple example(irrelevant but proportional to the above) to
> make it more clear...
>
> Lets say we want to find the combination that maximize the multiplication of
> the entries of some vectors.
>
> V1<-c(1,2,3)
> V2<-c(5, 2 , 4)
> V3<-c( 4, 3, 6)
>
> The combination we look for is ( 3 , 5 , 6) that give us 3*5*6 = 90
>
> If I apply the following in R , I won't take this result
>
> V1<-c(1,2,3)
> V2<-c(5, 2 , 4)
> V3<-c( 4, 3, 6)
>
> for( i in V1){
>  for( j in V2) {
>     for( k in V3){
>
> l<- i*j*k
>
> }
> }
> }
> l
>
> Then " l<- i*j*k " is  number and not vector(of all multiplications of all
> the combinations) , and is 3*4*6 = 72.
>
> How can I fix the code?
>
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/nested-for-loops-tp3992089p3992089.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.

```

More information about the R-help mailing list