[R] seq(2,5,-2) not an error but NULL
Duncan Murdoch
murdoch at stats.uwo.ca
Mon Mar 27 14:23:23 CEST 2006
On 3/27/2006 4:41 AM, Christian Hoffmann wrote:
> Hi,
>
> This may belong more to r-develop, but general discussion may be useful
> (for the how many-th time ?)
>
> seq(2,5,-2)
> seq(5,2,2)
>
> both result in
>
> Error in seq.default(2, 5, -2) : wrong sign in 'by' argument
>
> But often, if not always, mathematicians and programmers want a
> behaviour e.g. in for loops, where this statement results in an empty
> statement, that is
>
> for (ii in seq(2,5,-2)) print(ii)
>
> were equivalent to
>
> for (ii in NULL) print(ii).
>
> The relevant part in seq.default is now
>
> if (n < 0)
> stop("wrong sign in 'by' argument")
>
> but could be changed by option to
>
> return(NULL)
>
> I think there should be an option to seq requiring this behaviour, or a
> specific function, may be even a special operator, e.g. %;%:
>
> 3;5 resulting in NULL.
>
> What do you think?
If you want optional behaviour, the easiest way is to write your own
wrapper function. E.g.
emptyseq <- function(from, to, by) {
if ((to-from)*by < 0) return(NULL)
else return(seq(from, to, by))
}
I don't think this is a desirable default, though. We already have a
special way to handle the most common case, i.e.
seq(1, length(x), 1)
should be written as
seq(along=x))
to handle the length(x) == 0 case the way you're requesting.
But I'm not so sure that seq(2,5,-2) should really be NULL; it looks
much more like an error to me. You say mathematicians and programmers
want this behaviour, but I really can't think of any examples other than
the one above.
As a general principle, I think it's better to throw an error on
ambiguous or apparently erroneous code rather than always returning an
answer. If the code can be made unambiguous, it should be. (R doesn't
always follow this principle; for example, recycling of vectors of
lengths bigger than 1 is probably an error at least as often as it's
intended.)
Duncan Murdoch
More information about the R-help
mailing list