[R] How to avoid for or while loops when one index depends on another

Daniel Goldstein dgoldstein at london.edu
Fri Mar 24 13:38:25 CET 2006

Dear R Community,

I'm trying to exploit the elegance of R by doing the following
pseudocode routine without a WHILE or FOR loop in R:

for i = 1 to length-1
  for j = (i+1) to length
    print a[i], a[j]

That is, I want i and j to be the indices of a half-matrix
1 2, 1 3, 1 4, ..., 1 length,
      2 3, 2 4, ..., 2 length,
           3 4, ..., 3 length

1. Can this be done with the 'whole object' approach (Introduction to R 
v2.1.1 section 9.2.2) and not while loops?

2. (Extra credit) Is your solution likely to be more efficient than a loop?

3. (Extra credit) How could once do this with FOR as opposed to WHILE in 
R? Clearly if you attempt "j in i+1:length" you're in trouble when i 
exceeds length.

Thanks for your help with this excellent open-source resource,

Daniel Goldstein, Ph.D.
Assistant Professor of Marketing
London Business School s234
Regent's Park, Sussex Place
London NW1 4SA, United Kingdom
p: +44 (0) 20 7706 6796
f: +44 (0) 20 7724 1145

More information about the R-help mailing list