[Rd] Strict seq: a recommendation

Bill Dunlap bill at insightful.com
Wed Aug 23 19:46:54 CEST 2006


On Wed, 23 Aug 2006, Tony Plate wrote:

> The way I avoid this problem is to use seq(len=n) instead of 1:n.
> Of course, the syntax can get inconvenient for starting values other
> than 1 or 0, but I haven't found that to be much of a problem.
>
> Using the idiom 1:n in programming (as opposed to interactive use)
> results in errors commonly enough that it probably wouldn't be a bad
> idea for quality control tools to warn about contructs like 'for (* in
> *:*)' .

You do pay a time price for using seq(length=n) instead
of 1:n, because : is a .Primitive and seq() is not.  E.g.,
   R> unix.time(for(i in 1:1e6)1:5)
   [1] 1.570 0.020 1.636 0.000 0.000
   R> unix.time(for(i in 1:1e6)seq(length=5))
   [1] 51.120  0.040 51.682  0.000  0.000
   R> cat(version$version.string, "\n")
   version 2.4.0 Under development (unstable) (2006-06-29 r38459)
Long ago (using S, not S-PLUS or R) I tried introducing new operators,
"+:" and "-:", for ascending and descending sequences.  E.g., 1+:0
returned integer(0), not c(1,0).  They were ".Internal" like ":" was.
They were fast and avoided the pitfall of 1:length(x), but no one liked
adding new operators.  Perhaps seq() should become a .Internal (or
.Primitive).

Until then, heavily used functions can use something like
   if(n>0) for(i in 1:n) { ... }
instead of
   for(i in seq(length=n)) { ... }
to get both correctness and speed.

> Dominick Samperi wrote:
> > In for loops of the form:
> > for(m in seq(beg,end))
> > ...
> >
> > when beg > end, the default behavior is
> > to decrement, and the action described
> > by ... is executed at least once.

----------------------------------------------------------------------------
Bill Dunlap
Insightful Corporation
bill at insightful dot com
360-428-8146

 "All statements in this message represent the opinions of the author and do
 not necessarily reflect Insightful Corporation policy or position."



More information about the R-devel mailing list