[R] how to get empty sequence for certain bounds

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Nov 15 18:39:22 CET 2006


On Wed, 15 Nov 2006, Tamas K Papp wrote:

> Hi,
>
> I have encountered this problem quite a few times and thought I would
> ask.
>
> Let's say that I have two endpoints, a and b, which are integers.  If
> a <= b, I would like to get a:b, but if a > b, then numeric(0), for
> example:
>
> myseq(3,5) => 3:5
> myseq(3,3) => 3
> myseq(3,2) => numeric(0)
>
> The operator : just gives decreasing sequences in the latter case, and
> I could not coax seq into doing this either (of course the
> documentation is correct, it never claims that I could).  Should I
> just write my own function, or is there a standard R way to do this?

This has been discussed fairly recently, so see the list archives.

myseq <- function(m, n) m - 1 + seq_len(max(n-m+1, 0))

looks about right.  Note that this is a little strange, as you want to 
include the left endpoint sometimes and not others.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list