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

Jacques VESLOT jacques.veslot at cirad.fr
Fri Mar 24 14:09:40 CET 2006


 > mat <- matrix(rnorm(10000),100)
 > system.time({    res1 <- NULL ;
                   for (i in 1:(ncol(mat)-1)) for (j in (i+1):ncol(mat)) 
res1 <- rbind(res1, c(i, j))})
[1] 1.51 0.01 1.53   NA   NA
 > system.time(res2 <- which(upper.tri(mat), T))
[1] 0.02 0.00 0.02   NA   NA
 > all.equal(res1,res2[order(res2[,"row"]),])
[1] TRUE


Daniel Goldstein a écrit :

>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,
>Dan
>
>  
>




More information about the R-help mailing list