Skip to content
Prev 166845 / 398502 Next

If...while...or what else??

On 13-Jan-09 13:20:54, Niccol? Bassani wrote:
Presumably the foloowing summarises the situation you want to avoid:

  for(i in (1:5)){for(j in ((i+1):5)){ print(c(i,j))}}
# [1] 1 2
# [1] 1 3
# [1] 1 4
# [1] 1 5
# [1] 2 3
# [1] 2 4
# [1] 2 5
# [1] 3 4
# [1] 3 5
# [1] 4 5
# [1] 5 6
# [1] 5 5

I.e. you get (5,6) when case 6 is not wanted. If (as seems likely)
you don't want (5,5) either (i.e. you only want all pairs (i,j)
from 1:5 with i<j), then the following does it:

  for(i in (1:4)){for(j in ((i+1):5)){ print(c(i,j))}}
# [1] 1 2
# [1] 1 3
# [1] 1 4
# [1] 1 5
# [1] 2 3
# [1] 2 4
# [1] 2 5
# [1] 3 4
# [1] 3 5
# [1] 4 5

However, if for some reason you do want (5,5) as well, then:

  for(i in (1:5)){for(j in (min(5,(i+1)):5)){ print(c(i,j))}}
# [1] 1 2
# [1] 1 3
# [1] 1 4
# [1] 1 5
# [1] 2 3
# [1] 2 4
# [1] 2 5
# [1] 3 4
# [1] 3 5
# [1] 4 5
# [1] 5 5

Also (though I suspect it was simply due to hasty typing), the syntax
of what you wrote above:

  for i in 1:5{
   for j in (i+1):5{
     ...
   }
  }

will not work, since you must write "for( ... )" and not "for ... ":

  for i in (1:5)
# Error: unexpected symbol in "for i"

Hoping this helps,
Ted.

--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 13-Jan-09                                       Time: 15:09:58
------------------------------ XFMail ------------------------------