Gabor Grothendieck
2002-Jan-29 03:39 UTC
[R] Problems with seq (was Iterate over 1<=i<j<=n
In answer to the query about iterating over 1 <= i < j <= n several people suggested for(i in 1:(n-1)) for(j in (i+1):n)) ... This also has the efficiency advantage that the last iteration of i is never attempted. The index arithmetic, albeit minimal, is still a bit hard on the mind but its a pretty good practical solution in most cases. Unfortunately, it fails for n=1. This may not be so terrible in most cases of interest. However, handling boundary cases correctly is a hallmark of good programming so I think we need to keep looking. Here is another solution I came up with: for( i in seq(n) ) for( j in seq(n)[-seq(i)] ) ... however, it too is a kludge in my mind. An improvement to the seq() built into R is what is really required. Many people are used to this in C, awk and perl: for( i=1; i<=n; i++ ) for( j=i+1; j<=n; j++ ) as well as similar constructs in other languages. The principle of least surprise suggests that the R analogue should work correctly too. Its pretty easy to write your own seq but the use of this function is widespread in R and having it broken in this way just encourages kludges, mind numbing workarounds or bad code failing to handle boundary conditions. Creating a new builtin (e.g. seq0), adding an argument to seq (e.g. nullOK) or changing seq''s behaviour on boundary conditions are three possible solutions. _____________________________________________________________ -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.- r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html Send "info", "help", or "[un]subscribe" (in the "body", not the subject !) To: r-help-request@stat.math.ethz.ch _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._