[R] Nested for loops

Moshe Olshansky m_olshansky at yahoo.com
Tue Jul 14 08:03:50 CEST 2009


Make it
for (i in 1:9)

This is not the general solution, but in your case when i=10 you do not want to do anything.

--- On Tue, 14/7/09, Michael Knudsen <micknudsen at gmail.com> wrote:

> From: Michael Knudsen <micknudsen at gmail.com>
> Subject: [R] Nested for loops
> To: r-help at r-project.org
> Received: Tuesday, 14 July, 2009, 3:38 PM
> Hi,
> 
> I have spent some time locating a quite subtle (at least in
> my
> opinion) bug in my code. I want two nested for loops
> traversing the
> above-diagonal part of a square matrix. In pseudo code it
> would
> something like
> 
> for i = 1 to 10
> {
>    for j = i+1 to 10
>    {
>       // do something
>    }
> }
> 
> However, trying to do the same in R, my first try was
> 
> for (i in 1:10)
> {
>    for (j in (i+1):10)
>    {
>        // do something
>    }
> }
> 
> but there's a problem here. For i=10, the last for loop is
> over 11:10.
> Usually programming laguages would regard what corresponds
> to 11:10 as
> empty, but A:B with A bigger than B is in R interpreted as
> the numbers
> from B to A in reverse order.
> 
> Is there a clever way to make nested loops like the one
> above in R?
> 
> -- 
> Michael Knudsen
> micknudsen at gmail.com
> http://lifeofknudsen.blogspot.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