[Rd] Strict seq: a recommendation
Tony Plate
tplate at acm.org
Wed Aug 23 18:16:29 CEST 2006
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
*:*)' .
BTW, it would probably be nice for a seqStrict() function to return a
vector of the same storage mode as seq(), e.g.:
> storage.mode(seq(len=0))
[1] "integer"
> storage.mode(1:3)
[1] "integer"
> n <- 3
> storage.mode(n)
[1] "double"
> storage.mode(1:n)
[1] "integer"
> storage.mode(c())
[1] "NULL"
>
-- Tony Plate
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.
>
> On the other hand, if you view this
> construction as a translation of the C code:
> for(m = beg; m < end; m++)
> ...
>
> then the semantics of C/C++ is not
> respected, because the code in ... is
> not executed when beg > end in
> the case of C/C++.
>
> To get the proper C/C++ semantics I
> use the following replacement for seq:
>
> seqStrict <- function(beg, end, step=1) {
> if((beg >= end && step > 0) || (beg <= end && step < 0))
> val <- c() # null vector
> else
> val <- seq(beg,end,step)
> val
> }
>
> Perhaps it would be useful to add an option to
> seq, so seq(beg,end,strict=TRUE) amounts to
> the same thing as using seqStrict(beg,end).
>
> ds
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>
More information about the R-devel
mailing list